-
Notifications
You must be signed in to change notification settings - Fork 21
/
overlay.html
352 lines (303 loc) · 9.34 KB
/
overlay.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
<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 Overlay Window</title>
<meta name="title" content="CAPTION.Ninja: Overlay" />
<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');
}
body {
margin:0;
padding:0 10px;
height:100%;
border: 0;
display: flex;
flex-direction: column-reverse;
position:absolute;
bottom:0;
overflow:hidden;
}
.output {
margin:0;
background-color: #0000;
color: white;
font-family: Cousine, monospace;
font-size: 3.2em;
line-height: 1.1em;
letter-spacing: 0.0em;
padding: 0em;
text-shadow: 0.05em 0.05em 0px rgba(0,0,0,1);
}
.output span {
background-color: black;
padding: 8px 8px 0px 8px;
margin:0;
}
a {
text-transform: none;
}
</style>
</head>
<body>
<div id="interm" class="output"></div>
<div id="output" class="output"></div>
<div id="status" style="display:none;"></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 worker;
let modelRegistry;
let version;
let supportedFromCodes = {};
let supportedToCodes = {};
let currentTo = null;
const status = function(message){document.getElementById("status").innerText = message;}
const langs = { // https://github.com/mozilla/translate - MPL 2.0 - Mozilla
"bg": "Bulgarian",
"cs": "Czech",
"nl": "Dutch",
"en": "English",
"et": "Estonian",
"de": "German",
"fr": "French",
"is": "Icelandic",
"it": "Italian",
"nb": "Norwegian Bokmål",
"nn": "Norwegian Nynorsk",
"fa": "Persian",
"pl": "Polish",
"pt": "Portuguese",
"ru": "Russian",
"es": "Spanish",
"uk": "Ukrainian"
};
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]);
}
log(href.toString());
window.history.pushState({path:href.toString()},'',href.toString());
}
}
}
var langTo = false;
if (urlParams.has("translate") || urlParams.has("lang") || urlParams.has("ln") ){
var myLang = urlParams.get("translate") || urlParams.get("lang") || urlParams.get("ln") || "en";
langTo = myLang.split("-")[0];
console.log("Language: "+langTo);
}
if (langTo){
var langFrom = "en";
if (window.Worker) {
worker = new Worker("worker.js");
worker.postMessage(["import"]);
}
var translateCall = (text, meta, interm=false) => { // https://github.com/mozilla/translate - MPL 2.0 - Mozilla
if (!text.trim().length) return;
const paragraphs = text.split("\n");
worker.postMessage(["translate", langFrom, langTo, paragraphs, meta, interm]);
};
worker.onmessage = function (e) {
if (e.data[0] === "translate_reply" && e.data[1]) {
if (!e.data[2]){
document.getElementById("output").innerText = e.data[1].join("<br /><br />");
} else if (e.data[2].final){
e.data[2].final = e.data[1].join("<br /><br />");
processReply(e.data[2], (e.data[3]||false));
} else if (e.data[2].interm){
e.data[2].interm = e.data[1].join("<br /><br />");
processReply(e.data[2], (e.data[3]||false));
} else {
document.getElementById("output").innerText = e.data[1].join("<br /><br />");
}
} else if (e.data[0] === "load_model_reply" && e.data[1]) {
status(e.data[1]);
} else if (e.data[0] === "import_reply" && e.data[1]) {
modelRegistry = e.data[1];
version = e.data[2];
init();
}
};
var isSupported = (lngFrom, lngTo) => {
return true; //(`${lngFrom}${lngTo}` in modelRegistry) || ((`${lngFrom}en` in modelRegistry) && (`en${lngTo}` in modelRegistry))
}
var loadModel = () => {
if (langFrom !== langTo) {
status(`Installing model...`);
console.log(`Loading model '${langFrom}${langTo}'`);
worker.postMessage(["load_model", langFrom, langTo]);
} else {
console.log("No model loaded yet");
// do nothing.
}
};
function init() { // https://github.com/mozilla/translate - MPL 2.0 - Mozilla
// parse supported languages and model types (prod or dev)
supportedFromCodes["en"] = "prod";
supportedToCodes["en"] = "prod";
for (const [langPair, value] of Object.entries(modelRegistry)) {
const firstLang = langPair.substring(0, 2);
const secondLang = langPair.substring(2, 4);
if (firstLang !== "en") supportedFromCodes[firstLang] = value.model.modelType;
if (secondLang !== "en") supportedToCodes[secondLang] = value.model.modelType;
}
loadModel();
}
} else {
var translateCall = console.log;
}
////////
var roomID = "test";
if (urlParams.has("room")){
roomID = urlParams.get("room");
} else if (urlParams.has("ROOM")){
roomID = urlParams.get("ROOM");
} else {
window.location.href = "./speechin";
}
var clearOnNew = false;
if (urlParams.has("clear")){
clearOnNew = true;
}
var timeoutSpeed = 5000;
if (urlParams.has("showtime")){
timeoutSpeed = parseInt(urlParams.get("showtime")) || 0;
}
var allowHTML = false;
if (urlParams.has("html")){
allowHTML = true;
}
//var counter=0;
var idle = null;
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); // Try to reconnect after 5 seconds
};
socket.onopen = function() {
console.log("WebSocket connected. Joining room...");
socket.send(JSON.stringify({"join":roomID}));
};
// Add error handling
socket.onerror = function(error) {
console.error("WebSocket error:", error);
setTimeout(connectWebSocket, 5000); // Try to reconnect after 5 seconds
};
}
// Initial connection
connectWebSocket();
socket.addEventListener('message', function (event) {
if (event.data){
var data = JSON.parse(event.data);
if (langTo && data.ln){
//if (data.final)
if (langFrom !== data.ln.split("-")[0]){
langFrom = data.ln.split("-")[0];
console.log("Loading model");
loadModel();
}
translateCall(data.final || data.interm, data, data.interm||false);
//}
} else {
processReply(data);
}
}
});
var lastLabel = "";
var label = ""
var sanitize = function(string) {
if (allowHTML){
return string;
}
var temp = document.createElement('div');
temp.innerText = string;
temp.innerText = temp.innerHTML;
temp = temp.textContent || temp.innerText || "";
temp = temp.substring(0, Math.min(temp.length, 500));
return temp.trim();
};
function processReply(data){
var newLabel = false;
if (data.label){
console.log(data.label);
try {
data.label = sanitize(data.label);
data.label = data.label.replaceAll('_', ' ');
label = "<span class='label'>"+data.label+": </span>";
} catch (e) {
return;
}
} else {
label = "";
}
console.log(data);
if ("interm" in data){
document.getElementById("interm").innerHTML = label+"<span>"+sanitize(data.interm)+"</span><br/>";
} else if ("final" in data){
if (clearOnNew || data.c){
document.getElementById("output").innerHTML = label+"<span>"+sanitize(data.final)+"</span><br/>";
} else {
document.getElementById("output").innerHTML += label+"<span>"+sanitize(data.final)+"</span><br/>";
}
document.getElementById("interm").innerHTML="";
}
if (!clearOnNew){
if (idle){
clearInterval(idle);
}
if (timeoutSpeed){
idle = setTimeout(function(){
document.getElementById("output").innerHTML="";
document.getElementById("interm").innerHTML="";
},timeoutSpeed);
}
}
}
socket.onclose = function (){
setTimeout(function(){window.location.reload(true);},100);
};
</script>
</body>
</html>