File size: 9,625 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
        // Variables globales
let currentMode = 'seguros';
let currentModel = 'Gemini 8b';
let currentTTS = 'EDGE';
let isListening = false;
let recognition = null;

function playAudio(button, text) {
    const icon = button ? button.querySelector('i') : null;
    text = text || (button ? button.getAttribute('data-text') : '');
    
    if (!text) {
        console.error('No text provided for audio');
        return;
    }
    
    if (button) {
        icon.className = 'fas fa-spinner fa-spin';
        button.disabled = true;
    }
    
    fetch('/generate_audio', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
            text: text,
            model: currentTTS
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.audio_url) {
            console.log(`Reproduciendo audio generado con modelo: ${data.model_used}`);
            const audio = new Audio(window.location.origin + data.audio_url);
            
            if (button) {
                audio.onplay = () => {
                    icon.className = 'fas fa-pause';
                };
                
                audio.onended = () => {
                    icon.className = 'fas fa-play';
                    button.disabled = false;
                };
            }
            
            audio.onerror = (e) => {
                console.error('Error reproduciendo audio:', e);
                if (button) {
                    icon.className = 'fas fa-play';
                    button.disabled = false;
                }
                appendBotMessage("Error reproduciendo el audio. Intente de nuevo.");
            };
            
            audio.play().catch(error => {
                console.error('Error playing audio:', error);
                if (button) {
                    icon.className = 'fas fa-play';
                    button.disabled = false;
                }
                appendBotMessage("Error reproduciendo el audio. Intente de nuevo.");
            });
        } else {
            throw new Error('No audio URL in response');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (button) {
            icon.className = 'fas fa-play';
            button.disabled = false;
        }
        appendBotMessage(`Error generando el audio: ${error.message}`);
    });
}

// Agregar esto para manejar nuevos mensajes din谩micamente
function appendBotMessage(message) {
    const chatMessages = document.getElementById('chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message bot-message';
    messageDiv.innerHTML = `

        <div class="message-content">${message}</div>

        <button onclick="playAudio(this)" data-text="${message}" class="play-button">

            <i class="fas fa-play"></i>

        </button>

    `;
    chatMessages.appendChild(messageDiv);
}

async function sendMessage() {
    const input = document.getElementById('user-input');
    const text = input.value.trim();
    
    if (text) {
        // Agregar mensaje del usuario
        const chatMessages = document.getElementById('chat-messages');
        const userDiv = document.createElement('div');
        userDiv.className = 'message user-message';
        userDiv.textContent = text;
        chatMessages.appendChild(userDiv);
        
        // Limpiar input
        input.value = '';
        
        try {
            // Enviar mensaje al backend con el modo actual
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ 
                    message: text,
                    mode: currentMode 
                })
            });

            const data = await response.json();
            
            if (data.response) {
                // Agregar respuesta del bot
                appendBotMessage(data.response);
                // Auto-reproducir respuesta
                const lastButton = document.querySelector('.bot-message:last-child .play-button');
                if (lastButton) {
                    playAudio(lastButton);
                }
            }
        } catch (error) {
            console.error('Error:', error);
            appendBotMessage("Lo siento, hubo un error al procesar tu mensaje.");
        }
    }
}

async function changeMode(mode) {
    try {
        const response = await fetch('/change_mode', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ mode })
        });
        
        if (response.ok) {
            currentMode = mode;
            appendBotMessage(`Modo cambiado a: ${mode}`);
            playAudio(null, `Modo de operaci贸n cambiado a ${mode}`);
        }
    } catch (error) {
        console.error('Error changing mode:', error);
        appendBotMessage("Error al cambiar el modo de operaci贸n");
    }
}

async function changeModel(model) {
    try {
        const response = await fetch('/change_model', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ model })
        });
        
        if (response.ok) {
            currentModel = model;
            appendBotMessage(`Modelo de IA cambiado a: ${model}`);
            playAudio(null, `Modelo de inteligencia artificial cambiado a ${model}`);
        }
    } catch (error) {
        console.error('Error changing model:', error);
        appendBotMessage("Error al cambiar el modelo de IA");
    }
}

// Inicializar reconocimiento de voz
function initSpeechRecognition() {
    if ('webkitSpeechRecognition' in window) {
        recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = true;
        recognition.lang = 'es-ES';

        recognition.onresult = function(event) {
            const result = event.results[event.results.length - 1];
            if (result.isFinal) {
                const text = result.item(0).transcript;
                document.getElementById('user-input').value = text;
                sendMessage();
            }
        };

        recognition.onerror = function(event) {
            console.error('Error en reconocimiento:', event.error);
            toggleVAD();
        };
    } else {
        console.error('Reconocimiento de voz no soportado');
    }
}

// Funci贸n para cambiar TTS
async function changeTTS(model) {
    try {
        const response = await fetch('/change_tts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ model })
        });
        
        if (response.ok) {
            currentTTS = model;
            appendBotMessage(`Modelo de voz cambiado a: ${model}`);
            playAudio(null, `Voz del sistema cambiada a ${model}`);
        }
    } catch (error) {
        console.error('Error changing TTS:', error);
        appendBotMessage("Error al cambiar el modelo de voz");
    }
}

// Funci贸n para activar/desactivar VAD
function toggleVAD() {
    const vadButton = document.querySelector('.vad-button');
    const vadStatus = document.getElementById('vad-status');
    
    if (!isListening) {
        if (recognition) {
            recognition.start();
            isListening = true;
            vadButton.classList.remove('inactive');
            vadButton.classList.add('active');
            vadButton.innerHTML = '<i class="fas fa-microphone"></i> Escuchando';
            
            // Mostrar estado de escucha
            vadStatus.classList.add('listening');
            vadStatus.innerHTML = '馃帳 Escuchando...';
            
            // Reproducir sonido de inicio
            playAudio(null, "Sistema activado. Puede hablar.");
        }
    } else {
        if (recognition) {
            recognition.stop();
            isListening = false;
            vadButton.classList.remove('active');
            vadButton.classList.add('inactive');
            vadButton.innerHTML = '<i class="fas fa-microphone-slash"></i> Activar micr贸fono';
            
            // Ocultar estado de escucha
            vadStatus.classList.remove('listening');
            vadStatus.innerHTML = '';
            
            // Mensaje de desactivaci贸n
            playAudio(null, "Sistema en pausa.");
        }
    }
}

// Inicializar cuando el documento est茅 listo
document.addEventListener('DOMContentLoaded', function() {
    initSpeechRecognition();
    // Iniciar VAD autom谩ticamente
    setTimeout(() => {
        toggleVAD(); // Activar el VAD al inicio
        appendBotMessage("Sistema iniciado. Modelos cargados correctamente. Escuchando...");
    }, 1000);
});

// Permitir enviar con Enter
document.getElementById('user-input')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendMessage();
    }
});