Spaces:
Running
Running
Remove server-based TTS libraries and rely on Web Speech API in the client
Browse files- app.py +5 -4
- models/chatbot_model.py +10 -14
- requirements.txt +0 -0
- static/js/scripts.js +13 -9
app.py
CHANGED
@@ -46,17 +46,18 @@ def get_bot_response():
|
|
46 |
user_input = request.form.get('message', '').strip()
|
47 |
if not user_input:
|
48 |
logger.warning("Mensaje vac铆o recibido del usuario.")
|
49 |
-
return jsonify({'response': "Por favor, ingresa un mensaje."
|
50 |
|
51 |
response_data = chatbot.generate_response(user_input)
|
|
|
52 |
response_text = response_data.get('text', "Lo siento, no pude procesar tu mensaje.")
|
53 |
-
audio_path = response_data.get('audio_path', '')
|
54 |
|
55 |
-
|
|
|
56 |
|
57 |
except Exception as e:
|
58 |
logger.error(f"Error en /get_response: {e}")
|
59 |
-
return jsonify({'response': "Lo siento, ha ocurrido un error al procesar tu solicitud."
|
60 |
|
61 |
if __name__ == '__main__':
|
62 |
# Ajustamos para leer la variable de entorno PORT (o usar 7860 por defecto)
|
|
|
46 |
user_input = request.form.get('message', '').strip()
|
47 |
if not user_input:
|
48 |
logger.warning("Mensaje vac铆o recibido del usuario.")
|
49 |
+
return jsonify({'response': "Por favor, ingresa un mensaje."}), 400
|
50 |
|
51 |
response_data = chatbot.generate_response(user_input)
|
52 |
+
# Obtenemos el texto, pero ignoramos audio_path, ya que no generamos audio en el servidor
|
53 |
response_text = response_data.get('text', "Lo siento, no pude procesar tu mensaje.")
|
|
|
54 |
|
55 |
+
# Devolvemos solo el texto (y, si quieres, emoci贸n, confianza, etc.)
|
56 |
+
return jsonify({'response': response_text})
|
57 |
|
58 |
except Exception as e:
|
59 |
logger.error(f"Error en /get_response: {e}")
|
60 |
+
return jsonify({'response': "Lo siento, ha ocurrido un error al procesar tu solicitud."}), 500
|
61 |
|
62 |
if __name__ == '__main__':
|
63 |
# Ajustamos para leer la variable de entorno PORT (o usar 7860 por defecto)
|
models/chatbot_model.py
CHANGED
@@ -7,7 +7,7 @@ import os
|
|
7 |
import logging
|
8 |
from typing import Tuple, Dict, Any
|
9 |
import json
|
10 |
-
import pyttsx3
|
11 |
|
12 |
class MentalHealthChatbot:
|
13 |
def __init__(self, model_path: str = 'models/bert_emotion_model'):
|
@@ -120,7 +120,7 @@ class MentalHealthChatbot:
|
|
120 |
return 'CONFUSI脫N', 0.0
|
121 |
|
122 |
def generate_response(self, user_input: str) -> Dict[str, Any]:
|
123 |
-
"""Genera una respuesta basada en el input del usuario."""
|
124 |
try:
|
125 |
processed_text = self.preprocess_text(user_input)
|
126 |
self.logger.info(f"Texto procesado: {processed_text}")
|
@@ -136,14 +136,15 @@ class MentalHealthChatbot:
|
|
136 |
response = np.random.choice(responses)
|
137 |
self.logger.info(f"Respuesta seleccionada: {response}")
|
138 |
|
139 |
-
|
|
|
140 |
|
141 |
self.update_conversation_history(user_input, response, emotion)
|
142 |
self.save_conversation_history()
|
143 |
|
144 |
return {
|
145 |
'text': response,
|
146 |
-
'audio_path': audio_path,
|
147 |
'emotion': emotion,
|
148 |
'confidence': confidence,
|
149 |
'timestamp': datetime.now().isoformat()
|
@@ -153,21 +154,18 @@ class MentalHealthChatbot:
|
|
153 |
self.logger.error(f"Error al generar respuesta: {str(e)}")
|
154 |
return {
|
155 |
'text': "Lo siento, ha ocurrido un error. 驴Podr铆as intentarlo de nuevo?",
|
156 |
-
'audio_path': None,
|
157 |
'emotion': 'ERROR',
|
158 |
'confidence': 0.0,
|
159 |
'timestamp': datetime.now().isoformat()
|
160 |
}
|
161 |
|
|
|
|
|
162 |
def generate_audio(self, text: str) -> str:
|
163 |
-
|
164 |
-
Genera el audio para la respuesta y devuelve una ruta local.
|
165 |
-
Nota: Si quieres servir este audio v铆a HTTP,
|
166 |
-
necesitar谩s un endpoint que lo sirva desde /tmp/audio.
|
167 |
-
"""
|
168 |
try:
|
169 |
filename = f"response_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.mp3"
|
170 |
-
# Guardar audios en /tmp/audio
|
171 |
file_path = os.path.join(self.audio_dir, filename)
|
172 |
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
173 |
|
@@ -188,13 +186,12 @@ class MentalHealthChatbot:
|
|
188 |
engine.runAndWait()
|
189 |
|
190 |
self.logger.info(f"Audio generado y guardado en {file_path}")
|
191 |
-
|
192 |
-
# Devolvemos la ruta local en /tmp/audio
|
193 |
return file_path
|
194 |
|
195 |
except Exception as e:
|
196 |
self.logger.error(f"Error al generar audio: {str(e)}")
|
197 |
return None
|
|
|
198 |
|
199 |
def update_conversation_history(self, user_input: str, response: str, emotion: str):
|
200 |
"""Actualiza el historial de conversaci贸n en memoria."""
|
@@ -216,7 +213,6 @@ class MentalHealthChatbot:
|
|
216 |
def save_conversation_history(self):
|
217 |
"""Guarda el historial de conversaci贸n en un archivo dentro de /tmp."""
|
218 |
try:
|
219 |
-
# Guardamos en /tmp/conversations
|
220 |
filename = f"{self.conversations_dir}/chat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
221 |
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
222 |
|
|
|
7 |
import logging
|
8 |
from typing import Tuple, Dict, Any
|
9 |
import json
|
10 |
+
# import pyttsx3 # Comentado para no usar TTS en el servidor
|
11 |
|
12 |
class MentalHealthChatbot:
|
13 |
def __init__(self, model_path: str = 'models/bert_emotion_model'):
|
|
|
120 |
return 'CONFUSI脫N', 0.0
|
121 |
|
122 |
def generate_response(self, user_input: str) -> Dict[str, Any]:
|
123 |
+
"""Genera una respuesta basada en el input del usuario, sin generar audio en el servidor."""
|
124 |
try:
|
125 |
processed_text = self.preprocess_text(user_input)
|
126 |
self.logger.info(f"Texto procesado: {processed_text}")
|
|
|
136 |
response = np.random.choice(responses)
|
137 |
self.logger.info(f"Respuesta seleccionada: {response}")
|
138 |
|
139 |
+
# Comentamos la generaci贸n de audio en el servidor
|
140 |
+
# audio_path = self.generate_audio(response)
|
141 |
|
142 |
self.update_conversation_history(user_input, response, emotion)
|
143 |
self.save_conversation_history()
|
144 |
|
145 |
return {
|
146 |
'text': response,
|
147 |
+
# 'audio_path': audio_path, # Comentado
|
148 |
'emotion': emotion,
|
149 |
'confidence': confidence,
|
150 |
'timestamp': datetime.now().isoformat()
|
|
|
154 |
self.logger.error(f"Error al generar respuesta: {str(e)}")
|
155 |
return {
|
156 |
'text': "Lo siento, ha ocurrido un error. 驴Podr铆as intentarlo de nuevo?",
|
157 |
+
# 'audio_path': None,
|
158 |
'emotion': 'ERROR',
|
159 |
'confidence': 0.0,
|
160 |
'timestamp': datetime.now().isoformat()
|
161 |
}
|
162 |
|
163 |
+
# Comentamos toda la funci贸n generate_audio si no se usa
|
164 |
+
"""
|
165 |
def generate_audio(self, text: str) -> str:
|
166 |
+
# Genera el audio en el servidor (COMENTADO).
|
|
|
|
|
|
|
|
|
167 |
try:
|
168 |
filename = f"response_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.mp3"
|
|
|
169 |
file_path = os.path.join(self.audio_dir, filename)
|
170 |
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
171 |
|
|
|
186 |
engine.runAndWait()
|
187 |
|
188 |
self.logger.info(f"Audio generado y guardado en {file_path}")
|
|
|
|
|
189 |
return file_path
|
190 |
|
191 |
except Exception as e:
|
192 |
self.logger.error(f"Error al generar audio: {str(e)}")
|
193 |
return None
|
194 |
+
"""
|
195 |
|
196 |
def update_conversation_history(self, user_input: str, response: str, emotion: str):
|
197 |
"""Actualiza el historial de conversaci贸n en memoria."""
|
|
|
213 |
def save_conversation_history(self):
|
214 |
"""Guarda el historial de conversaci贸n en un archivo dentro de /tmp."""
|
215 |
try:
|
|
|
216 |
filename = f"{self.conversations_dir}/chat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
217 |
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
218 |
|
requirements.txt
CHANGED
Binary files a/requirements.txt and b/requirements.txt differ
|
|
static/js/scripts.js
CHANGED
@@ -24,13 +24,15 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
24 |
|
25 |
fetch('/get_response', {
|
26 |
method: 'POST',
|
27 |
-
body: new URLSearchParams({'message': message}),
|
28 |
})
|
29 |
.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
|
30 |
.then(data => {
|
31 |
removeTypingIndicator();
|
32 |
addMessageToChatbox('Asistente', data.response);
|
33 |
-
|
|
|
|
|
34 |
})
|
35 |
.catch(error => {
|
36 |
removeTypingIndicator();
|
@@ -98,13 +100,15 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
98 |
};
|
99 |
}
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
const
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
108 |
}
|
109 |
}
|
110 |
|
|
|
24 |
|
25 |
fetch('/get_response', {
|
26 |
method: 'POST',
|
27 |
+
body: new URLSearchParams({ 'message': message }),
|
28 |
})
|
29 |
.then(response => response.ok ? response.json() : response.json().then(err => Promise.reject(err)))
|
30 |
.then(data => {
|
31 |
removeTypingIndicator();
|
32 |
addMessageToChatbox('Asistente', data.response);
|
33 |
+
|
34 |
+
// En lugar de reproducir audio del servidor, usamos TTS en el navegador
|
35 |
+
speakResponse(data.response);
|
36 |
})
|
37 |
.catch(error => {
|
38 |
removeTypingIndicator();
|
|
|
100 |
};
|
101 |
}
|
102 |
|
103 |
+
// Eliminamos la funci贸n playResponse y a帽adimos speakResponse
|
104 |
+
function speakResponse(text) {
|
105 |
+
if ('speechSynthesis' in window) {
|
106 |
+
const utterance = new SpeechSynthesisUtterance(text);
|
107 |
+
utterance.lang = 'es-ES'; // Ajusta el idioma si lo deseas
|
108 |
+
// utterance.rate = 1.0; // Puedes ajustar la velocidad
|
109 |
+
window.speechSynthesis.speak(utterance);
|
110 |
+
} else {
|
111 |
+
console.warn("Este navegador no soporta Speech Synthesis.");
|
112 |
}
|
113 |
}
|
114 |
|