-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module-cst.js
223 lines (198 loc) · 6.87 KB
/
module-cst.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
//author= Mücahit Sahin
//github=https://github.com/mucahit-sahin
//author of fork with addons = lexxai
//github=https://github.com/lexxai/coursera-subtitle-translate-extension
window.browser = (function () {
return typeof window.browser === "undefined" ? window.chrome : window.browser;
})();
async function openBilingual() {
let tracks = document.getElementsByTagName("track");
let en;
//let tr;
if (tracks.length) {
for (let i = 0; i < tracks.length; i++) {
if (tracks[i].srclang === "en") {
en = tracks[i];
}
}
if (en) {
en.track.mode = "showing";
//addSubtitleStyles("font-size: 16px; color: red;", en);
await sleep(500);
let cues = en.track.cues;
// Виявлення моментів закінчення речення в англійському письмі.
// ..... кінець речення. Нове речення
// Тут вважається, що речення закінчується лише у випадках, коли після символу крапки стоїть пробіл.
// 75.3, model.fit і т.д., щоб не сприймати крапку як кінець речення.
let endSentence = [];
let match_pattern = /[.?!]/;
for (let i = 0; i < cues.length; i++) {
for (let j = 0; j < cues[i].text.length; j++) {
if (cues[i].text[j].match(match_pattern) && cues[i].text[j + 1] == undefined) {
endSentence.push(i);
}
}
}
///////////////////////
let cuesTextList = getTexts(cues);
getTranslation(cuesTextList, (translatedText) => {
//console.log("getTranslation. translatedText:", translatedText);
let translatedList = translatedText.split(" u~~~u");
//console.log("getTranslation. translatedList:", translatedList);
translatedList.splice(-1, 1);
// console.log(
// "getTranslation. translatedList:.splice(-1, 1)",
// translatedList
// );
if (!translatedList) {
return;
}
for (let i = 0; i < endSentence.length; i++) {
if (i != 0) {
for (let j = endSentence[i - 1] + 1; j <= endSentence[i]; j++) {
cues[j].text = cues[j].text.split(" u~~~u")[0].replace(/\n/g, " ");
if (typeof translatedList[i] != "undefined") {
cues[j].text += "\n\n" + translatedList[i].trim();
}
// console.log(translatedList[i]);
}
} else {
for (let j = 0; j <= endSentence[i]; j++) {
cues[j].text = cues[j].text.split(" u~~~u")[0].replace(/\n/g, " ");
if (typeof translatedList[i] != "undefined") {
cues[j].text += "\n\n" + translatedList[i].trim();
}
// console.log(translatedList[i]);
}
}
}
mark_translated();
});
}
}
}
String.prototype.replaceAt = function (index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
};
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getTexts(cues) {
let cuesTextList = "";
const match_pattern = /[.?!]/;
const clear_regex = /^"?(.*[.?!])"?$/;
const subst = `$1`;
const mark_sequence = "u~~~u";
let mark_sequence_added = " " + mark_sequence + " ";
for (let i = 0; i < cues.length; i++) {
if (cues[i].text.includes("\n\n")) continue;
// let str = cues[i].text;
// cues[i].text = str.replace(clear_regex, subst);
let last_char = cues[i].text[cues[i].text.length - 1];
if (last_char.match(match_pattern)) {
cues[i].text = cues[i].text.replaceAt(cues[i].text.length - 1, last_char + mark_sequence_added);
}
cuesTextList += cues[i].text.replace(/\n/g, " ") + " ";
}
return cuesTextList;
}
function resizeSub(size) {
console.log("CST size:", size);
//let size = result.size;
size = size / 100;
// alert('Value is set to ' + size);
let css = `video::-webkit-media-text-track-display {font-size: ${size}em;}`,
head = document.head || document.getElementsByTagName("head")[0],
style = document.createElement("style");
style.type = "text/css";
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
function getTranslation(words, callback) {
browser.storage.sync.get({ cst_lang: "uk" }, function (result) {
let lang = result.cst_lang;
console.log("CST Lang:", lang);
const xhr = new XMLHttpRequest();
let url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${lang}&dt=t&q=${encodeURI(
words
)}`;
xhr.open("GET", url, true);
xhr.responseType = "text";
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200 || xhr.status === 304) {
const translatedList = JSON.parse(xhr.responseText)[0];
let translatedText = "";
if (translatedList) {
for (let i = 0; i < translatedList.length; i++) {
translatedText += translatedList[i][0];
}
callback(translatedText);
}
}
}
};
xhr.send();
});
}
function check_translated() {
let video = document.getElementById("video_player_html5_api");
result = video?.getAttribute("cst") == "translated";
if (result) console.log("CST video is already marked as translated, skip");
return result;
}
function mark_translated() {
let video = document.getElementById("video_player_html5_api");
if (video && video?.getAttribute("cst") != "translated") {
console.log("CST mark video as translated");
video.setAttribute("cst", "translated");
}
}
function check_cst_loaded() {
result = document.body?.getAttribute("cst") === "loaded";
if (result) console.log("CST module is already marked as loaded, skip");
return result;
}
function mark_cst_loaded() {
if (document.body?.getAttribute("cst") != "loaded") {
console.log("CST module makr as loaded");
document.body.setAttribute("cst", "loaded");
}
}
function translate() {
if (check_translated()) {
return;
}
browser.storage.sync
.get({
cst_fontsize: 75,
})
.then((result) => {
let fontsize = result.cst_fontsize;
if (fontsize) {
resizeSub(fontsize);
} else {
resizeSub(75);
}
})
.catch(() => {
resizeSub(75);
});
openBilingual();
}
// MAIN
browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.command == "translate") {
console.log("CST MODULE translating", request.command);
translate();
console.log("CST MODULE translated", request.command);
if (sendResponse) sendResponse({ command: "translated" });
}
return false;
});
console.log("CST MODULE LOADED ...");
mark_cst_loaded();