Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, send_from_directory, request, jsonify, render_template
|
2 |
+
from flask_cors import CORS
|
3 |
+
import os
|
4 |
+
from pathlib import Path
|
5 |
+
from audio_utils import AudioUtils
|
6 |
+
import logging
|
7 |
+
import google.generativeai as genai
|
8 |
+
import yaml
|
9 |
+
from inference import InferenceManager
|
10 |
+
from chat_log import ChatLogger
|
11 |
+
|
12 |
+
# Configurar logging
|
13 |
+
logging.basicConfig(level=logging.DEBUG)
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
app = Flask(__name__)
|
17 |
+
CORS(app)
|
18 |
+
|
19 |
+
# Cargar configuraci贸n
|
20 |
+
with open('config.yaml', 'r') as file:
|
21 |
+
config = yaml.safe_load(file)
|
22 |
+
|
23 |
+
# Inicializar componentes con mensajes
|
24 |
+
try:
|
25 |
+
logger.info("Iniciando sistema...")
|
26 |
+
|
27 |
+
logger.info("Configurando API de Google...")
|
28 |
+
genai.configure(api_key=config.get('GOOGLE_API_KEY', ''))
|
29 |
+
|
30 |
+
logger.info("Inicializando sistema de inferencia...")
|
31 |
+
inference = InferenceManager(config)
|
32 |
+
|
33 |
+
logger.info("Inicializando registro de chat...")
|
34 |
+
chat_logger = ChatLogger()
|
35 |
+
|
36 |
+
logger.info("Inicializando sistema de audio...")
|
37 |
+
audio_utils = AudioUtils()
|
38 |
+
|
39 |
+
logger.info("Sistema iniciado correctamente")
|
40 |
+
except Exception as e:
|
41 |
+
logger.error(f"Error cr铆tico inicializando el sistema: {e}")
|
42 |
+
raise e
|
43 |
+
|
44 |
+
# Configurar el directorio de archivos temporales
|
45 |
+
TEMP_AUDIO_DIR = Path("static/temp_audio")
|
46 |
+
TEMP_AUDIO_DIR.mkdir(parents=True, exist_ok=True)
|
47 |
+
|
48 |
+
@app.after_request
|
49 |
+
def after_request(response):
|
50 |
+
# Agregar headers necesarios para ngrok
|
51 |
+
response.headers.add('Accept-Ranges', 'bytes')
|
52 |
+
response.headers.add('Access-Control-Allow-Origin', '*')
|
53 |
+
logger.debug(f"Response headers: {dict(response.headers)}")
|
54 |
+
return response
|
55 |
+
|
56 |
+
@app.route('/temp_audio/<path:filename>')
|
57 |
+
def serve_audio(filename):
|
58 |
+
try:
|
59 |
+
logger.info(f"Attempting to serve audio file: {filename}")
|
60 |
+
file_path = TEMP_AUDIO_DIR / filename
|
61 |
+
|
62 |
+
if not file_path.exists():
|
63 |
+
logger.error(f"File not found: {file_path}")
|
64 |
+
return jsonify({'error': 'File not found'}), 404
|
65 |
+
|
66 |
+
if not filename.endswith(('.wav', '.mp3')):
|
67 |
+
logger.error(f"Invalid file format: {filename}")
|
68 |
+
return jsonify({'error': 'Invalid file format'}), 400
|
69 |
+
|
70 |
+
logger.info(f"Serving file from: {file_path}")
|
71 |
+
response = send_from_directory(str(TEMP_AUDIO_DIR), filename)
|
72 |
+
response.headers['Content-Type'] = 'audio/wav' if filename.endswith('.wav') else 'audio/mpeg'
|
73 |
+
response.headers['Cache-Control'] = 'no-cache'
|
74 |
+
return response
|
75 |
+
|
76 |
+
except Exception as e:
|
77 |
+
logger.error(f"Error serving audio file: {e}", exc_info=True)
|
78 |
+
return jsonify({'error': str(e)}), 500
|
79 |
+
|
80 |
+
@app.route('/generate_audio', methods=['POST'])
|
81 |
+
def generate_audio():
|
82 |
+
try:
|
83 |
+
text = request.json.get('text')
|
84 |
+
model = request.json.get('model', 'EDGE') # EDGE como default
|
85 |
+
logger.info(f"Generando audio para texto: '{text}' usando modelo: {model}")
|
86 |
+
|
87 |
+
if not text:
|
88 |
+
logger.error("No se proporcion贸 texto")
|
89 |
+
return jsonify({'error': 'No text provided'}), 400
|
90 |
+
|
91 |
+
try:
|
92 |
+
temp_audio_utils = AudioUtils(model_name=model)
|
93 |
+
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
94 |
+
|
95 |
+
if not audio_file:
|
96 |
+
logger.error(f"Fallo al generar audio con {model}, intentando con EDGE")
|
97 |
+
temp_audio_utils = AudioUtils(model_name='EDGE')
|
98 |
+
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
99 |
+
except Exception as e:
|
100 |
+
logger.error(f"Error con modelo {model}, usando EDGE: {e}")
|
101 |
+
temp_audio_utils = AudioUtils(model_name='EDGE')
|
102 |
+
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
103 |
+
|
104 |
+
if audio_file:
|
105 |
+
audio_url = f'/temp_audio/{audio_file}'
|
106 |
+
logger.info(f"Audio generado: {audio_url}")
|
107 |
+
|
108 |
+
file_path = TEMP_AUDIO_DIR / audio_file
|
109 |
+
if not file_path.exists():
|
110 |
+
logger.error(f"Archivo no encontrado: {file_path}")
|
111 |
+
return jsonify({
|
112 |
+
'error': 'Generated file not found',
|
113 |
+
'details': 'El archivo de audio no se gener贸 correctamente'
|
114 |
+
}), 500
|
115 |
+
|
116 |
+
return jsonify({
|
117 |
+
'audio_url': audio_url,
|
118 |
+
'model_used': temp_audio_utils.current_model
|
119 |
+
})
|
120 |
+
|
121 |
+
return jsonify({
|
122 |
+
'error': 'Failed to generate audio',
|
123 |
+
'details': 'No se pudo generar el audio con ning煤n modelo'
|
124 |
+
}), 500
|
125 |
+
|
126 |
+
except Exception as e:
|
127 |
+
logger.error(f"Error cr铆tico generando audio: {e}", exc_info=True)
|
128 |
+
return jsonify({
|
129 |
+
'error': str(e),
|
130 |
+
'details': 'Error interno del servidor al generar audio'
|
131 |
+
}), 500
|
132 |
+
|
133 |
+
@app.route('/static/<path:path>')
|
134 |
+
def send_static(path):
|
135 |
+
logger.debug(f"Serving static file: {path}")
|
136 |
+
return send_from_directory('static', path)
|
137 |
+
|
138 |
+
@app.route('/')
|
139 |
+
def home():
|
140 |
+
# Agregar mensajes iniciales
|
141 |
+
initial_messages = [{
|
142 |
+
'role': 'assistant',
|
143 |
+
'content': 'Sistema iniciado. Todos los modelos cargados correctamente.'
|
144 |
+
}]
|
145 |
+
return render_template('chat.html', messages=initial_messages)
|
146 |
+
|
147 |
+
@app.route('/chat', methods=['POST'])
|
148 |
+
def chat():
|
149 |
+
try:
|
150 |
+
message = request.json.get('message')
|
151 |
+
mode = request.json.get('mode', 'seguros') # Modo por defecto
|
152 |
+
|
153 |
+
if not message:
|
154 |
+
return jsonify({'error': 'No message provided'}), 400
|
155 |
+
|
156 |
+
# Registrar mensaje del usuario
|
157 |
+
chat_logger.log_message(message, is_user=True)
|
158 |
+
|
159 |
+
# Obtener respuesta usando el sistema de inferencia
|
160 |
+
response = inference.get_response(message, mode)
|
161 |
+
|
162 |
+
if response:
|
163 |
+
# Registrar respuesta del bot
|
164 |
+
chat_logger.log_message(response, is_user=False)
|
165 |
+
|
166 |
+
return jsonify({
|
167 |
+
'response': response
|
168 |
+
})
|
169 |
+
|
170 |
+
return jsonify({'error': 'No response generated'}), 500
|
171 |
+
|
172 |
+
except Exception as e:
|
173 |
+
logger.error(f"Error in chat endpoint: {e}", exc_info=True)
|
174 |
+
return jsonify({'error': str(e)}), 500
|
175 |
+
|
176 |
+
@app.route('/change_mode', methods=['POST'])
|
177 |
+
def change_mode():
|
178 |
+
try:
|
179 |
+
mode = request.json.get('mode')
|
180 |
+
if mode not in ['seguros', 'creditos', 'cobranza']:
|
181 |
+
return jsonify({'error': 'Invalid mode'}), 400
|
182 |
+
|
183 |
+
# Actualizar modo en el sistema de inferencia
|
184 |
+
inference.mode = mode
|
185 |
+
|
186 |
+
return jsonify({'success': True})
|
187 |
+
except Exception as e:
|
188 |
+
logger.error(f"Error changing mode: {e}")
|
189 |
+
return jsonify({'error': str(e)}), 500
|
190 |
+
|
191 |
+
@app.route('/change_model', methods=['POST'])
|
192 |
+
def change_model():
|
193 |
+
try:
|
194 |
+
model = request.json.get('model')
|
195 |
+
if model not in ['Gemini 8b', 'Mixtral 7b']:
|
196 |
+
return jsonify({'error': 'Invalid model'}), 400
|
197 |
+
|
198 |
+
inference.current_model = model
|
199 |
+
|
200 |
+
return jsonify({'success': True})
|
201 |
+
except Exception as e:
|
202 |
+
logger.error(f"Error changing model: {e}")
|
203 |
+
return jsonify({'error': str(e)}), 500
|
204 |
+
|
205 |
+
@app.route('/change_tts', methods=['POST'])
|
206 |
+
def change_tts():
|
207 |
+
try:
|
208 |
+
model = request.json.get('model')
|
209 |
+
if model not in ['EDGE', 'VITS', 'gTTS']:
|
210 |
+
return jsonify({'error': 'Invalid TTS model'}), 400
|
211 |
+
|
212 |
+
# Actualizar modelo TTS
|
213 |
+
audio_utils = AudioUtils(model_name=model)
|
214 |
+
|
215 |
+
return jsonify({'success': True})
|
216 |
+
except Exception as e:
|
217 |
+
logger.error(f"Error changing TTS model: {e}")
|
218 |
+
return jsonify({'error': str(e)}), 500
|
219 |
+
|
220 |
+
if __name__ == "__main__":
|
221 |
+
try:
|
222 |
+
logger.info("Iniciando servidor...")
|
223 |
+
# Cambiar para que funcione en Hugging Face Spaces
|
224 |
+
app.run(host='0.0.0.0', port=7860) # Puerto est谩ndar de Spaces
|
225 |
+
except Exception as e:
|
226 |
+
logger.error(f"Error al iniciar la aplicaci贸n: {e}", exc_info=True)
|