File size: 13,522 Bytes
2e947b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let recognition = null;
let isProcessingSpeech = false;
let isPlayingAudio = false;
const STOP_WORDS = ['alto', 'detente', 'permiteme', 'callate', 'silencio'];

// Elementos del DOM
const chatBox = document.getElementById('chatBox');
const textInput = document.getElementById('textInput');
const sendTextButton = document.getElementById('sendText');
const modoSelect = document.getElementById('modoSelect');
const modeloSelect = document.getElementById('modeloSelect');
const vozSelect = document.getElementById('vozSelect');
const configForm = document.getElementById('configForm');
const statusLabel = document.getElementById('statusLabel');

// Manejar guardado de configuraci贸n
if (configForm) {
    configForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const config = {
            GOOGLE_API_KEY: document.getElementById('googleApiKey').value,
            HUGGINGFACE_TOKEN: document.getElementById('huggingfaceToken').value,
            OPENAI_API_KEY: document.getElementById('openaiApiKey').value
        };

        try {
            const response = await fetch('/guardar_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            });

            const data = await response.json();
            if (data.success) {
                alert('Configuraci贸n guardada exitosamente');
            } else {
                alert('Error al guardar la configuraci贸n: ' + data.error);
            }
        } catch (error) {
            alert('Error al guardar la configuraci贸n: ' + error);
        }
    });
}

// Manejar cambio de modelo AI
if (modeloSelect) {
    modeloSelect.addEventListener('change', async function() {
        const response = await fetch('/cambiar_modelo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ modelo: this.value })
        });

        const data = await response.json();
        if (!data.success) {
            alert('Error al cambiar el modelo: ' + data.error);
        }
    });
}

// Manejar cambio de modelo de voz
if (vozSelect) {
    vozSelect.addEventListener('change', async function() {
        const response = await fetch('/cambiar_voz', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ voz: this.value })
        });

        const data = await response.json();
        if (!data.success) {
            alert('Error al cambiar el modelo de voz: ' + data.error);
        }
    });
}

// Manejar cambio de modo
modoSelect.addEventListener('change', async function() {
    const response = await fetch('/cambiar_modo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ modo: this.value })
    });

    const data = await response.json();
    if (data.success) {
        addMessage(data.mensaje, 'bot');
        if (data.audio) {
            await playAudio(data.audio);
        }
        updateStatus('Esperando activaci贸n...');
    }
});

// Funci贸n para verificar si el texto contiene palabras de parada
function containsStopWord(text) {
    const lowerText = text.toLowerCase();
    return STOP_WORDS.some(word => lowerText.includes(word));
}

// Funci贸n para reproducir audio
async function playAudio(base64Audio) {
    try {
        console.log('Preparando reproducci贸n de audio...');
        isPlayingAudio = true;
        
        // Detener completamente el reconocimiento
        if (recognition) {
            recognition.stop();
            recognition.abort();
            await new Promise(resolve => setTimeout(resolve, 500));
        }
        
        updateStatus('Reproduciendo respuesta...');
        const audio = new Audio('data:audio/mp3;base64,' + base64Audio);
        
        // Permitir interrupciones durante la reproducci贸n
        recognition.start();
        
        audio.onended = () => {
            console.log('Audio reproducido completamente');
            isPlayingAudio = false;
            updateStatus('Escuchando...');
        };
        
        audio.play();
        
    } catch (error) {
        console.error('Error reproduciendo audio:', error);
        isPlayingAudio = false;
        updateStatus('Error al reproducir audio. Escuchando...');
        if (!isProcessingSpeech) {
            recognition.start();
        }
    }
}

// Funci贸n para agregar mensaje al chat
function addMessage(text, sender) {
    if (!text || !sender) {
        console.error('Error: texto o remitente faltante', { text, sender });
        return;
    }
    
    const chatBox = document.getElementById('chatBox');
    if (!chatBox) {
        console.error('Error cr铆tico: No se encontr贸 el elemento chatBox');
        return;
    }
    
    try {
        console.log('Agregando mensaje al chat:', { text, sender });
        
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}-message`;
        
        const iconSpan = document.createElement('span');
        iconSpan.className = 'message-icon';
        iconSpan.textContent = sender === 'user' ? '馃懁' : '馃';
        
        const textSpan = document.createElement('span');
        textSpan.className = 'message-text';
        textSpan.textContent = text;
        
        messageDiv.appendChild(iconSpan);
        messageDiv.appendChild(textSpan);
        chatBox.appendChild(messageDiv);
        
        // Hacer scroll al 煤ltimo mensaje
        chatBox.scrollTop = chatBox.scrollHeight;
        
        console.log('Mensaje agregado exitosamente');
    } catch (error) {
        console.error('Error al agregar mensaje:', error);
    }
}

// Agregar m煤ltiples mensajes
function addMessages(messages) {
    messages.forEach(msg => {
        addMessage(msg.text, msg.sender);
    });
}

// Funci贸n para actualizar el estado
function updateStatus(text) {
    const statusLabel = document.getElementById('statusLabel');
    if (statusLabel) {
        statusLabel.textContent = text;
        statusLabel.style.display = 'block'; // Asegurar que sea visible
        console.log('Estado actualizado:', text);
    } else {
        console.error('No se encontr贸 el elemento statusLabel');
    }
}

// Funci贸n para procesar la respuesta del servidor
async function processServerResponse(data, userText) {
    try {
        console.log('Procesando respuesta del servidor:', data);
        
        // Mostrar el mensaje del usuario
        addMessage(userText, 'user');
        
        if (data.success && data.texto) {
            // Mostrar la respuesta del bot
            console.log('Mostrando respuesta del bot:', data.texto);
            addMessage(data.texto, 'bot');
            
            // Reproducir el audio si existe y no se dijo una palabra de parada
            if (data.audio && !containsStopWord(userText)) {
                await playAudio(data.audio);
            }
        } else {
            const errorMessage = data.error || 'Error desconocido';
            console.error('Error en la respuesta:', errorMessage);
            addMessage('Lo siento, hubo un error: ' + errorMessage, 'bot');
        }
    } catch (error) {
        console.error('Error procesando respuesta:', error);
        addMessage('Lo siento, ocurri贸 un error inesperado.', 'bot');
    }
}

// Inicializar reconocimiento de voz
function initializeSpeechRecognition() {
    if ('webkitSpeechRecognition' in window) {
        recognition = new webkitSpeechRecognition();
        recognition.continuous = true;  // Cambiar a true para permitir interrupciones
        recognition.interimResults = true;
        recognition.lang = 'es-ES';

        recognition.onstart = function() {
            console.log('Reconocimiento de voz iniciado');
            updateStatus('Escuchando...');
        };

        recognition.onend = function() {
            console.log('Reconocimiento de voz terminado');
            if (!isProcessingSpeech) {
                console.log('Reiniciando reconocimiento...');
                updateStatus('Escuchando...');
                setTimeout(() => recognition.start(), 500);
            }
        };

        recognition.onerror = function(event) {
            console.error('Error en reconocimiento de voz:', event.error);
            if (!isProcessingSpeech && event.error !== 'no-speech') {
                setTimeout(() => recognition.start(), 1000);
            }
        };

        recognition.onresult = async function(event) {
            let finalTranscript = '';
            let interimTranscript = '';

            for (let i = event.resultIndex; i < event.results.length; ++i) {
                const transcript = event.results[i][0].transcript;
                
                if (event.results[i].isFinal) {
                    finalTranscript = transcript;
                    console.log('Texto final:', finalTranscript);
                    
                    // Verificar si es una palabra de parada
                    if (containsStopWord(finalTranscript)) {
                        console.log('Palabra de parada detectada, deteniendo audio...');
                        const audio = document.querySelector('audio');
                        if (audio) {
                            audio.pause();
                            audio.currentTime = 0;
                        }
                        isPlayingAudio = false;
                        updateStatus('Audio detenido. Escuchando...');
                        continue;
                    }
                    
                    if (!isProcessingSpeech) {
                        isProcessingSpeech = true;
                        updateStatus('Procesando...');
                        
                        try {
                            console.log('Enviando texto al servidor:', finalTranscript);
                            const response = await fetch('/procesar_voz', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ texto: finalTranscript })
                            });
                            
                            const data = await response.json();
                            console.log('Respuesta recibida:', data);
                            await processServerResponse(data, finalTranscript);
                            
                        } catch (error) {
                            console.error('Error al procesar voz:', error);
                            updateStatus('Error de conexi贸n. Escuchando...');
                            addMessage('Lo siento, hubo un error de conexi贸n.', 'bot');
                        }
                        
                        isProcessingSpeech = false;
                    }
                } else {
                    interimTranscript = transcript;
                    updateStatus(`Escuchando: ${interimTranscript}`);
                }
            }
        };

        // Iniciar reconocimiento
        recognition.start();
        updateStatus('Escuchando...');
        
    } else {
        console.error('El reconocimiento de voz no est谩 soportado en este navegador');
        alert('Tu navegador no soporta el reconocimiento de voz. Por favor, usa Chrome.');
        updateStatus('Reconocimiento de voz no soportado');
    }
}

// Manejar env铆o de texto
sendTextButton.addEventListener('click', async () => {
    const text = textInput.value.trim();
    if (text) {
        updateStatus('Procesando...');
        addMessage(text, 'user');
        
        try {
            const response = await fetch('/procesar_voz', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ texto: text })
            });
            
            const data = await response.json();
            await processServerResponse(data, text);
            
            textInput.value = '';
            updateStatus('Esperando activaci贸n...');
        } catch (error) {
            console.error('Error:', error);
            updateStatus('Error de conexi贸n');
        }
    }
});

// Inicializar cuando se carga la p谩gina
document.addEventListener('DOMContentLoaded', () => {
    console.log('P谩gina cargada, verificando elementos...');
    
    // Verificar que existan los elementos necesarios
    const chatBox = document.getElementById('chatBox');
    const statusLabel = document.getElementById('statusLabel');
    
    if (!chatBox) {
        console.error('Error cr铆tico: No se encontr贸 el elemento chatBox');
        return;
    }
    
    if (!statusLabel) {
        console.error('Error cr铆tico: No se encontr贸 el elemento statusLabel');
        return;
    }
    
    // Asegurar que el statusLabel sea visible
    statusLabel.style.display = 'block';
    
    console.log('Elementos encontrados, inicializando reconocimiento de voz...');
    initializeSpeechRecognition();
    
    // Agregar mensaje de bienvenida
    addMessage('隆Hola! Soy tu asistente virtual. 驴En qu茅 puedo ayudarte?', 'bot');
});