-
Notifications
You must be signed in to change notification settings - Fork 21
/
translation_worker.js
1302 lines (1031 loc) · 43.5 KB
/
translation_worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//import { pipeline } from './tjs/transformers.js';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from '@xenova/transformers';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from './tjs/transformers.js';
//import './shared_utils.js';
import { pipeline, env } from './tjs/transformers.min.js';
import './js/eld.M60.min.js';
////console.log("translation worker: loaded language detection script. eld: ", eld);
//import { registerPromiseWorker } from './js/promise-worker.register.js';
//console.log("HELLO FROM TRANSLATION WORKER");
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
env.backends.onnx.wasm.simd = true;
self.device = 'webgpu';
//const MAX_NEW_TOKENS = 256;
self.supports_web_gpu16 = false;
self.supports_web_gpu32 = false;
self.running = false;
self.interrupted = false;
self.force_webgpu = false; // test setting for ONNX Debugging
//elf.output_so_far = '';
//self.task = null;
async function hasFp16() {
try {
const adapter = await navigator.gpu.requestAdapter();
if (typeof adapter != 'undefined' && adapter != null && typeof adapter.features != 'undefined') {
self.supports_web_gpu32 = true;
}
self.supports_web_gpu16 = adapter.features.has('shader-f16');
return adapter.features.has('shader-f16');
} catch (e) {
return false;
}
}
await hasFp16();
// self.supports_web_gpu16 ??= await hasFp16();
console.log("TRANSLATION WORKER: self.supports_web_gpu16: ", self.supports_web_gpu16);
console.log("TRANSLATION WORKER: self.supports_web_gpu32: ", self.supports_web_gpu32);
if(self.supports_web_gpu16 == false && self.supports_web_gpu32 == false){
//console.log("TRANSLATION WORKER: NO WEB GPU");
self.device = 'wasm';
}
else{
//console.log("TRANSLATION WORKER: WEB GPU IS AVAILABLE");
self.device = 'webgpu';
}
//console.log("TRANSLATION WORKER: env.backends.onnx.wasm.proxy before: ", env.backends.onnx.wasm.proxy);
env.backends.onnx.wasm.proxy = self.device !== 'webgpu';
//console.log("TRANSLATION WORKER: env.backends.onnx.wasm.proxy after: ", env.backends.onnx.wasm.proxy);
// BART50 needs longer codes
self.bart_lookup = {
"ar": "ar_AR",
"cs": "cs_CZ",
"de": "de_DE",
"en": "en_XX",
"es": "es_XX",
"et": "et_EE",
"fi": "fi_FI",
"fr": "fr_XX",
"gu": "gu_IN",
"hi": "hi_IN",
"it": "it_IT",
"ja": "ja_XX",
"kk": "kk_KZ",
"ko": "ko_KR",
"lt": "lt_LT",
"lv": "lv_LV",
"my": "my_MM",
"ne": "ne_NP",
"nl": "nl_XX",
"ro": "ro_RO",
"ru": "ru_RU",
"si": "si_LK",
"tr": "tr_TR",
"vi": "vi_VN",
"zh": "zh_CN"
}
function isPromise (obj) {
// via https://unpkg.com/[email protected]/index.js
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
function registerPromiseWorker (callback) {
function postOutgoingMessage (e, messageId, error, result) {
function postMessage (msg) {
/* istanbul ignore if */
if (typeof self.postMessage !== 'function') { // service worker
e.ports[0].postMessage(msg)
} else { // web worker
self.postMessage(msg)
}
}
if (error) {
/* istanbul ignore else */
if (typeof console !== 'undefined' && 'error' in console) {
// This is to make errors easier to debug. I think it's important
// enough to just leave here without giving the user an option
// to silence it.
console.error('Promise worker caught an error:', error)
}
postMessage([messageId, {
message: error.message
}])
} else {
postMessage([messageId, null, result])
}
}
function tryCatchFunc (callback, message) {
try {
return { res: callback(message) }
} catch (e) {
return { err: e }
}
}
function handleIncomingMessage (e, callback, messageId, message) {
////console.log("registerPromiseWorker: in handleIncomingMessage")
var result = tryCatchFunc(callback, message)
if (result.err) {
postOutgoingMessage(e, messageId, result.err)
} else if (!isPromise(result.res)) {
postOutgoingMessage(e, messageId, null, result.res)
} else {
result.res.then(function (finalResult) {
postOutgoingMessage(e, messageId, null, finalResult)
}, function (finalError) {
postOutgoingMessage(e, messageId, finalError)
})
}
}
function onIncomingMessage (e) {
////console.log("translation worket: registerPromiseWorker: onIncomingMessage: e.data: ", e.data);
var payload = e.data
if (!Array.isArray(payload) || payload.length !== 2) {
//console.log("onIncomingMessage: ignoring message with wrong format");
// message doens't match communication format; ignore
return
}
var messageId = payload[0]
var message = payload[1]
if (typeof callback !== 'function') {
postOutgoingMessage(e, messageId, new Error(
'Please pass a function into register().'))
} else {
handleIncomingMessage(e, callback, messageId, message)
}
}
self.addEventListener('message', onIncomingMessage)
}
////console.log("TRANSLATION (PROMISE) WORKER EXISTS");
////console.log("TRANSLATION (PROMISE) WORKER: registerPromiseWorker: ", registerPromiseWorker);
// Do local model checks
//env.allowLocalModels = true;
//env.allowRemoteModels = false;
let pipelines = {};
function check_if_already_target_language(paragraph,output_language){
const language_detection_result = eld.detect(paragraph);
if(typeof language_detection_result.language == 'string'){
const detected_language = language_detection_result.language;
////console.log("TRANSLATION WORKER: check_if_already_target_language: detected_language: ", detected_language);
if(language_detection_result.isReliable() && output_language.toLowerCase() == detected_language.toLowerCase()){
return true
}
}
return false
}
function extract_sentences(text, output_language){
//console.log("translation worker: in extract_sentences. text,output_language: ", text, output_language);
if(typeof text != 'string'){
console.error("extract_sentences: returning empty array, as text was not a string: ", text);
return [];
}
function is_number(char) {
return !isNaN(parseInt(char));
}
function is_letter(character) {
return character.length === 1 && character.match(/[a-z]/i);
}
/*
if(text.indexOf('<context>') != -1 && text.indexOf('</context>') != -1 ){
let context_text = text.split('<context>')[1];
if(text.indexOf('</context>') != -1){
context_text = context_text.split('</context>')[0];
const language_detection_result = eld.detect(context_text);
if(typeof language_detection_result.language == 'string'){
detected_language = language_detection_result.language;
//text.replace('<context>' + context_text + '')
}
}
}
*/
let sentences = []; // this will be filled with actual individual sentences, and then returned
if(text.indexOf('🕰️ ') != -1){ // && text.indexOf(' ( T+ ') != -1 && text.indexOf(' )') != -1
////console.log("translation worker: it looks like the text contains 🕰️ scribe timestamps");
}
let lines = text.split("\n");
let timestamp_lines_removed = 0;
////console.log("translation worker: extract_sentences: number of lines to check: ", lines.length);
if(lines.length){
let ok_line = '';
for(let l = lines.length - 1; l >= 0; l--){
//console.log("translation worker: extract_sentences: l: ", l, lines[l].charAt(2));
if(typeof lines[l] == 'string'){
//if(lines[l].startsWith('🕰️ ') && lines[l].endsWith(' )') && lines[l].indexOf(' ( T+ ') != -1){
if(lines[l].startsWith('🕰️ ') && !isNaN(lines[l].charAt(3))){
////console.log("extract_sentences: removing timestamp line from source_text: ", lines[l]);
lines.splice(l,1);
l--;
timestamp_lines_removed++;
}
else if(lines[l].charAt(2) == ':' && lines[l].charAt(5) == ':' && lines[l].indexOf(' --> ') != -1){
////console.log("extract_sentences: removing timestamp line from source_text: ", lines[l]);
lines.splice(l,1);
l--;
timestamp_lines_removed++;
}
else if( (lines[l].trim()).length < 2){
////console.log("translation worker: extract_sentences: removing empty line from lines: ", lines[l]);
lines.splice(l,1);
l--;
}
else if(lines[l].trim() == '<context>' || lines[l].trim() == '</context>'){
////console.log("translation worker: extract_sentences: removing <context> tag line from lines: ", lines[l]);
lines.splice(l,1);
l--;
}
else{
let letter_count = 0;
for(let c = 0; c < lines[l].length; c++){
if(is_letter(lines[l].charAt(c))){
letter_count++;
if(letter_count > 2){
break
}
}
}
if(letter_count < 3 && lines[l].length > 10){
lines.splice(l,1);
l--;
}
}
}
else{
console.error("extract_sentences: lines[l] was not a string??", l, lines, lines[l]);
}
}
}
////console.log("next: removing empty strings from sentences"); // already done?
//console.log("translation_worker: lines: ", lines);
if(lines.length){
for(let l = lines.length - 1; l >= 0; l--){
if(lines[l].trim().length < 2){
////console.log("extract_sentences: removed empty line from lines: ", lines[l]);
lines.splice(l,1);
l--;
}
else if(lines[l].trim() == '""'){
lines.splice(l,1);
l--;
}
}
}
/*
////console.log("extract_sentences: number of lines after stripping: ", lines.length);
if(lines.length > 3 && timestamp_lines_removed > 3){
////console.log("translate_selection: setting lines as prepared_lines: ", lines);
prepared_lines = lines;
}
*/
////console.log("extract_sentences: number of lines to check 2: ", lines.length);
//console.log("translation_worker: lines again: ", lines);
for(let l = 0; l < lines.length; l++){
let paragraph = lines[l];
let start = 0;
if(paragraph.length > 50 && check_if_already_target_language(paragraph,output_language) == true){
console.warn("TRANSLATION WORKER: skipping paragraph that already seems to be in the desired language: ", paragraph);
continue
}
/*
let spaces_count = lines[l].split(" ").length - 1; // Chinese and Japanese don't use spaces
if(spaces_count == 0 && lines[l].length > 20){
continue
}
if(spaces_count > 5 && lines[l].length < 300){
sentences.push(lines[l]);
continue
}
*/
// Skip lines that contain a lot of untranslatable characters
let non_letters = '@#$%ˆ&*()_-+=|.~[]<>{}"';
let non_letter_count = 0;
let cleaner_line = lines[l].replaceAll(/(?:https?|ftp):\/\/[\n\S]+/g, '');
if(cleaner_line != lines[l]){
////console.log("cleaner_line: ", cleaner_line);
}
for(let c = 0; c < cleaner_line.length; c++){
const char = cleaner_line[c];
for(let n = 0; n < non_letters.length; n++){
if(char == non_letters[n]){
non_letter_count++;
break
}
}
}
////console.log("non_letter percentage: ", Math.round((non_letter_count/cleaner_line.length) * 100) + '%');
if(non_letter_count * 4 >= cleaner_line.length){
console.warn("translation_worker: skipping line that contains too many non-characters: ", lines[l]);
continue
}
paragraph = paragraph.replace(/([a-z][a-z])(\.\"\s)([A-Z][a-z])/g, '$1."=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\"\.\s)([A-Z][a-z])/g, '$1".=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\?\"\s)([A-Z][a-z])/g, '$1?"=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\"\?\s)([A-Z][a-z])/g, '$1"?=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\!\"\s)([A-Z][a-z])/g, '$1!"=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\"\!\s)([A-Z][a-z])/g, '$1"!=|=sentence_break=|=$3');
paragraph = paragraph.replace(/([a-z][a-z])(\.\s)([A-Z][a-z])/g, "$1. =|=sentence_break=|=$3");
paragraph = paragraph.replace(/([a-z][a-z])(\!\s)([A-Z][a-z])/g, "$1! =|=sentence_break=|=$3");
paragraph = paragraph.replace(/([a-z][a-z])(\?\s)([A-Z][a-z])/g, "$1? =|=sentence_break=|=$3");
////console.log("paragraph broken up: ", paragraph);
if(paragraph.indexOf('=|=sentence_break=|=') != -1){
const paragraph_parts = paragraph.split('=|=sentence_break=|=');
sentences = sentences.concat(paragraph_parts);
/*
for(let s = 0; s < paragraph_parts.length; s++){
if(paragraph_parts[s].length > 1){
sentences.push(s);
}
}
*/
}
else{
sentences.push(paragraph);
}
/*
if(paragraph.length < 4 && l < (lines.length - 1) && paragraph.indexOf('.') == -1 && paragraph.indexOf('!') == -1 && paragraph.indexOf('?') == -1){
////console.log("extract_sentences: could scoot this very short paragraph over so it becomes part of the next one: ", lines[l], lines[l+1]);
//lines[l+1] = lines[l] + ' ' + lines[l+1];
}
*/
/*
for (let i = 0; i < paragraph.length; i++) {
else if (paragraph[i] === '.' || paragraph[i] === '?' || paragraph[i] === '!') {
let sentence = paragraph.substring(start, i + 1).trim();
if(sentence.length < 3){ // try to continue if the sentence is very short
////console.log("very short sentence, will try to get a longer one")
if( (paragraph.length - i) < 5){ // almost at the end
sentence = paragraph.substring(start).trim(); // grab everything until the end
sentences.push(sentence);
break
}
else{
////console.log("extract_sentences: aiming for a longer sentence");
}
}
else if(paragraph.length - i > 1){ // almost at the end
//if(paragraph[i+1] === ' '){
if(is_number(paragraph[i+1])){
}
else{
sentences.push(sentence);
start = i + 1;
}
}
else{
sentence = paragraph.substring(start).trim(); // grab everything until the end
sentences.push(sentence);
break
}
}
}
*/
}
if(sentences.length){
for(let l = sentences.length - 1; l >= 0; l--){
if((sentences[l].trim()).length < 2){
////console.log("extract_sentences: removed empty line from sentences: ", sentences[l]);
sentences.splice(l,1);
l--;
}
}
}
//console.log("extract_sentences: final sentences: ", JSON.stringify(sentences));
return sentences
}
/*
async function go() {
//let pipe = await pipeline('translation', 'onnx/quantized/Helsinki-NLP/opus-mt-nl-en');
let pipe = await pipeline('translation', 'Xenova/opus-mt-nl-en'); // ,{ dtype: 'fp32' }
let translation = await pipe("Wat is de hoofdstad van Frankrijk?");
//console.log("translation worker: ", translation);
return translation;
}
go();
*/
/*
// Use the Singleton pattern to enable lazy construction of the pipeline.
class MyTextToSpeechPipeline {
static BASE_URL = 'https://huggingface.co/datasets/Xenova/cmu-arctic-xvectors-extracted/resolve/main/';
static model_id = 'Xenova/speecht5_translation';
static vocoder_id = 'Xenova/speecht5_hifigan';
static tokenizer_instance = null;
static model_instance = null;
static vocoder_instance = null;
static async getInstance(progress_callback = null) {
if (this.tokenizer_instance === null) {
this.tokenizer = AutoTokenizer.from_pretrained(this.model_id, { progress_callback });
}
if (this.model_instance === null) {
this.model_instance = SpeechT5ForTextToSpeech.from_pretrained(this.model_id, {
//quantized: false,
dtype: 'fp32',
progress_callback,
});
}
if (this.vocoder_instance === null) {
this.vocoder_instance = SpeechT5HifiGan.from_pretrained(this.vocoder_id, {
//quantized: false,
dtype: 'fp32',
progress_callback,
});
}
return new Promise(async (resolve, reject) => {
const result = await Promise.all([
this.tokenizer,
this.model_instance,
this.vocoder_instance,
]);
self.postMessage({
status: 'ready',
});
resolve(result);
});
}
static async getSpeakerEmbeddings(speaker_id) {
// e.g., `cmu_us_awb_arctic-wav-arctic_a0001`
const speaker_embeddings_url = `${this.BASE_URL}${speaker_id}.bin`;
////console.log("translation_worker2: speaker_embeddings_url: ", speaker_embeddings_url);
const speaker_embeddings = new Tensor(
'float32',
new Float32Array(await (await fetch(speaker_embeddings_url)).arrayBuffer()),
[1, 512]
)
return speaker_embeddings;
}
}
// Mapping of cached speaker embeddings
const speaker_embeddings_cache = new Map();
*/
/*
// Use the Singleton pattern to enable lazy construction of the pipeline.
class PipelineSingleton {
static task = 'text-classification';
static model = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
static instance = null;
static async getInstance(progress_callback = null) {
if (this.instance === null) {
this.instance = pipeline(this.task, this.model, { progress_callback });
}
return this.instance;
}
}
*/
registerPromiseWorker(function (message) {
//console.log("registerPromiseWorker: translation worker got message: ", message);
////console.log("WORKER: registerPromiseWorker: GOT MESSAGE: ", message); // { hello: 'world', answer: 42, 'this is fun': true }
////console.log("TRANSLATION WORKER RECEIVED TASK");
////console.log("TRANSLATION message: ", message);
/*
if(typeof event.data.cache_name == 'string'){
////console.log("translation_worker: setting cache_name to: ", event.data.cache_name)
cache_name = event.data.cache_name;
}
*/
return new Promise((resolve, reject) => {
try{
if(typeof message.task != 'undefined' && message.task != null){
//console.log("TRANSLATION WORKER: received a task: ", message.task);
//return {"error":"translation worker: this is a test"};
/*
if(typeof message.task.source_text == 'string' && message.task.source_text.length){
////console.log("TRANSLATION_WORKER: task has simple source_text property, using that as the input source_text: ", message.task.source_text);
source_text = message.task.source_text; // simpler shortcut option for simple tasks
}
else
*/
let source_text = null;
let translated_property = null;
let translated_property_index = null;
self.running = true;
self.interrupt = false;
self.stop = false;
////console.log("TRANSLATION WORKER: pre-existing pipelines: ", Object.keys(pipelines));
if(typeof message.task.force_webgpu == 'boolean'){
self.force_webgpu = message.task.force_webgpu;
}
if(typeof message.task.silent == 'boolean' && message.task.silent == true && typeof message.task.results != 'undefined' && Array.isArray(message.task.results) && message.task.results.length ){
source_text = message.task.results[message.task.results.length - 1];
translated_property = 'result';
translated_property_index = message.task.results.length - 1;
////console.log("TRANSLATION WORKER: translating result at index: ", translated_property_index);
}
else if(typeof message.task.q != 'undefined' && message.task.q.length == 0 && typeof message.task.silent != 'undefined' && typeof message.task.return_language == 'string' && Array.isArray(message.task.results) && message.task.results.length){
source_text = message.task.results[message.task.results.length - 1];
translated_property = 'result';
translated_property_index = message.task.results.length - 1;
////console.log("TRANSLATION WORKER: translating post-translation return journey result at index: ", translated_property_index);
}
else if(typeof message.task.text == 'string' && message.task.text.length){
////console.log("TRANSLATION_WORKER: task had no source_text, but does have text. Using that as translation input. ", message.task.text);
source_text = message.task.text;
translated_property = 'text';
}
else if(typeof message.task.original_prompt == 'undefined' && typeof message.task.prompt == 'string' && message.task.prompt.length){
source_text = message.task.prompt;
translated_property = 'prompt';
}
else if(typeof message.task.results != 'undefined' && Array.isArray(message.task.results) && message.task.results.length){
source_text = message.task.results[message.task.results.length - 1];
translated_property = 'result';
translated_property_index = message.task.results.length - 1;
////console.log("TRANSLATION WORKER: translating result at index: ", translated_property_index);
}
////console.log("source_text came from this task property: ", translated_property);
//console.log("translation worker: source_text: ", source_text);
if(source_text){
let input_language = null;
if(typeof message.task.input_language == 'string'){
input_language = message.task.input_language.toLowerCase();
}
let output_language = null;
if(typeof message.task.output_language == 'string'){
output_language = message.task.output_language.toLowerCase();
}
//console.log("TRANSLATION WORKER: input_language: ", input_language);
//console.log("TRANSLATION WORKER: output_language: ", output_language);
//await caches.open("transformers").then((my_cache) => my_cache.add('./tjs/transformers.js'));
if(typeof input_language != 'string' || typeof output_language != 'string'){
console.error("TRANSLATION WORKER: input or output language was null: ", input_language, output_language);
self.postMessage({
task: message.task,
status: 'error',
error: 'input or output language was not clear',
translation: source_text
});
reject(false);
return
}
let hf_model_url = 'Xenova/opus-mt-' + input_language + '-' + output_language;
if(typeof message.task.translation_details != 'undefined' && message.task.translation_details != null){
if(typeof message.task.translation_details.model == 'string'){
//console.log("TRANSLATION WORKER: found model name in translation_details: ", message.task.translation_details.model);
hf_model_url = message.task.translation_details.model;
}
}
// TEST
//hf_model_url = 'Xenova/mbart-large-50-many-to-many-mmt';
/*
let translator = await pipeline(
"translation",
"Xenova/mbart-large-50-many-to-many-mmt"
);
*/
////console.log("TRANSLATION WORKER: hf_model_url: ", hf_model_url);
function progressCallback(x){
//console.log("translation worker: download progressCallback: ", x);
self.postMessage(x);
}
let previous_doc_cursor = 0;
let done_so_far = '';
let so_far = '';
let ahead_text = '' + source_text;
let constructed_text = '';
//let previous_constructed_text = '';
let work_text = '' + source_text;
let to_go_part = '' + source_text;
let old_text = '' + source_text;
let new_text = '' + source_text;
let sentences = [];
if(typeof message.task.sentences_to_translate != 'undefined'){
//console.log("TRANSLATION WORKER: TASK HAS LIST OF PRE-SPLIT SENTENCES_TO_TRANSLATE: ", message.task.sentences_to_translate);
sentences = message.task.sentences_to_translate;
}
else{
sentences = extract_sentences(source_text,output_language);
//console.log("TRANSLATION WORKER: used extract_sentences. Sentences list is now: ", sentences);
}
console.warn("TRANSLATION WORKER: sentences to translate: ", sentences.length, sentences);
let s = 0;
const do_translation_loop = () => {
console.warn("TRANSLATION WORKER: in do_translation_loop. s: ", s, " of ", sentences.length);
if(self.interrupt){
console.error("TRANSLATION WORKER: INTERRUPTED");
self.postMessage({
task: message.task,
status: 'translation_interrupted',
translated_property:translated_property,
translated_property_index:translated_property_index,
translation: constructed_text
});
if(self.stop){
clean_up();
}
reject(false);
}
else if(s < sentences.length){
let sentence = sentences[s]; //.trim();
s++;
if(sentence.length > 1){
if(ahead_text.indexOf(sentence) == -1){
console.error("TRANSLATION WORKER: sentence to translate was not found in ahead_text:\nSENTENCE: ", sentence, "\nAHEAD_TEXT: ", ahead_text);
self.postMessage({
task: message.task,
status: 'error',
error: 'sentence to translate was not found: ' + sentence,
ahead_text: ahead_text,
translated_property:translated_property,
translated_property_index:translated_property_index,
translation: constructed_text
});
return
}
const pre_part = ahead_text.substr(0,ahead_text.indexOf(sentence));
//console.log("pre_part: -->" + pre_part + "<--");
////console.log("next cursor with pre_part + sentence: ", ahead_text.indexOf(sentence) + sentence.length);
ahead_text = ahead_text.substr(ahead_text.indexOf(sentence) + sentence.length);
//console.log("ahead text has shrunk to: -->" + ahead_text);
//console.log("TRANSLATION WORKER: TRANSLATING: SENTENCE:", sentence);
self.postMessage({
task: message.task,
translated_property:translated_property,
translated_property_index:translated_property_index,
sentences_count:s,
sentences_total:sentences.length,
status: 'translation_progress',
sentence:sentence,
sentence_selection:{'from': (constructed_text + pre_part).length, 'to': (constructed_text + pre_part + sentence).length}
});
let translation_settings = {};
if(typeof input_language == 'string' && typeof output_language == 'string'){
/*
const pipe = await pipeline('translation', 'Helsinki-NLP/opus-mt-en-mul');
const result = await pipe(">>jpn<< I love pizza", {
do_sample: false,
num_beams: 1
});
*/
// Small fix for BART // Xenova/mbart-large-50-many-to-many-mmt
if(hf_model_url.endsWith('mbart-large-50-many-to-many-mmt')){
//console.log("translation worker: looking up language code in bart_lookup table: " + input_language, bart_lookup);
if(typeof self.bart_lookup[input_language] != 'undefined'){
input_language = self.bart_lookup[input_language];
}
if(typeof self.bart_lookup[output_language] != 'undefined'){
output_language = self.bart_lookup[output_language];
}
}
// Small fix for M2M
else if(hf_model_url.endsWith('m2m100_418M')){
if(input_language == 'jp'){
input_language = 'jap';
}
if(output_language == 'jp'){
output_language = 'jap';
}
}
if(hf_model_url.endsWith('-mul-en')){
if(input_language.length != 3){
console.error("-mul-en: input language code is too short: ", input_language);
if(typeof message.task.translation_details != 'undefined' && typeof message.task.translation_details != null && typeof message.task.translation_details.language == 'string' && message.task.translation_details.language.length == 3){
input_language = message.task.translation_details.language;
console.error("-mul-en: input language code replaced with: ", input_language);
}
}
if(input_language.length != 3){
console.error("TRANSLATION WORKER: -mul-en: input language should be three letters long: ", input_language);
}
output_language = 'eng';
}
if(hf_model_url.endsWith('-en-mul')){
if(output_language.length != 3){
console.error("-mul-en: input language code is too short: ", output_language);
if(typeof message.task.translation_details != 'undefined' && typeof message.task.translation_details != null && typeof message.task.translation_details.language == 'string' && message.task.translation_details.language.length == 3){
output_language = message.task.translation_details.language;
console.error("-en-mul: output language code replaced with: ", output_language);
}
}
if(output_language.length != 3){
console.error("TRANSLATION WORKER: -en-mul: output language should be three letters long: ", output_language);
}
input_language = 'eng';
}
// Open MT MUL (currently not used)
if(hf_model_url.endsWith('-mul-en') || hf_model_url.endsWith('-en-mul')){
/*
if(input_language == 'en'){
input_language = 'eng';
if(output_language.length != 3){
console.error("TRANSLATION WORKER: output language should be three letters long: ", output_language);
}
}
if(output_language == 'en'){
output_language = 'eng';
if(input_language.length != 3){
console.error("TRANSLATION WORKER: input language should be three letters long: ", input_language);
}
}
*/
/*
if(input_language == 'ces'){
input_language = 'ce';
if(output_language.length != 3){
console.error("TRANSLATION WORKER: CES test: ", input_language, " -> ", output_language);
}
}
*/
if(hf_model_url.endsWith('-mul-en')){
////console.log("TRANSLATION WORKER: MUL -> EN");
sentence = '>>' + input_language + '<< ' + sentence;
}
else if(hf_model_url.endsWith('-en-mul')){
////console.log("TRANSLATION WORKER: EN -> MUL");
sentence = '>>' + output_language + '<< ' + sentence;
}
}
else{
//translation_settings['src_lang'] = 'en_XX' //input_language;
//translation_settings['tgt_lang'] = 'nl_XX' //output_language;
translation_settings['src_lang'] = input_language //input_language;
translation_settings['tgt_lang'] = output_language //output_language;
}
}
//console.log("TRANSLATION_WORKER: hf_model_url: ", hf_model_url);
//console.log("TRANSLATION_WORKER: translation_settings: ", translation_settings);
//translation_settings['src_lang'] = 'en_XX' //input_language;
//translation_settings['tgt_lang'] = 'nl_XX' //output_language;
// final cleaning of the string before translating it
sentence = sentence.replaceAll('\"','"');
sentence = sentence.replaceAll('\t',' ');
//sentence = sentence.trim();
//console.log("trimmed sentence: -->" + sentence + "<--");
//console.log("TRANSLATION WORKER: TRANSLATING: FINAL SENTENCE:", sentence);
pipelines[hf_model_url].pipe(sentence,translation_settings)
.then((translation) => {
//console.log("\nTRANSLATION WORKER: TRANSLATED! \nfrom: ", sentence, "\n to: ", translation, "\n");
try{
//console.log("translation[0].translation_text: ", translation[0].translation_text);
}
catch(err){
console.error("translation result was not an array: ", err);
}
let extra_space = '';
if((constructed_text + pre_part).length && !(constructed_text + pre_part).endsWith(' ') && !(constructed_text + pre_part).endsWith('\n') && !translation[0].translation_text.startsWith(' ') && translation[0].translation_text.length && !translation[0].translation_text.startsWith('\n')){
//console.log("translation worker: injecting an extra space");
extra_space = ' ';
}
self.postMessage({
task: message.task,
translated_property:translated_property,
translated_property_index:translated_property_index,
sentences_count:s,
sentences_total:sentences.length,
status: 'chunk',
input_sentence:sentence,
output_sentence:translation[0].translation_text,
response_so_far:constructed_text + pre_part,
pre_part:pre_part,
chunk:pre_part + extra_space + translation[0].translation_text,
old_text:constructed_text,
new_text:constructed_text + pre_part + extra_space + translation[0].translation_text,
});
constructed_text += pre_part;
if(typeof pre_part == 'string' && typeof translation[0].translation_text == 'string'){
//console.log("TRANSLATION WORKER: JOINING: ", pre_part + "-XXX-" + translation[0].translation_text.substr(0,10) + "...");
}
constructed_text = constructed_text + extra_space + translation[0].translation_text;
//previous_constructed_text = constructed_text;
////console.log("NEW constructed_text: ", constructed_text);
do_translation_loop();
return
})
.catch((err) => {
console.error("TRANSLATION WORKER: pipe: caught translation error. err: ", err);
self.postMessage({
task: message.task,
status: 'error',
error: '' + err,
translated_property:translated_property,
translated_property_index:translated_property_index,
translation: constructed_text
});
reject(err);
})
}
else{
console.warn("TRANSLATION WORKER: Sentence was too short to translate? sentence: ", sentence);
if(s + 1 < sentences.length){
do_translation_loop();
}
else if(s == 0){
// basically no sentences to translate
self.postMessage({
task: message.task,
status: 'error',
error: 'Sentence was too short to translate, and no other sentences remain'
});
reject(false);
}
else{
reject(false);
}
return
}