Spaces:
Running
Running
import os | |
import logging | |
from flask import Flask, render_template, request, jsonify | |
from models.chatbot_model import MentalHealthChatbot | |
app = Flask(__name__) | |
# Configurar el registro de errores | |
logging.basicConfig( | |
level=logging.ERROR, | |
format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s', | |
handlers=[ | |
# Cambiamos a /tmp/error.log para que sea escribible en Hugging Face Spaces | |
logging.FileHandler("/tmp/error.log"), | |
logging.StreamHandler() | |
] | |
) | |
logger = logging.getLogger(__name__) | |
# Crear una instancia del chatbot con el modelo fine-tuned | |
try: | |
chatbot = MentalHealthChatbot(model_path='models/bert_emotion_model') | |
except Exception as e: | |
logger.error(f"Error al inicializar el chatbot: {e}") | |
raise | |
def index(): | |
try: | |
return render_template('index.html') | |
except Exception as e: | |
logger.error(f"Error al renderizar index.html: {e}") | |
return "Error al cargar la página de inicio.", 500 | |
def chatbot_page(): | |
try: | |
return render_template('chatbot.html') | |
except Exception as e: | |
logger.error(f"Error al renderizar chatbot.html: {e}") | |
return "Error al cargar la página del chatbot.", 500 | |
def get_bot_response(): | |
try: | |
user_input = request.form.get('message', '').strip() | |
if not user_input: | |
logger.warning("Mensaje vacío recibido del usuario.") | |
return jsonify({'response': "Por favor, ingresa un mensaje."}), 400 | |
response_data = chatbot.generate_response(user_input) | |
# Obtenemos el texto, pero ignoramos audio_path, ya que no generamos audio en el servidor | |
response_text = response_data.get('text', "Lo siento, no pude procesar tu mensaje.") | |
# Devolvemos solo el texto (y, si quieres, emoción, confianza, etc.) | |
return jsonify({'response': response_text}) | |
except Exception as e: | |
logger.error(f"Error en /get_response: {e}") | |
return jsonify({'response': "Lo siento, ha ocurrido un error al procesar tu solicitud."}), 500 | |
if __name__ == '__main__': | |
# Ajustamos para leer la variable de entorno PORT (o usar 7860 por defecto) | |
port = int(os.environ.get("PORT", 7860)) | |
app.run(host="0.0.0.0", port=port, debug=True) |