-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
369 lines (300 loc) · 12.2 KB
/
Copy pathscript.js
File metadata and controls
369 lines (300 loc) · 12.2 KB
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
import { $ } from './dom.js'
class GoogleTranslator {
static SUPPORTED_LANGUAGES = [
'en',
'es',
'fr',
'de',
'it',
'pt',
'ru',
'ja',
'zh'
]
static FULL_LANGUAGES_CODES = {
es: 'es-ES',
en: 'en-US',
fr: 'fr-FR',
de: 'de-DE',
it: 'it-IT',
pt: 'pt-PT',
ru: 'ru-RU',
ja: ['ja-JP', 'ja-Latn'],
zh: 'zh-CN'
}
static DEFAULT_SOURCE_LANGUAGE = 'es'
static DEFAULT_TARGET_LANGUAGE = 'en'
constructor() {
this.init()
this.setupEventListeners()
this.translationTimeout = null
this.currentTranslator = null
this.currentTranslatorKey = null
this.currentDetector = null
}
init() {
// Recuperamos todos los elementos del DOM que necesitamos
this.inputText = $('#inputText')
this.outputText = $('#outputText')
this.sourceLanguage = $('#sourceLanguage')
this.targetLanguage = $('#targetLanguage')
this.micButton = $('#micButton')
this.eraserButton = $('#borrarBtn')
this.copyButton = $('#copyButton')
this.speakerButton = $('#speakerButton')
this.swapLanguagesButton = $('#swapLanguages')
// Configuración inicial
this.targetLanguage.value = GoogleTranslator.DEFAULT_TARGET_LANGUAGE
// Verificar que el usuario tiene soporte para la API de traducción
this.checkAPISupport()
}
checkAPISupport() {
this.hasNativeTranslator = "Translator" in window
this.hasNativeDetector = "LanguageDetector" in window
if (!this.hasNativeTranslator || !this.hasNativeDetector) {
console.warn("APIs nativas de traducción y detección de idioma NO soportadas en tu navegador.")
this.showAPIWarning()
} else {
console.log('✅ APIs nativas de IA disponibles')
}
}
// Mostrar aviso de que las APIs nativas no están disponibles
showAPIWarning() {
const warning = $("#apiWarning")
warning.style.display = "block"
}
setupEventListeners () {
this.inputText.addEventListener('input', () => {
// actualizar el contador de letras
this.debounceTranslate();
// ✅ Usar this.eraserButton (el elemento), no borrarBtn (la función)
this.eraserButton.classList.toggle('visible', this.inputText.value.trim().length > 0)
})
this.sourceLanguage.addEventListener('change', () => this.translate())
this.targetLanguage.addEventListener('change', () => this.translate())
this.swapLanguagesButton.addEventListener('click', () => this.swapLanguages())
this.eraserButton.addEventListener('click', () => this.clearInput())
this.micButton.addEventListener('click', () => this.startVoiceRecognition())
this.copyButton.addEventListener('click', () => this.copyTranslation())
this.speakerButton.addEventListener('click', () => this.speakTranslation())
}
debounceTranslate () {
clearTimeout(this.translationTimeout)
this.translationTimeout = setTimeout(() => {
this.translate()
}, 500)
}
clearInput() {
this.inputText.value = ''
this.outputText.textContent = ''
this.eraserButton.classList.remove('visible')
}
updateDetectedLanguage (detectedLanguage, result) {
// Actualizar visualmente el idioma detectado
let option;
if (detectedLanguage === 'ja-Latn') {
option = this.sourceLanguage.querySelector(`option[value="ja"]`)
} else {
option = this.sourceLanguage.querySelector(`option[value="${detectedLanguage}"]`)
}
if (option) {
const autoOption = this.sourceLanguage.querySelector(`option[value="auto"]`)
const confidence = result?.confidence ? ` (${(result.confidence * 100).toFixed(4)}%)` : ''
autoOption.textContent = `Detectar idioma (${option.textContent}:${confidence})`
}
}
async getTranslation (text) {
let sourceLanguage;
if (this.sourceLanguage.value === 'auto') {
const detected = await this.detectLanguage(text)
sourceLanguage = this.normalizeLanguageCode(detected.detectedLanguage)
} else {
sourceLanguage = this.sourceLanguage.value
}
const targetLanguage = this.targetLanguage.value
if (sourceLanguage === targetLanguage) return text
// 1. Revisar o verificar si realmente tenemos disponibilidad de esta traducción entre origen y destino
try {
const status = await window.Translator.availability({
sourceLanguage,
targetLanguage
})
if (status === 'unavailable') {
throw new Error(`Traducción de ${sourceLanguage} a ${targetLanguage} no disponible`)
}
} catch (error) {
console.error(error)
throw new Error(`Traducción de ${sourceLanguage} a ${targetLanguage} no disponible`)
}
// 2. Realizar la traducción
const translatorKey = `${sourceLanguage}-${targetLanguage}`
try {
if (
!this.currentTranslator ||
this.currentTranslatorKey !== translatorKey
) {
this.currentTranslator = await window.Translator.create({
sourceLanguage,
targetLanguage,
monitor: (monitor) => {
monitor.addEventListener("downloadprogress", (e) => {
this.outputText.innerHTML = `<span class="loading">Descargando modelo: ${Math.floor(e.loaded * 100)}%</span>`
})
}
})
}
this.currentTranslatorKey = translatorKey
const translation = await this.currentTranslator.translate(text)
return translation
} catch (error) {
console.error(error)
return 'Error al traducir'
}
}
async translate () {
const text = this.inputText.value.trim()
if (!text) {
this.outputText.textContent = ''
return
}
this.outputText.textContent = 'Traduciendo...'
if (this.sourceLanguage.value === 'auto') {
if (text.length > 1) {
/*const detectedLanguage = await this.detectLanguage(text)
this.updateDetectedLanguage(detectedLanguage, result[0])*/
const { detectedLanguage, confidence } = await this.detectLanguage(text)
this.updateDetectedLanguage(detectedLanguage, { confidence })
}else{
this.outputText.textContent = 'Texto demasiado corto para detectar idioma'
}
}
try {
const translation = await this.getTranslation(text)
this.outputText.textContent = translation
} catch (error) {
console.error(error)
const hasSupport = this.checkAPISupport()
if (!hasSupport) {
this.outputText.textContent = '¡Error! No tienes soporte nativo a la API de traducción con IA'
return
}
this.outputText.textContent = 'Error al traducir'
}
}
async swapLanguages () {
if (this.sourceLanguage.value === 'auto') {
const detected = await this.detectLanguage(this.inputText.value)
this.sourceLanguage.value = this.normalizeLanguageCode(detected.detectedLanguage)
}
// intercambiar los valores
const temporalLanguage = this.sourceLanguage.value
this.sourceLanguage.value = this.targetLanguage.value
this.targetLanguage.value = temporalLanguage
// intercambiar los textos
this.inputText.value = this.outputText.value
this.outputText.value = ""
if (this.inputText.value.trim()) {
this.translate()
}
// restaurar la opción de auto-detectar
}
getFullLanguageCode(languageCode, preferLatn = false) {
const code = GoogleTranslator.FULL_LANGUAGES_CODES[languageCode]
if (Array.isArray(code)) {
return preferLatn ? code[1] : code[0]
}
return code ?? GoogleTranslator.DEFAULT_SOURCE_LANGUAGE
}
async startVoiceRecognition() {
const hasNativeRecognitionSupport = "SpeechRecognition" in window || "webkitSpeechRecognition" in window
if (!hasNativeRecognitionSupport) return
const SpeechRecognition = window.SpeechRecognition ?? window.webkitSpeechRecognition
const recognition = new SpeechRecognition()
recognition.continuous = false
recognition.interimResults = false
const language = this.sourceLanguage.value === 'auto'
? this.normalizeLanguageCode((await this.detectLanguage(this.inputText.value)).detectedLanguage)
: this.sourceLanguage.value
recognition.lang = this.getFullLanguageCode(language)
recognition.onstart = () => {
this.micButton.style.backgroundColor = "var(--google-red)"
this.micButton.style.color = "white"
}
recognition.onend = () => {
this.micButton.style.backgroundColor = ""
this.micButton.style.color = ""
}
recognition.onresult = (event) => {
console.log(event.results)
const [{ transcript }] = event.results[0]
this.inputText.value = transcript
this.translate()
}
recognition.onerror = (event) => {
console.error('Error de reconocimiento de voz: ', event.error)
}
recognition.start()
}
copyTranslation() {
const text = this.outputText.textContent
if (!text) {this.mostrarGoogle('❌ No hay texto para copiar', 'error'); return}
navigator.clipboard.writeText(text)
this.mostrarGoogle('✅ Texto copiado!', 'success')
}
async mostrarGoogle(mensaje, tipo) {
const notificacion = document.createElement('div');
notificacion.className = 'google-notification';
notificacion.textContent = 'Texto copiado';
document.body.appendChild(notificacion);
setTimeout(() => notificacion.classList.add('show'), 10);
setTimeout(() => {
notificacion.classList.remove('show');
setTimeout(() => notificacion.remove(), 300);
}, 2000);
}
speakTranslation() {
const hasNativeSupportSynthesis = "SpeechSynthesis" in window
if (!hasNativeSupportSynthesis) return
const text = this.outputText.textContent
if (!text) return
const utterance = new SpeechSynthesisUtterance(text)
utterance.lang = this.getFullLanguageCode(this.targetLanguage.value)
utterance.rate = 0.8
utterance.onstart = () => {
this.speakerButton.style.backgroundColor = "var(--google-green)"
this.speakerButton.style.color = "white"
}
utterance.onend = () => {
this.speakerButton.style.backgroundColor = ""
this.speakerButton.style.color = ""
}
window.speechSynthesis.speak(utterance)
}
async detectLanguage (text) {
try {
if (!this.currentDetector) {
// Aplana el array para que solo haya strings
const langs = Object.values(GoogleTranslator.FULL_LANGUAGES_CODES).flat()
this.currentDetector = await window.LanguageDetector.create({
expectedInputLanguages: langs
})
}
const results = await this.currentDetector.detect(text)
const detectedLanguage = results[0]?.detectedLanguage
const confidence = results[0]?.confidence
return {
detectedLanguage: detectedLanguage === 'und' ? GoogleTranslator.DEFAULT_SOURCE_LANGUAGE : detectedLanguage,
confidence
}
} catch (error) {
console.error("No he podido averiguar el idioma: ", error)
return GoogleTranslator.DEFAULT_SOURCE_LANGUAGE
}
}
normalizeLanguageCode(code) {
if (code === 'ja-Latn') return 'ja'
return code
}
}
const googleTranslator = new GoogleTranslator()
window.googleTranslator = googleTranslator