-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
396 lines (366 loc) · 15.3 KB
/
index.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
<!DOCTYPE html>
<html class='w-full overflow-x-hidden' lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Language Selector</title>
<script src="https://unpkg.com/htmx.org@1.8.4"></script>
<link rel="stylesheet" href="/style.css">
<script type="module">
window.API_HOST = import.meta.env.VITE_API_HOST;
import './style.scss';
</script>
<script>
/*
create html elements to be used throughout the code
*/
let rowDiv = `<div class='phrases flex flex-row row w-full'>`;
let languageSelect = `<select name='language' class='w-32 language pl-1 defaultSelect border-solid text-left' onchange='translateColumn(this)'>`;
let phraseTextArea = (numRows, innerText) => `<textarea row=${numRows} name='text' class='w-32 pl-1 phrase overflow-y-auto break-words text-wrap resize-none' onchange='translateRow(this)'>${innerText}</textarea>`;
let translationCellOpenTag = `<div class="box flex justify-between items-center text-wrap w-32 translationCell">`
let translationCellClosingTag = `</div>`
let translationCellWrapper = `${translationCellOpenTag}${translationCellClosingTag}`
let translationCell = (translated_text, i, j) => {
return `${translationCellOpenTag}
${translationCellContents(translated_text, i, j)}
${translationCellClosingTag}`;
}
let translationCellContents = (translated_text, i, j) => {
return `<span class='text-wrap overflow-y-auto overflow-x-hidden whitespace-nowrap w-32 p-2'>${translated_text}</span>
<svg onclick="playAudioFromCache('${i}-${j}')" class="w-4 h-4 cursor-pointer flex-shrink-0" viewBox="0 0 24 24" fill="currentColor">
<circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="2"/>
<path d="M10 8l6 4-6 4V8z"/>
</svg>`;
}
//let emptyCell = `<div class="inline-block w-32 border-1 border-[#767676] border-solid pl-1 translationCell h-20 break-words text-wrap"></div>`;
let languages = ["arabic", "bengali", "english", "french", "german", "hindi", "indonesian", "japanese", "mandarin", "portuguese (br)", "russian", "spanish", "thai", "urdu"]
// append options to default select
let options = languages.map(lang => `<option value='${lang}'>${lang}</option>`)
// create default table if none exists
if (localStorage.getItem('table') === null || localStorage.getItem('table') === '') {
localStorage.setItem('table', JSON.stringify([
['english', 'spanish'],
['', ''],
]));
}
// build table html from local storage
let html = '';
JSON.parse(localStorage.getItem('table')).forEach((row, i) => {
// First row is only selects (languages)
if (i == 0) {
html += rowDiv;
// iterate languages in row, set the option to the language
row.forEach((language, j) => {
html += languageSelect;
languages.forEach(lang => {
html += `<option value="${lang}" ${lang === language ? 'selected' : ''}>${lang}</option>`;
});
html += '</select>';
});
html += '</div>';
}
else {
html += rowDiv;
// All other rows are 1 input and n divs (phrases)
row.forEach((cell, j) => {
// first cell is text area
if (j == 0) {
html += phraseTextArea(i, cell);
}
else {
// all other cells are divs (phrases)
if (cell) { // if there's translated text, translateCell
html += translationCell(cell, i, j);
} else { // else, empty cell
html += translationCellWrapper
}
}
});
}
html += '</div>';
});
window.onload = function () {
// render table by appending to table div
document.querySelector('.table').insertAdjacentHTML('beforeend', html);
// Create observer to watch table changes
const tableObserver = new MutationObserver(() => {
console.log('table changed');
const table = [];
document.querySelectorAll('.row').forEach((row, rowIndex) => {
table[rowIndex] = [];
if (rowIndex === 0) {
// First row: get language values from selects
row.querySelectorAll('.language').forEach(select => {
table[rowIndex].push(select.value);
});
} else {
// Other rows: get input value and translated phrases
const input = row.querySelector('textarea');
table[rowIndex].push(input?.value || '');
row.querySelectorAll('.translationCell').forEach(phrase => {
table[rowIndex].push(phrase.textContent || '');
});
}
});
localStorage.setItem('table', JSON.stringify(table));
});
// Start observing the table div for changes
tableObserver.observe(document.querySelector('.table'), {
subtree: true, // Watch all descendants
childList: true, // Watch for added/removed nodes
characterData: true, // Watch for text changes
attributes: true // Watch for attribute changes
});
};
function add_col() {
table = JSON.parse(localStorage.getItem('table'))
let numColumns = document.querySelectorAll('.language').length;
if (numColumns === languages.length) {
alert('Max languages reached')
return;
}
const rows = document.querySelectorAll('.row');
// iterate through all rows, translate the first cell if it has text
// first row is selects (languages), other rows are 1 input and n divs (phrases)
// if
for (let i = 0; i < rows.length; i++) {
if (i === 0) {
rows[i].insertAdjacentHTML('beforeend', `
${languageSelect}
${options.map((opt, index) =>
`<option value='${languages[index]}' ${index === numColumns ? 'selected' : ''}>${languages[index]}</option>`
).join('')}
</select>
`);
table[i].push(languages[numColumns]);
localStorage.setItem('table', JSON.stringify(table));
} else {
// create a div and update it with the translation later
rows[i].insertAdjacentHTML('beforeend', translationCellWrapper);
// if input is empty, don't translate
if (rows[i].querySelector('textarea').value === '') {
table[i].push('');
localStorage.setItem('table', JSON.stringify(table));
continue;
}
// update the div with the translation
fetch(`${API_HOST}/translate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
phrase: rows[i].querySelector('textarea').value,
target_language: languages[numColumns]
})
})
.then(response => response.json())
.then(data => {
// update the div with the translation
// hit the text to speech api, and update the div with a play icon to play the audio
console.log(data)
fetch(`${API_HOST}/text-to-speech`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: data.translated_text, language: languages[numColumns] })
})
.then(response => response.blob())
.then(audioBlob => {
saveAudioToIndexedDB(`${i}-${numColumns}`, audioBlob);
rows[i].lastElementChild.innerHTML = translationCellContents(data.translated_text, i, numColumns);
})
})
.catch(error => {
rows[i].lastElementChild.textContent = 'Translation failed';
console.error('Translation error:', error);
});
}
}
}
function add_row() {
// add <div>1<input>#cols<div></div></div>
// get the number of rows from HTML
let numRows = document.querySelectorAll('.row').length;
let localStorageRow = [];
let table = JSON.parse(localStorage.getItem('table'))
let html = rowDiv;
html += phraseTextArea(numRows, '');
document.querySelectorAll('.language').forEach((lang, i) => {
if (i > 0) {
html += translationCellWrapper;
}
localStorageRow.push('');
});
table.push(localStorageRow);
localStorage.setItem('table', JSON.stringify(table));
html += `</div>`
document.querySelector('.table').insertAdjacentHTML('beforeend', html);
}
function translateRow(input) {
/*
textInput onChange, iterate through the cells of the row / over the columns. translate first cell (text input) with the column language (select values)
*/
let table = JSON.parse(localStorage.getItem('table'))
let rowIndex = input.getAttribute('row');
table[rowIndex][0] = input.value;
localStorage.setItem('table', JSON.stringify(table));
// get all but first column
const languageSelects = [...document.querySelectorAll('.language')].slice(1);
const translationSpans = input.parentElement.querySelectorAll('.translationCell');
// if text input is empty, don't translate
if (input.value === '') {
translationSpans.forEach(div => div.textContent = ''); // Clear the divs on input change
return;
}
// iterate over all columns of the text input row
languageSelects.forEach((langSelect, i) => {
fetch(`${API_HOST}/translate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phrase: input.value,
target_language: langSelect.value
})
})
.then(response => response.json())
.then(data => {
// Add text-to-speech request here
console.log('translateRow')
//debugger;
fetch(`${API_HOST}/text-to-speech`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: data.translated_text, language: langSelect.value })
})
.then(response => response.blob())
.then(audioBlob => {
saveAudioToIndexedDB(`${rowIndex}-${i + 1}`, audioBlob);
translationSpans[i].innerHTML = translationCellContents(data.translated_text, rowIndex, i + 1);
});
})
.catch(error => {
translationSpans[i].textContent = 'Translation failed';
console.error('Translation error:', error);
});
});
}
function translateColumn(select) {
const columnIndex = [...select.parentElement.children].indexOf(select);
// get all rows except for the first (phrase rows)
[...document.querySelectorAll('.row')].slice(1)
.filter(row => row.querySelector('textarea').value)
.forEach(row => {
fetch(`${API_HOST}/translate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phrase: row.querySelector('textarea').value,
target_language: select.value
})
})
.then(response => response.json())
.then(data => {
fetch(`${API_HOST}/text-to-speech`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: data.translated_text, language: select.value })
})
.then(response => response.blob())
.then(audioBlob => {
const rowIndex = [...row.parentElement.children].indexOf(row);
saveAudioToIndexedDB(`${rowIndex}-${columnIndex}`, audioBlob);
row.children[columnIndex].innerHTML = translationCellContents(data.translated_text, rowIndex, columnIndex, );
});
})
.catch(error => {
row.children[columnIndex].textContent = 'Translation failed';
console.error('Translation error:', error);
});
});
}
// Add IndexedDB setup
const dbName = "audioCache";
const dbVersion = 1;
const storeName = "audioFiles";
// Open/create the database
const dbRequest = indexedDB.open(dbName, dbVersion);
dbRequest.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
}
};
// Helper functions for IndexedDB operations
function saveAudioToIndexedDB(key, audioBlob) {
const request = indexedDB.open(dbName);
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction([storeName], "readwrite");
const store = transaction.objectStore(storeName);
store.put(audioBlob, key);
};
}
function playAudioFromCache(key) {
const request = indexedDB.open(dbName);
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction([storeName], "readonly");
const store = transaction.objectStore(storeName);
const getRequest = store.get(key);
getRequest.onsuccess = () => {
if (getRequest.result) {
const audioUrl = URL.createObjectURL(getRequest.result);
new Audio(audioUrl).play();
} else {
// If not in cache, fetch from server
const [text, language] = key.split('_');
fetch(`${API_HOST}/text-to-speech`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, language })
})
.then(response => response.blob())
.then(audioBlob => {
saveAudioToIndexedDB(key, audioBlob);
const audioUrl = URL.createObjectURL(audioBlob);
new Audio(audioUrl).play();
});
}
};
};
}
function clearTable() {
// Clear the table div
document.querySelector('.table').innerHTML = '';
// Clear the 'table' item in localStorage
localStorage.setItem('table', JSON.stringify([
['english', 'spanish'],
['', ''],
]));
}
</script>
<link href="https://fonts.googleapis.com/css2?family=Atma:wght@400;700&display=swap" rel="stylesheet">
</head>
<body class='w-full p-2 overflow-x-hidden touch-pan-y'></body>
<div class="flex flex-row items-center">
<img class="inline-block w-12 h-12" src="monster.png" alt="Monster">
<h1 class="inline-block m-0">Hello!</h1>
</div>
<p class="mt-2 mb-2">Enter phrases in the first column (then press enter or click away)</p>
<!-- buttons -->
<div class="pb-2">
<button onclick="add_col()">
Add Language (column)
</button>
<button onclick="add_row()">
Add Phrase (row)
</button>
</div>
<!-- table -->
<div class='overflow-x-auto w-full whitespace-nowrap'>
<div class='table'>
<!-- Table content will be inserted here -->
</div>
</div>
</body>
</html>