-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcommon.js
195 lines (173 loc) · 6.04 KB
/
common.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
function formatDefinition() {
document.querySelectorAll(".definition").forEach(function (def) {
let text = def.innerHTML;
if (text.includes(",") || text.includes(";")) {
text = text.replaceAll(
/([^,;\[\] ][^,;\[\]]+[^,;\[\] ])/g,
(match) => `<span class="no-break">${match}</span>`
);
text = text.replaceAll(
'<span class="no-break"> ',
' <span class="no-break">'
);
text = text.replaceAll(
'</span>, <span class="no-break">',
',</span> <span class="no-break">'
);
text = text.replaceAll(
'</span>; <span class="no-break">',
';</span> <span class="no-break">'
);
}
text = text.replaceAll(
/\(-?(.*?)-?\)/g,
'<span class="pre-suffix">$1</span>'
);
text = text.replaceAll(/\[(.*?)\]/g, '<span class="grammar">$&</span>');
def.innerHTML = text;
});
}
function processText(text, isFrench, processStars = true) {
if (text.length === 0) {
return text;
}
text = text.replaceAll(/([^<>\s])'/g, "$1’"); // convert apostrophes
text = text.replaceAll("...", "…"); // convert ellipsis
if (isFrench) {
text = text.replaceAll(/[\u0020\u00A0\u202F]+| /g, " "); // replace with regular space
text = text.replaceAll("« ", "«").replaceAll(" »", "»");
text = text.replaceAll("«", '"').replaceAll("»", '"');
// insert thin non-breaking space before punctuation (but not inside HTML tags)
text = text.replaceAll(/(?!.*<[^>]+>)(\s?)([?|:|!|;])/g, "\u202F$2");
// Replace " with French quote marks « ... », except inside HTML tags
text = text.replace(/"(?![^<]*>)(.*?)"(?![^<]*>)/g, "«\u202F$1\u202F»");
if (text[0] === "-") {
text[0] = "–";
}
text = text.replaceAll("<br>-", "<br>–");
} else {
// format dialogue
if (text.includes("<br>-") || text.includes("<br>–")) {
const lines = text.split("<br>");
const formattedLines = [];
for (let line of lines) {
line = line.trim();
if (line.startsWith("–") || line.startsWith("-")) {
line = line.replaceAll(/^(–|-)\s*/g, "");
}
formattedLines.push(`"${line}"`);
}
text = formattedLines.join("<br>");
}
// replace with German quote marks »...«
text = text.replaceAll("„", '"').replaceAll("“", '"');
text = text.replaceAll(/"(?![^<]*>)(.*?)"(?![^<]*>)/g, "»\u2060$1\u2060«");
}
// replace *...* with word-highlight span
if (processStars) {
text = text.replaceAll(/\*(.*?)\*/g, '\u2060<span class="word-highlight">$1</span>\u2060');
}
return text;
}
function shuffleArray(arr, persist = true) {
let seed = Math.random();
if (persist) {
Persistence.setItem(seed);
} else {
seed = Persistence.getItem();
Persistence.clear();
}
let currentSeed = seed;
for (let i = arr.length - 1; i > 0; i--) {
currentSeed = (currentSeed * 16807) % 2147483647;
const j = Math.floor((currentSeed / 2147483647) * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
async function fetchAudio({text, customFileName = undefined, lang = "fr-FR"}) {
const url = customFileName
? getAnkiPrefix() + "/" + customFileName
: await getTTSUrl(text, false, lang);
const audioCurrent = document.querySelector("audio");
audioCurrent.src = url;
}
async function playAudio({text, customFileName = undefined, lang = "fr-FR"}) {
await fetchAudio({text, customFileName, lang});
const audioCurrent = document.querySelector("audio");
try {
await audioCurrent.play();
} catch {
audioCurrent.src = await getTTSUrl(text, true, lang);
audioCurrent.play();
}
}
const memoizedTTSUrls = {};
async function getTTSUrl(textToRead, forceGoogleTranslate = false, lang = "fr-FR") {
const text = textToRead.replaceAll("*", "");
// if no API key is set, fallback to use the free Google Translate TTS
if (!options.googleTTSApiKey || forceGoogleTranslate) {
return `https://translate.google.com/translate_tts?ie=UTF-8&q=${text}&tl=${lang}&client=tw-ob`;
}
if (memoizedTTSUrls && memoizedTTSUrls[text]) {
return memoizedTTSUrls[text];
}
try {
const textInput = decodeURIComponent(text).replaceAll("*", "").replaceAll("→", ";").replace(/[\u0000-\u001F\u007F-\u009F\u200B\u2060\uFEFF\u202f]/g, "");
let voice = {
languageCode: "fr-FR",
name: "fr-FR-Journey-" + ["D", "F", "O"][Math.floor(Math.random() * 3)],
};
if (lang === "de-DE") {
voice = {
languageCode: "de-DE",
name: "de-DE-Journey-" + ["D", "F", "O"][Math.floor(Math.random() * 3)],
};
}
const response = await fetch(
`https://texttospeech.googleapis.com/v1/text:synthesize?key=${options.googleTTSApiKey}`,
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
audioConfig: { audioEncoding: "LINEAR16" },
input: { text: textInput },
voice,
}),
}
);
if (!response.ok) {
throw new Error("Network response was not ok " + response.statusText);
}
const data = await response.json();
const audioContent = data.audioContent;
if (audioContent) {
const audioBlob = b64ToBlob(audioContent, "audio/mp3");
const audioUrl = URL.createObjectURL(audioBlob);
if (memoizedTTSUrls) {
memoizedTTSUrls[text] = audioUrl;
}
return audioUrl;
}
} catch (error) {
console.error("Fetch error:", error);
}
}
function b64ToBlob(b64Data, contentType, sliceSize = 512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, { type: contentType });
}
___CLOZE_GAME___;