Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
@@ -1,205 +1,59 @@
|
|
1 |
-
from flask import Flask, send_from_directory, request, jsonify, render_template
|
2 |
-
from flask_cors import CORS
|
3 |
import os
|
4 |
-
|
5 |
-
from
|
|
|
|
|
6 |
import logging
|
7 |
-
import
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
logging.basicConfig(level=logging.DEBUG)
|
15 |
-
logger = logging.getLogger(__name__)
|
16 |
-
|
17 |
-
app = Flask(__name__)
|
18 |
-
CORS(app)
|
19 |
-
|
20 |
-
# Cargar variables de entorno
|
21 |
-
load_dotenv()
|
22 |
-
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
|
23 |
-
|
24 |
-
# Cargar configuración
|
25 |
-
with open('config.yaml', 'r') as file:
|
26 |
-
config = yaml.safe_load(file)
|
27 |
-
|
28 |
-
# Inicializar componentes con mensajes
|
29 |
-
try:
|
30 |
-
logger.info("Iniciando sistema...")
|
31 |
-
|
32 |
-
logger.info("Configurando API de Google...")
|
33 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
34 |
-
|
35 |
-
logger.info("Inicializando sistema de inferencia...")
|
36 |
-
inference = InferenceManager()
|
37 |
-
|
38 |
-
logger.info("Inicializando registro de chat...")
|
39 |
-
chat_logger = ChatLogger()
|
40 |
-
|
41 |
-
logger.info("Inicializando sistema de audio...")
|
42 |
-
audio_utils = AudioUtils()
|
43 |
-
|
44 |
-
logger.info("Sistema iniciado correctamente")
|
45 |
-
except Exception as e:
|
46 |
-
logger.error(f"Error crítico inicializando el sistema: {e}")
|
47 |
-
raise e
|
48 |
-
|
49 |
-
# Configurar el directorio de archivos temporales
|
50 |
-
TEMP_AUDIO_DIR = Path("static/temp_audio")
|
51 |
-
TEMP_AUDIO_DIR.mkdir(parents=True, exist_ok=True)
|
52 |
-
|
53 |
-
# Configurar el modelo
|
54 |
-
model = genai.GenerativeModel('gemini-pro')
|
55 |
-
|
56 |
-
@app.after_request
|
57 |
-
def after_request(response):
|
58 |
-
# Agregar headers necesarios para ngrok
|
59 |
-
response.headers.add('Accept-Ranges', 'bytes')
|
60 |
-
response.headers.add('Access-Control-Allow-Origin', '*')
|
61 |
-
logger.debug(f"Response headers: {dict(response.headers)}")
|
62 |
-
return response
|
63 |
-
|
64 |
-
@app.route('/temp_audio/<path:filename>')
|
65 |
-
def serve_audio(filename):
|
66 |
-
try:
|
67 |
-
logger.info(f"Attempting to serve audio file: {filename}")
|
68 |
-
file_path = TEMP_AUDIO_DIR / filename
|
69 |
-
|
70 |
-
if not file_path.exists():
|
71 |
-
logger.error(f"File not found: {file_path}")
|
72 |
-
return jsonify({'error': 'File not found'}), 404
|
73 |
-
|
74 |
-
if not filename.endswith(('.wav', '.mp3')):
|
75 |
-
logger.error(f"Invalid file format: {filename}")
|
76 |
-
return jsonify({'error': 'Invalid file format'}), 400
|
77 |
-
|
78 |
-
logger.info(f"Serving file from: {file_path}")
|
79 |
-
response = send_from_directory(str(TEMP_AUDIO_DIR), filename)
|
80 |
-
response.headers['Content-Type'] = 'audio/wav' if filename.endswith('.wav') else 'audio/mpeg'
|
81 |
-
response.headers['Cache-Control'] = 'no-cache'
|
82 |
-
return response
|
83 |
-
|
84 |
-
except Exception as e:
|
85 |
-
logger.error(f"Error serving audio file: {e}", exc_info=True)
|
86 |
-
return jsonify({'error': str(e)}), 500
|
87 |
-
|
88 |
-
@app.route('/generate_audio', methods=['POST'])
|
89 |
-
def generate_audio():
|
90 |
try:
|
91 |
-
|
92 |
-
|
93 |
-
logger.info(f"Generando audio para texto: '{text}' usando modelo: {model}")
|
94 |
-
|
95 |
-
if not text:
|
96 |
-
logger.error("No se proporcionó texto")
|
97 |
-
return jsonify({'error': 'No text provided'}), 400
|
98 |
-
|
99 |
-
try:
|
100 |
-
temp_audio_utils = AudioUtils(model_name=model)
|
101 |
-
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
102 |
-
|
103 |
-
if not audio_file:
|
104 |
-
logger.error(f"Fallo al generar audio con {model}, intentando con EDGE")
|
105 |
-
temp_audio_utils = AudioUtils(model_name='EDGE')
|
106 |
-
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
107 |
-
except Exception as e:
|
108 |
-
logger.error(f"Error con modelo {model}, usando EDGE: {e}")
|
109 |
-
temp_audio_utils = AudioUtils(model_name='EDGE')
|
110 |
-
audio_file = temp_audio_utils.text_to_speech(text, return_file=True)
|
111 |
-
|
112 |
-
if audio_file:
|
113 |
-
audio_url = f'/temp_audio/{audio_file}'
|
114 |
-
logger.info(f"Audio generado: {audio_url}")
|
115 |
-
|
116 |
-
file_path = TEMP_AUDIO_DIR / audio_file
|
117 |
-
if not file_path.exists():
|
118 |
-
logger.error(f"Archivo no encontrado: {file_path}")
|
119 |
-
return jsonify({
|
120 |
-
'error': 'Generated file not found',
|
121 |
-
'details': 'El archivo de audio no se generó correctamente'
|
122 |
-
}), 500
|
123 |
-
|
124 |
-
return jsonify({
|
125 |
-
'audio_url': audio_url,
|
126 |
-
'model_used': temp_audio_utils.current_model
|
127 |
-
})
|
128 |
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
}), 500
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
'error': str(e),
|
138 |
-
'details': 'Error interno del servidor al generar audio'
|
139 |
-
}), 500
|
140 |
-
|
141 |
-
@app.route('/static/<path:path>')
|
142 |
-
def send_static(path):
|
143 |
-
logger.debug(f"Serving static file: {path}")
|
144 |
-
return send_from_directory('static', path)
|
145 |
-
|
146 |
-
@app.route('/')
|
147 |
-
def home():
|
148 |
-
return render_template('chat.html')
|
149 |
-
|
150 |
-
@app.route('/chat', methods=['POST'])
|
151 |
-
def chat():
|
152 |
-
try:
|
153 |
-
data = request.json
|
154 |
-
message = data.get('message', '')
|
155 |
-
mode = data.get('mode', 'seguros')
|
156 |
|
157 |
-
|
158 |
-
|
159 |
-
inference.change_mode(mode)
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
return jsonify({'error': str(e)}), 500
|
165 |
-
|
166 |
-
@app.route('/change_mode', methods=['POST'])
|
167 |
-
def change_mode():
|
168 |
-
try:
|
169 |
-
mode = request.json.get('mode')
|
170 |
-
success = inference.change_mode(mode)
|
171 |
-
return jsonify({'success': success})
|
172 |
-
except Exception as e:
|
173 |
-
return jsonify({'error': str(e)}), 500
|
174 |
-
|
175 |
-
@app.route('/change_model', methods=['POST'])
|
176 |
-
def change_model():
|
177 |
-
try:
|
178 |
-
model = request.json.get('model')
|
179 |
-
success = inference.change_model(model)
|
180 |
-
return jsonify({'success': success})
|
181 |
-
except Exception as e:
|
182 |
-
return jsonify({'error': str(e)}), 500
|
183 |
-
|
184 |
-
@app.route('/change_tts', methods=['POST'])
|
185 |
-
def change_tts():
|
186 |
-
try:
|
187 |
-
model = request.json.get('model')
|
188 |
-
if model not in ['EDGE', 'VITS', 'gTTS']:
|
189 |
-
return jsonify({'error': 'Invalid TTS model'}), 400
|
190 |
-
|
191 |
-
# Actualizar modelo TTS
|
192 |
-
audio_utils = AudioUtils(model_name=model)
|
193 |
|
194 |
-
return jsonify({'success': True})
|
195 |
-
except Exception as e:
|
196 |
-
logger.error(f"Error changing TTS model: {e}")
|
197 |
-
return jsonify({'error': str(e)}), 500
|
198 |
-
|
199 |
-
if __name__ == "__main__":
|
200 |
-
try:
|
201 |
-
logger.info("Iniciando servidor...")
|
202 |
-
# Cambiar para que funcione en Hugging Face Spaces
|
203 |
-
app.run(host='0.0.0.0', port=7860) # Puerto estándar de Spaces
|
204 |
except Exception as e:
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import shutil
|
3 |
+
from web_app import WebChatbotApp
|
4 |
+
import traceback
|
5 |
+
import sys
|
6 |
import logging
|
7 |
+
import signal
|
8 |
+
|
9 |
+
# Configuración del registro
|
10 |
+
logging.basicConfig(
|
11 |
+
filename='app.log', # Nombre del archivo de registro
|
12 |
+
level=logging.DEBUG, # Nivel de registro
|
13 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
14 |
+
encoding='utf-8'
|
15 |
+
)
|
16 |
+
|
17 |
+
def clean_pycache():
|
18 |
+
"""Eliminar el directorio __pycache__ si existe."""
|
19 |
+
pycache_dir = "__pycache__"
|
20 |
+
if os.path.exists(pycache_dir):
|
21 |
+
shutil.rmtree(pycache_dir)
|
22 |
+
logging.info(f"Limpieza de {pycache_dir} completada")
|
23 |
+
|
24 |
+
def setup_directories():
|
25 |
+
"""Crear directorios necesarios si no existen."""
|
26 |
+
directories = ['temp', 'sessions', 'logs', 'flask_session']
|
27 |
+
for directory in directories:
|
28 |
+
os.makedirs(directory, exist_ok=True)
|
29 |
+
logging.info(f"Directorio {directory} verificado")
|
30 |
+
|
31 |
+
def signal_handler(signum, frame):
|
32 |
+
logging.info("Señal de terminación recibida. Cerrando servidor...")
|
33 |
+
sys.exit(0)
|
34 |
|
35 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
try:
|
37 |
+
signal.signal(signal.SIGINT, signal_handler)
|
38 |
+
signal.signal(signal.SIGTERM, signal_handler)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
# Limpiar caché y crear directorios
|
41 |
+
clean_pycache()
|
42 |
+
setup_directories()
|
|
|
43 |
|
44 |
+
# Iniciar aplicación
|
45 |
+
logging.info("Iniciando aplicación...")
|
46 |
+
app = WebChatbotApp()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
+
port = int(os.environ.get('PORT', 5000))
|
49 |
+
host = os.environ.get('HOST', '127.0.0.1')
|
|
|
50 |
|
51 |
+
# Iniciar servidor
|
52 |
+
logging.info(f"Iniciando servidor en {host}:{port}...")
|
53 |
+
app.run(host=host, port=port, debug=False, use_tunnel=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
except Exception as e:
|
56 |
+
logging.error(f"Error crítico al iniciar la aplicación: {str(e)}")
|
57 |
+
logging.error(f"Detalles del error: {traceback.format_exc()}")
|
58 |
+
print(f"\n❌ Error crítico: {str(e)}")
|
59 |
+
sys.exit(1)
|