-
Notifications
You must be signed in to change notification settings - Fork 21
/
translate_premium.html
957 lines (930 loc) · 30.1 KB
/
translate_premium.html
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
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<meta name="copyright" content="© 2020 Steve Seguin" />
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon" />
<!-- Primary Meta Tags -->
<title>CAPTION.Ninja - translate</title>
<meta name="title" content="CAPTION.Ninja" />
<meta name="description" content="This is a free-to-use captioning tool for OBS. Speech-to-text is done using Machine Learning" />
<meta name="author" content="Steve Seguin" />
<style>
@font-face {
font-family: 'Cousine';
src: url('fonts/Cousine-Bold.ttf') format('truetype');
}
:root {
--primary-color: #2498Eb;
--secondary-color: #2c3e50;
--background-color: #0000;
--text-color: #333;
--border-radius: 4px;
--cc-background: #000000;
--cc-text-color: #ffffff;
--cc-font-size: 24px;
--cc-line-height: 1.2;
}
body {
font-family: 'Arial', sans-serif;
line-height: 1.6;
color: var(--text-color);
background-color: var(--background-color);
margin: 0;
padding: 20px;
}
h3 {
color: var(--secondary-color);
border-bottom: 2px solid var(--primary-color);
padding-bottom: 10px;
}
a {
color: var(--primary-color);
text-decoration: none;
font-weight:600;
transition: color 0.3s ease;
}
a:hover {
color: var(--secondary-color);
}
.output {
font-family: Cousine, monospace;
margin-top:15px;
color: black;
min-height: 120px;
font-size: 3.2em;
line-height: 1.1em;
letter-spacing: 0.0em;
padding: 0em;
padding-top:10px;
text-shadow: 0.05em 0.05em 0px rgba(255,255,255,1);
}
.output span {
background-color: black;
padding: 8px 8px 0px 8px;
margin:0;
}
/* Add this new style for the caption container */
#caption-container {
position: relative;
width: 100%;
height: 200px; /* Adjust as needed */
overflow: hidden;
background-color: var(--cc-background);
}
select, input[type="checkbox"] {
margin: 10px 0;
}
select {
padding: 5px;
border-radius: var(--border-radius);
border: 1px solid #ddd;
}
label {
display: inline-block;
margin-right: 15px;
}
textarea {
width: 700px;
display:block;
padding: 10px;
border: 1px solid #ddd;
border-radius: var(--border-radius);
height: 70px;
resize: all;
}
#status {
margin-top: 10px;
font-style: italic;
color: var(--secondary-color);
}
#whosekey {
display: inline-block;
padding: 5px 10px;
border-radius: var(--border-radius);
font-weight: bold;
}
#whosekey[style*="yellow"] {
background-color: #ffeeba;
color: #856404;
}
#whosekey[style*="green"] {
background-color: #d4edda;
color: #155724;
}
/* Responsive design */
@media (max-width: 768px) {
body {
padding: 10px;
}
textarea {
width: calc(100% - 20px);
}
.output span {
font-size: calc(var(--cc-font-size) * 0.8);
}
}
.github {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAd5JREFUOE+d1MurjlEUBvDfIZQZShEGmMhQiZGZlAlyK4eEAZHcyiVRyq1cUq5FwsD1MJGJiT/AzEzRcR8xMnGOW89pv9q9fScfe/J977o8e61nP2v16HzGYBWWYA4mlbBPeI5HuI9v7fSeDnircRqTh7msMX/ALtyr42rAEbiAzX8BaruTsx0/46gBL/0HWAMe0G01YNq8Xbz5PYuN2ISvCHc5oWEsruA69mJF8a0Mr6kwD/C64mw3zpSgCfjc6nE8vhRbAE+U/+8xI4DrcKNKOol9XfJ4CimgOb0BfIilxfIds/GyS8BZeIGRJf5BAN9gWjE8xcIuwZqwZ1hQPvoDOIBRxRCiN/wj4C30lpyBNmAmYNk/Aj7G4pIz2G75I6Y2Iu0CONwlZ2Ldcl+rqmjvWhdgCdmCi1Xs0KOsxc3C5WDhcw8uI9+dzugyVZFNw3/i1jTCfoVIJmo/VDiJeJ9gPX4U1CRHs4swrnXTO8xsZjlAd9GP+WU1zcPxckGde7WMZbvy5eirl8N5bMUxHMSvYdo9igMt3znsiK29vuLI1ojYU+2dwmWdnwv3V4YskozfUAGdFmzaz4KdgiM43KomNGTW32JnGd0/IZ0A48wrhpPMdFZ+feZievjqpILf7lRg3csIRqAAAAAASUVORK5CYII=");
background-color: #FFF !important;
width: 4px;
height: 12px;
background-repeat: no-repeat;
display: inline-block;
top: 2px;
position: relative;
left: 2px;
filter: invert(100%);
-webkit-filter: invert(100%);
}
div {
display:block;
}
</style>
</head>
<body>
<h3>This is a premium version of the captioning tool, with enhanced speech-to-text transcription & language translation.</h3>
The overlay-friendly output of the translated text is mirrored here: <a id="shareLink" href="overlay.html" target='_blank'>*ERROR GENERATING LINK*</a>.
<br /><br />
To use this app, accept the microphone permissions on page load and then just say something outloud. Once working, enable the transcription.
<br /><br />
Please note that this app uses your default microphone as the audio input source.
You sometimes can change the default audio source via the browser's setting, but you can also change it at your system level by changing the default recording device.
You can also change audio sources by using a Virtual Audio Cable, <a href='https://www.vb-audio.com/Cable/'> such as this one.</a>
Using it, it becomes possible to select other sources, including microphones, speakers, and other applications.
<br /><br />
The translation is powered by Google Cloud Translation, which <a href='https://console.cloud.google.com/apis/api/translate.googleapis.com/credentials' target="_blank">requires an API key. Get yours here.</a> Once you have it, add <b>&key=xxxxxxx</b> to this page's URL to set it. <br /><br /> You will need to get your own Google API key if you wish to use this premium version of the service. <a href='./translate'>The non-premium version is free of course.</a> Check out more options and details on <a href='https://github.com/steveseguin/captionninja'>GitHub</a>.
<br /><br />
<label>
From
<select id="lang-from" title="Set input language via the URL `&lang=en-US` option" name="from" class="lang-select"></select>
</label>
<label>
To
<select id="lang-to" name="to" class="lang-select"></select>
</label>
<label>
<input type="checkbox" id="fullContext" />
Translate with added context?
</label>
<label>
<input type="checkbox" id="enabledTranscription" />
<span style='color:green;'><b>Start</b></span> Translation Output (💸)
</label>
<label>
<input type="checkbox" id="incrementalUpdates" />
Enable incremental updates (💸💸💸)
</label>
<span id="whosekey"></span>
<br /><br />
<div class="footer" id="status"></div>
<textarea id="input" name="input"></textarea>
<br />
<div id="output" class="output"></div>
<script>
(function (w) {
w.URLSearchParams = w.URLSearchParams || function (searchString) {
var self = this;
self.searchString = searchString;
self.get = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(self.searchString);
if (results == null) {
return null;
}
else {
return decodeURI(results[1]) || 0;
}
};
};
})(window);
var urlParams = new URLSearchParams(window.location.search);
let version;
const status = function(message){document.getElementById("status").innerText = message;}
var apiKey = "";
var langs = {
"aa": "Afar",
"ab": "Abkhazian",
"ae": "Avestan",
"af": "Afrikaans",
"ak": "Akan",
"am": "Amharic",
"an": "Aragonese",
"ar": "Arabic",
"as": "Assamese",
"av": "Avaric",
"ay": "Aymara",
"az": "Azerbaijani",
"ba": "Bashkir",
"be": "Belarusian",
"bg": "Bulgarian",
"bh": "Bihari languages",
"bi": "Bislama",
"bm": "Bambara",
"bn": "Bengali",
"bo": "Tibetan",
"br": "Breton",
"bs": "Bosnian",
"ca": "Catalan; Valencian",
"ce": "Chechen",
"ch": "Chamorro",
"co": "Corsican",
"cr": "Cree",
"cs": "Czech",
"cu": "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic",
"cv": "Chuvash",
"cy": "Welsh",
"da": "Danish",
"de": "German",
"dv": "Divehi; Dhivehi; Maldivian",
"dz": "Dzongkha",
"ee": "Ewe",
"el": "Greek, Modern (1453-)",
"en": "English",
"eo": "Esperanto",
"es": "Spanish; Castilian",
"et": "Estonian",
"eu": "Basque",
"fa": "Persian",
"ff": "Fulah",
"fi": "Finnish",
"fj": "Fijian",
"fo": "Faroese",
"fr": "French",
"fy": "Western Frisian",
"ga": "Irish",
"gd": "Gaelic; Scomttish Gaelic",
"gl": "Galician",
"gn": "Guarani",
"gu": "Gujarati",
"gv": "Manx",
"ha": "Hausa",
"he": "Hebrew",
"hi": "Hindi",
"ho": "Hiri Motu",
"hr": "Croatian",
"ht": "Haitian; Haitian Creole",
"hu": "Hungarian",
"hy": "Armenian",
"hz": "Herero",
"ia": "Interlingua (International Auxiliary Language Association)",
"id": "Indonesian",
"ie": "Interlingue; Occidental",
"ig": "Igbo",
"ii": "Sichuan Yi; Nuosu",
"ik": "Inupiaq",
"io": "Ido",
"is": "Icelandic",
"it": "Italian",
"iu": "Inuktitut",
"ja": "Japanese",
"jv": "Javanese",
"ka": "Georgian",
"kg": "Kongo",
"ki": "Kikuyu; Gikuyu",
"kj": "Kuanyama; Kwanyama",
"kk": "Kazakh",
"kl": "Kalaallisut; Greenlandic",
"km": "Central Khmer",
"kn": "Kannada",
"ko": "Korean",
"kr": "Kanuri",
"ks": "Kashmiri",
"ku": "Kurdish",
"kv": "Komi",
"kw": "Cornish",
"ky": "Kirghiz; Kyrgyz",
"la": "Latin",
"lb": "Luxembourgish; Letzeburgesch",
"lg": "Ganda",
"li": "Limburgan; Limburger; Limburgish",
"ln": "Lingala",
"lo": "Lao",
"lt": "Lithuanian",
"lu": "Luba-Katanga",
"lv": "Latvian",
"mg": "Malagasy",
"mh": "Marshallese",
"mi": "Maori",
"mk": "Macedonian",
"ml": "Malayalam",
"mn": "Mongolian",
"mr": "Marathi",
"ms": "Malay",
"mt": "Maltese",
"my": "Burmese",
"na": "Nauru",
"nb": "Bokmål, Norwegian; Norwegian Bokmål",
"nd": "Ndebele, North; North Ndebele",
"ne": "Nepali",
"ng": "Ndonga",
"nl": "Dutch; Flemish",
"nn": "Norwegian Nynorsk; Nynorsk, Norwegian",
"no": "Norwegian",
"nr": "Ndebele, South; South Ndebele",
"nv": "Navajo; Navaho",
"ny": "Chichewa; Chewa; Nyanja",
"oc": "Occitan (post 1500)",
"oj": "Ojibwa",
"om": "Oromo",
"or": "Oriya",
"os": "Ossetian; Ossetic",
"pa": "Panjabi; Punjabi",
"pi": "Pali",
"pl": "Polish",
"ps": "Pushto; Pashto",
"pt": "Portuguese",
"qu": "Quechua",
"rm": "Romansh",
"rn": "Rundi",
"ro": "Romanian; Moldavian; Moldovan",
"ru": "Russian",
"rw": "Kinyarwanda",
"sa": "Sanskrit",
"sc": "Sardinian",
"sd": "Sindhi",
"se": "Northern Sami",
"sg": "Sango",
"si": "Sinhala; Sinhalese",
"sk": "Slovak",
"sl": "Slovenian",
"sm": "Samoan",
"sn": "Shona",
"so": "Somali",
"sq": "Albanian",
"sr": "Serbian",
"ss": "Swati",
"st": "Sotho, Southern",
"su": "Sundanese",
"sv": "Swedish",
"sw": "Swahili",
"ta": "Tamil",
"te": "Telugu",
"tg": "Tajik",
"th": "Thai",
"ti": "Tigrinya",
"tk": "Turkmen",
"tl": "Tagalog",
"tn": "Tswana",
"to": "Tonga (Tonga Islands)",
"tr": "Turkish",
"ts": "Tsonga",
"tt": "Tatar",
"tw": "Twi",
"ty": "Tahitian",
"ug": "Uighur; Uyghur",
"uk": "Ukrainian",
"ur": "Urdu",
"uz": "Uzbek",
"ve": "Venda",
"vi": "Vietnamese",
"vo": "Volapük",
"wa": "Walloon",
"wo": "Wolof",
"xh": "Xhosa",
"yi": "Yiddish",
"yo": "Yoruba",
"za": "Zhuang; Chuang",
"zh": "Chinese",
"zu": "Zulu"
};
if (urlParams.has("key")){
apiKey = urlParams.get("key") || "";
}
function getStorage(cname) {
try {
var itemStr = localStorage.getItem(cname);
} catch(e){
errorlog(e);
return;
}
if (!itemStr) {
return "";
}
let item = JSON.parse(itemStr);
let now = new Date();
if (now.getTime() > item.expiry) {
localStorage.removeItem(cname);
return "";
}
return item.value;
}
if (!apiKey && getStorage("apiKey")){
apiKey = getStorage("apiKey");
} else if (apiKey){
setStorage("apiKey", apiKey, 999999);
}
if (!apiKey){
document.getElementById("whosekey").innerText = "(you'll need to specify own API key first to use)";
document.getElementById("whosekey").style = "color: black; background-color: yellow;";
} else {
document.getElementById("whosekey").innerText = "PRIVATE KEY ACTIVE";
document.getElementById("whosekey").style = "color: white; background-color: green;";
}
function removeStorage(cname){
localStorage.removeItem(cname);
}
function clearStorage(){
localStorage.clear();
if (!session.cleanOutput){
warnUser("The local storage and saved settings have been cleared", 1000);
}
}
function setStorage(cname, cvalue, hours=9999){
let now = new Date();
let item = {
value: cvalue,
expiry: now.getTime() + (hours * 60 * 60 * 1000),
};
try{
localStorage.setItem(cname, JSON.stringify(item));
}catch(e){errorlog(e);}
}
var myLang = navigator.language || "en-US";
if (urlParams.has("lang")){
myLang = urlParams.get("lang");
} else if (getStorage("myLang")){
myLang = getStorage("myLang");
} else {
updateURL("lang="+myLang);
}
var myLangCode = myLang.split("-")[0].toLowerCase();
var targetCode = "de";
if (myLangCode == "de"){
targetCode = "en";
}
if (getStorage("targetCode")){
targetCode = getStorage("targetCode");
}
if (urlParams.has("translate") || urlParams.has("target")){
targetCode = urlParams.get("translate") || urlParams.get("target") || targetCode;
targetCode = targetCode.split("-")[0].toLowerCase();
} else if (getStorage("targetCode")){
targetCode = getStorage("targetCode");
} else {
updateURL("translate="+targetCode);
}
setStorage("targetCode", targetCode, 999999)
setStorage("myLang", myLang, 999999);
var label = false;
if (urlParams.has("label")){
label = urlParams.get("label");
}
var counter = 0;
let activeRequest = null;
let requestTimeout = null;
let lastRequestTime = 0;
const REQUEST_TIMEOUT = 3000;
const langFrom = document.getElementById("lang-from");
const langTo = document.getElementById("lang-to");
var availableLangs = {};
if (apiKey){
var langurl = "https://www.googleapis.com/language/translate/v2/languages?key=" + apiKey;
} else {
var langurl = "https://captionninjapremium.vdo.workers.dev/?ts="+Date.now();
}
fetch(langurl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json()).then((data) => {
console.log(data);
if (data.error){
alert(data.error.message);
return;
}
var languages = data.data.languages;
languages.forEach(l=>{
availableLangs[l.language] = langs[l.language] || l.language;
var option = document.createElement("option");
option.innerText = langs[l.language] || l.language;
option.value = l.language;
if (option.value == myLangCode){
option.selected = true;
}
langFrom.appendChild(option);
option = document.createElement("option");
option.innerText = langs[l.language] || l.language;
option.value = l.language;
if (option.value == targetCode){
option.selected = true;
}
langTo.appendChild(option);
});
setup();
});
const getCachedTranslation = (url) => {
try {
const cached = localStorage.getItem('translation_' + url);
if (cached) {
const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp < 24 * 60 * 60 * 1000) {
return data?.translations?.[0]?.translatedText || null;
}
localStorage.removeItem('translation_' + url);
}
} catch (e) {
console.error('Cache error:', e);
}
return null;
};
function cacheTranslation(url, data) {
try {
console.log("cacheTranslation");
localStorage.setItem('translation_' + url, JSON.stringify({
data: data,
timestamp: Date.now()
}));
} catch (e) {
console.error('Cache storage error:', e);
try {
const keys = Object.keys(localStorage);
for (let key of keys) {
if (key.startsWith('translation_')) {
localStorage.removeItem(key);
}
}
} catch (e) {
console.error('Cache cleanup error:', e);
}
}
}
let lastRequest = {
text: null,
timestamp: 0,
translation: null
};
const RATE_LIMIT = {
minTimeBetweenRequests: 250,
lastRequestTime: 0
};
async function translateIncremental(textToTranslate) {
if (!textToTranslate?.trim() || !document.getElementById("enabledTranscription").checked) {
return;
}
const incrementalEnabled = document.getElementById("incrementalUpdates").checked;
const useContext = document.getElementById("fullContext").checked;
if (textToTranslate === lastRequest.text) {
const timeSinceLastRequest = Date.now() - lastRequest.timestamp;
if (timeSinceLastRequest < 2000) {
console.log('Skipping duplicate request:', textToTranslate);
if (lastRequest.translation) {
updateTrans(lastRequest.translation, incrementalEnabled);
}
return;
}
}
const now = Date.now();
const timeSinceLastRequest = now - RATE_LIMIT.lastRequestTime;
if (timeSinceLastRequest < RATE_LIMIT.minTimeBetweenRequests) {
const delayNeeded = RATE_LIMIT.minTimeBetweenRequests - timeSinceLastRequest;
await new Promise(resolve => setTimeout(resolve, delayNeeded));
}
RATE_LIMIT.lastRequestTime = now;
if (activeRequest) {
activeRequest.abort();
activeRequest = null;
}
if (requestTimeout) {
clearTimeout(requestTimeout);
requestTimeout = null;
}
const url = apiKey
? `https://www.googleapis.com/language/translate/v2/?key=${apiKey}&q=${encodeURI(textToTranslate)}&target=${targetCode}&source=${myLangCode}`
: `https://captionninjapremium.vdo.workers.dev/?ts=${Date.now()}&q=${encodeURI(textToTranslate)}&target=${targetCode}&source=${myLangCode}`;
const cachedData = getCachedTranslation(url);
if (cachedData) {
console.log('Using cached translation for:', textToTranslate);
lastRequest = {
text: textToTranslate,
timestamp: Date.now(),
translation: cachedData
};
updateTrans(cachedData, incrementalEnabled);
return;
}
const controller = new AbortController();
activeRequest = controller;
lastRequestTime = Date.now();
requestTimeout = setTimeout(() => {
if (activeRequest === controller) {
console.log('Request timeout for:', textToTranslate);
controller.abort();
activeRequest = null;
requestTimeout = null;
}
}, REQUEST_TIMEOUT);
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!data?.data?.translations?.[0]) {
throw new Error('Invalid response format from translation service');
}
const translatedText = data.data.translations[0].translatedText;
cacheTranslation(url, data.data);
lastRequest = {
text: textToTranslate,
timestamp: Date.now(),
translation: translatedText
};
updateTrans(translatedText, incrementalEnabled);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request was aborted');
return;
}
console.error('Translation error:', error);
if (error.message.includes('HTTP error! status: 429')) {
const checkbox = document.getElementById("incrementalUpdates");
if (checkbox?.checked) {
checkbox.checked = false;
alert('Incremental updates have been automatically disabled due to rate limiting.');
}
RATE_LIMIT.minTimeBetweenRequests *= 2;
}
const now = Date.now();
if (!window.lastErrorTime || (now - window.lastErrorTime) > 5000) {
window.lastErrorTime = now;
handleTranslationError(error);
}
if (incrementalEnabled && window.lastSuccessfulTranslation) {
updateTrans(window.lastSuccessfulTranslation, true);
}
} finally {
if (activeRequest === controller) {
activeRequest = null;
}
if (requestTimeout) {
clearTimeout(requestTimeout);
requestTimeout = null;
}
}
}
function handleTranslationError(error) {
if (error instanceof TypeError && error.message.includes('CORS')) {
alert('CORS Error: Unable to access the translation service.\n\n' +
'1. Missing or invalid API key\n' +
'2. Browser security restrictions\n' +
'3. Service being temporarily unavailable\n\n' +
'Please check your API key or try again later.');
} else if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
alert('Network Error: Unable to connect to the translation service.\n\n' +
'This might be due to:\n' +
'1. No internet connection\n' +
'2. Website / IP denied access (CORS)\n' +
'3. Missing or invalid API key\n' +
'4. Service being down\n' +
'Please check your internet connection and try again.');
} else if (error.message.includes('HTTP error! status: 403')) {
alert('Authorization Error: Unable to access the translation service.\n\n' +
'This is likely due to:\n' +
'1. Invalid API key\n' +
'2. API key not having proper permissions\n' +
'3. API quota exceeded\n\n' +
'Please check your API key configuration.');
} else if (error.message.includes('HTTP error! status: 429')) {
alert('Rate Limit Error: Too many requests to the translation service.\n\n' +
'Please wait a moment before trying again.\n\n' +
'Consider disabling incremental updates to reduce API calls.');
} else if (error.message.includes('Invalid response format')) {
alert('Error: Received an unexpected response from the translation service.\n\n' +
'Please try again later or contact support if the issue persists.');
} else {
alert('Translation Error: ' + error.message + '\n\n' +
'Please try again later or contact support if the issue persists.\n\n' +
'If this persists, try disabling incremental updates.');
}
}
function updateTrans(translatedText, isIncremental) {
window.lastSuccessfulTranslation = translatedText;
document.getElementById("output").innerHTML = translatedText;
var text = document.getElementById("output").textContent || "";
counter += 1;
if (label) {
socket.send(JSON.stringify({
"msg": true,
[isIncremental ? "interm" : "final"]: text,
"id": counter,
"label": label,
"c": document.getElementById("fullContext").checked,
"ln": targetCode
}));
} else {
socket.send(JSON.stringify({
"msg": true,
[isIncremental ? "interm" : "final"]: text,
"id": counter,
"c": document.getElementById("fullContext").checked,
"ln": targetCode
}));
}
}
langFrom.addEventListener("change", e => {
myLangCode = e.target.value;
console.log(myLangCode)
if (myLang.split("-")[0].toLowerCase() !== myLangCode){
setStorage("myLang", myLangCode, 999999);
updateURL("lang="+myLangCode, true);
recognition.onend = null;
recognition.stop();
recognition = null;
setup();
}
});
langTo.addEventListener("change", e => {
targetCode = e.target.value;
updateURL("translate="+targetCode, true);
console.log(targetCode);
setStorage("targetCode", targetCode, 999999);
});
function updateURL(param, force=false) {
var para = param.split('=');
if (!(urlParams.has(para[0].toLowerCase()))){
if (history.pushState){
var arr = window.location.href.split('?');
var newurl;
if (arr.length > 1 && arr[1] !== '') {
newurl = window.location.href + '&' +param;
} else {
newurl = window.location.href + '?' +param;
}
window.history.pushState({path:newurl},'',newurl);
}
} else if (force){
if (history.pushState){
var href = new URL(window.location.href);
if (para.length==1){
href.searchParams.set(para[0].toLowerCase(), "");
} else {
href.searchParams.set(para[0].toLowerCase(), para[1]);
}
window.history.pushState({path:href.toString()},'',href.toString());
}
}
}
function generateStreamID(){
var text = "";
var possible = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
for (var i = 0; i < 7; i++){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
var roomID = "test";
if (urlParams.has("room")){
roomID = urlParams.get("room");
} else if (urlParams.has("ROOM")){
roomID = urlParams.get("ROOM");
} else {
roomID = generateStreamID();
updateURL("room="+roomID);
}
var url = document.URL.substr(0,document.URL.lastIndexOf('/'));
document.getElementById("shareLink").href= url+"/overlay?room="+roomID;
document.getElementById("shareLink").innerHTML = url+"/overlay?room="+roomID;
navigator.clipboard.writeText(url+"/overlay?room="+roomID).then(() => {
}, () => {
});
var socket;
function connectWebSocket() {
socket = new WebSocket("wss://api.caption.ninja:443");
socket.onclose = function() {
console.log("WebSocket connection closed. Attempting to reconnect...");
setTimeout(connectWebSocket, 500);
};
socket.onopen = function() {
console.log("WebSocket connected. Joining room...");
socket.send(JSON.stringify({"join":roomID}));
};
socket.onerror = function(error) {
console.error("WebSocket error:", error);
setTimeout(connectWebSocket, 5000);
};
}
connectWebSocket();
var final_transcript = '';
var last_transcription = "";
var second_transcription = "";
var idle = null;
var recognition = null;
var ends = 0;
document.getElementById("incrementalUpdates").addEventListener("change", function(e) {
if (recognition) {
recognition.onend = null;
recognition.stop();
recognition = null;
setup();
}
});
var sanitize = function(string) {
var temp = document.createElement('div');
temp.textContent = string;
return temp.textContent
.substring(0, Math.min(temp.textContent.length, 500))
.trim();
};
function setup(){
if ('webkitSpeechRecognition' in window){
console.log("Setting up webkitSpeechRecognition");
recognition = new webkitSpeechRecognition();
if (myLang && myLangCode){
if (myLang.split("-")[0] == myLangCode){
recognition.lang = myLang;
} else {
recognition.lang = myLangCode;
}
} else if (myLangCode){
recognition.lang = myLangCode;
} else if (myLang){
recognition.lang = myLang;
}
recognition.continuous = true;
recognition.interimResults = document.getElementById("incrementalUpdates").checked;
recognition.onstart = function(){
console.log("started transcription");
setTimeout(function(){
ends = 0;
}, 2000);
};
recognition.onerror = function(event){
console.error(event);
};
recognition.onend = function(e){
console.log(e);
console.log("Stopped transcription");
if (event.type === "end"){
ends +=1;
}
if (ends > 3){
alert("WARNING: Cannot enable transcription service\n\nThe service will fail completely if more than one transcription session is currently active on your computer.\n\nPlease close other Caption.Ninja tabs or other transcription services and then wait a few minutes before retrying.");
} else {
recognition.start();
}
};
recognition.onresult = function(event) {
let interim_transcript = '';
if (typeof(event.results) == 'undefined') {
console.log('Undefined results in event:', event);
return;
}
for(var i = event.resultIndex; i < event.results.length; ++i){
if(event.results[i].isFinal){
final_transcript += sanitize(event.results[i][0].transcript);
} else {
interim_transcript += " " +sanitize(event.results[i][0].transcript);
interim_transcript = interim_transcript.trim();
}
}
if (final_transcript || (interim_transcript && document.getElementById("incrementalUpdates").checked)) {
let currentText = final_transcript || interim_transcript;
console.log("Processing text:", currentText, "Final:", !!final_transcript);
if (document.getElementById("fullContext").checked) {
let fullText = [];
if (second_transcription?.trim()) {
fullText.push(second_transcription.trim().replace(/\.?$/, '.'));
}
if (last_transcription?.trim()) {
fullText.push(last_transcription.trim().replace(/\.?$/, '.'));
}
if (currentText?.trim()) {
fullText.push(currentText.trim().replace(/\.?$/, '.'));
}
document.getElementById("input").value = fullText.join('\n');
let contextText = fullText.join(' ');
console.log("Translating with context:", contextText);
translateIncremental(contextText);
} else {
document.getElementById("input").value = currentText;
translateIncremental(currentText);
}
if (final_transcript) {
if (currentText.trim()) {
second_transcription = last_transcription;
last_transcription = currentText.trim().replace(/\.?$/, '.') + ' ';
final_transcript = '';
console.log("Updated context state:", {
second: second_transcription,
last: last_transcription
});
}
}
}
};
recognition.start();
}
}
</script>
</body>
</html>