Jeremy Live
commited on
Commit
路
c22eca1
1
Parent(s):
7b28785
Revert "api flask full intration unification"
Browse filesThis reverts commit 483fa3408b38673e14f8a4453b590bbd791c5271.
api.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from typing import Dict, Optional
|
| 3 |
+
import uuid
|
| 4 |
+
import os
|
| 5 |
+
from app import initialize_llm, setup_database_connection, create_agent, gr
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# Almacenamiento en memoria de los mensajes
|
| 10 |
+
message_store: Dict[str, str] = {}
|
| 11 |
+
|
| 12 |
+
@app.route('/user_message', methods=['POST'])
|
| 13 |
+
def handle_user_message():
|
| 14 |
+
try:
|
| 15 |
+
data = request.get_json()
|
| 16 |
+
if not data or 'message' not in data:
|
| 17 |
+
return jsonify({'error': 'Se requiere el campo message'}), 400
|
| 18 |
+
|
| 19 |
+
user_message = data['message']
|
| 20 |
+
|
| 21 |
+
# Generar un ID 煤nico para este mensaje
|
| 22 |
+
message_id = str(uuid.uuid4())
|
| 23 |
+
|
| 24 |
+
# Almacenar el mensaje
|
| 25 |
+
message_store[message_id] = user_message
|
| 26 |
+
|
| 27 |
+
return jsonify({
|
| 28 |
+
'message_id': message_id,
|
| 29 |
+
'status': 'success'
|
| 30 |
+
})
|
| 31 |
+
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return jsonify({'error': str(e)}), 500
|
| 34 |
+
|
| 35 |
+
@app.route('/ask', methods=['POST'])
|
| 36 |
+
def handle_ask():
|
| 37 |
+
try:
|
| 38 |
+
data = request.get_json()
|
| 39 |
+
if not data or 'message_id' not in data:
|
| 40 |
+
return jsonify({'error': 'Se requiere el campo message_id'}), 400
|
| 41 |
+
|
| 42 |
+
message_id = data['message_id']
|
| 43 |
+
|
| 44 |
+
# Recuperar el mensaje almacenado
|
| 45 |
+
if message_id not in message_store:
|
| 46 |
+
return jsonify({'error': 'ID de mensaje no encontrado'}), 404
|
| 47 |
+
|
| 48 |
+
user_message = message_store[message_id]
|
| 49 |
+
|
| 50 |
+
# Inicializar componentes necesarios
|
| 51 |
+
llm, llm_error = initialize_llm()
|
| 52 |
+
if llm_error:
|
| 53 |
+
return jsonify({'error': f'Error al inicializar LLM: {llm_error}'}), 500
|
| 54 |
+
|
| 55 |
+
db_connection, db_error = setup_database_connection()
|
| 56 |
+
if db_error:
|
| 57 |
+
return jsonify({'error': f'Error de conexi贸n a la base de datos: {db_error}'}), 500
|
| 58 |
+
|
| 59 |
+
agent, agent_error = create_agent(llm, db_connection)
|
| 60 |
+
if agent_error:
|
| 61 |
+
return jsonify({'error': f'Error al crear el agente: {agent_error}'}), 500
|
| 62 |
+
|
| 63 |
+
# Obtener respuesta del agente
|
| 64 |
+
response = agent.invoke({"input": user_message})
|
| 65 |
+
|
| 66 |
+
# Procesar la respuesta
|
| 67 |
+
if hasattr(response, 'output') and response.output:
|
| 68 |
+
response_text = response.output
|
| 69 |
+
elif isinstance(response, str):
|
| 70 |
+
response_text = response
|
| 71 |
+
elif hasattr(response, 'get') and callable(response.get) and 'output' in response:
|
| 72 |
+
response_text = response['output']
|
| 73 |
+
else:
|
| 74 |
+
response_text = str(response)
|
| 75 |
+
|
| 76 |
+
# Eliminar el mensaje almacenado despu茅s de procesarlo
|
| 77 |
+
del message_store[message_id]
|
| 78 |
+
|
| 79 |
+
return jsonify({
|
| 80 |
+
'response': response_text,
|
| 81 |
+
'status': 'success'
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return jsonify({'error': str(e)}), 500
|
| 86 |
+
|
| 87 |
+
# Integraci贸n con Gradio para Hugging Face Spaces
|
| 88 |
+
def mount_in_app(gradio_app):
|
| 89 |
+
"""Monta la API Flask en la aplicaci贸n Gradio."""
|
| 90 |
+
return gradio_app
|
| 91 |
+
|
| 92 |
+
if __name__ == '__main__':
|
| 93 |
+
# Si se ejecuta directamente, inicia el servidor Flask
|
| 94 |
+
port = int(os.environ.get('PORT', 5000))
|
| 95 |
+
app.run(host='0.0.0.0', port=port)
|
| 96 |
+
else:
|
| 97 |
+
# Si se importa como m贸dulo (en Hugging Face Spaces),
|
| 98 |
+
# expone la funci贸n para montar en Gradio
|
| 99 |
+
gradio_app = gr.mount_gradio_app(
|
| 100 |
+
app,
|
| 101 |
+
"/api", # Prefijo para los endpoints de la API
|
| 102 |
+
lambda: True # Autenticaci贸n deshabilitada
|
| 103 |
+
)
|
app.py
CHANGED
|
@@ -12,93 +12,7 @@ import pandas as pd
|
|
| 12 |
import plotly.express as px
|
| 13 |
import plotly.graph_objects as go
|
| 14 |
from plotly.subplots import make_subplots
|
| 15 |
-
from
|
| 16 |
-
import uuid
|
| 17 |
-
|
| 18 |
-
# Configuraci贸n de logging
|
| 19 |
-
logging.basicConfig(level=logging.INFO)
|
| 20 |
-
logger = logging.getLogger(__name__)
|
| 21 |
-
|
| 22 |
-
# Flask app initialization
|
| 23 |
-
flask_app = Flask(__name__)
|
| 24 |
-
|
| 25 |
-
# Almacenamiento en memoria de los mensajes
|
| 26 |
-
message_store: Dict[str, str] = {}
|
| 27 |
-
|
| 28 |
-
@flask_app.route('/user_message', methods=['POST'])
|
| 29 |
-
def handle_user_message():
|
| 30 |
-
try:
|
| 31 |
-
data = request.get_json()
|
| 32 |
-
if not data or 'message' not in data:
|
| 33 |
-
return jsonify({'error': 'Se requiere el campo message'}), 400
|
| 34 |
-
|
| 35 |
-
user_message = data['message']
|
| 36 |
-
|
| 37 |
-
# Generar un ID 煤nico para este mensaje
|
| 38 |
-
message_id = str(uuid.uuid4())
|
| 39 |
-
|
| 40 |
-
# Almacenar el mensaje
|
| 41 |
-
message_store[message_id] = user_message
|
| 42 |
-
|
| 43 |
-
return jsonify({
|
| 44 |
-
'message_id': message_id,
|
| 45 |
-
'status': 'success'
|
| 46 |
-
})
|
| 47 |
-
|
| 48 |
-
except Exception as e:
|
| 49 |
-
return jsonify({'error': str(e)}), 500
|
| 50 |
-
|
| 51 |
-
@flask_app.route('/ask', methods=['POST'])
|
| 52 |
-
def handle_ask():
|
| 53 |
-
try:
|
| 54 |
-
data = request.get_json()
|
| 55 |
-
if not data or 'message_id' not in data:
|
| 56 |
-
return jsonify({'error': 'Se requiere el campo message_id'}), 400
|
| 57 |
-
|
| 58 |
-
message_id = data['message_id']
|
| 59 |
-
|
| 60 |
-
# Recuperar el mensaje almacenado
|
| 61 |
-
if message_id not in message_store:
|
| 62 |
-
return jsonify({'error': 'ID de mensaje no encontrado'}), 404
|
| 63 |
-
|
| 64 |
-
user_message = message_store[message_id]
|
| 65 |
-
|
| 66 |
-
# Inicializar componentes necesarios
|
| 67 |
-
llm, llm_error = initialize_llm()
|
| 68 |
-
if llm_error:
|
| 69 |
-
return jsonify({'error': f'Error al inicializar LLM: {llm_error}'}), 500
|
| 70 |
-
|
| 71 |
-
db_connection, db_error = setup_database_connection()
|
| 72 |
-
if db_error:
|
| 73 |
-
return jsonify({'error': f'Error de conexi贸n a la base de datos: {db_error}'}), 500
|
| 74 |
-
|
| 75 |
-
agent, agent_error = create_agent(llm, db_connection)
|
| 76 |
-
if agent_error:
|
| 77 |
-
return jsonify({'error': f'Error al crear el agente: {agent_error}'}), 500
|
| 78 |
-
|
| 79 |
-
# Obtener respuesta del agente
|
| 80 |
-
response = agent.invoke({"input": user_message})
|
| 81 |
-
|
| 82 |
-
# Procesar la respuesta
|
| 83 |
-
if hasattr(response, 'output') and response.output:
|
| 84 |
-
response_text = response.output
|
| 85 |
-
elif isinstance(response, str):
|
| 86 |
-
response_text = response
|
| 87 |
-
elif hasattr(response, 'get') and callable(response.get) and 'output' in response:
|
| 88 |
-
response_text = response['output']
|
| 89 |
-
else:
|
| 90 |
-
response_text = str(response)
|
| 91 |
-
|
| 92 |
-
# Eliminar el mensaje almacenado despu茅s de procesarlo
|
| 93 |
-
del message_store[message_id]
|
| 94 |
-
|
| 95 |
-
return jsonify({
|
| 96 |
-
'response': response_text,
|
| 97 |
-
'status': 'success'
|
| 98 |
-
})
|
| 99 |
-
|
| 100 |
-
except Exception as e:
|
| 101 |
-
return jsonify({'error': str(e)}), 500
|
| 102 |
|
| 103 |
# ... (resto del c贸digo existente sin cambios) ...
|
| 104 |
|
|
@@ -111,8 +25,8 @@ def create_application():
|
|
| 111 |
if os.getenv('SPACE_ID'):
|
| 112 |
demo = gr.mount_gradio_app(
|
| 113 |
flask_app,
|
| 114 |
-
|
| 115 |
-
|
| 116 |
)
|
| 117 |
|
| 118 |
def user_message(user_input: str, chat_history: List[Dict[str, str]]) -> Tuple[str, List[Dict[str, str]]]:
|
|
@@ -225,16 +139,10 @@ def get_app():
|
|
| 225 |
|
| 226 |
# Para desarrollo local
|
| 227 |
if __name__ == "__main__":
|
| 228 |
-
#
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
demo.launch(
|
| 236 |
-
server_name="0.0.0.0",
|
| 237 |
-
server_port=7860,
|
| 238 |
-
debug=True,
|
| 239 |
-
share=False
|
| 240 |
-
)
|
|
|
|
| 12 |
import plotly.express as px
|
| 13 |
import plotly.graph_objects as go
|
| 14 |
from plotly.subplots import make_subplots
|
| 15 |
+
from api import app as flask_app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# ... (resto del c贸digo existente sin cambios) ...
|
| 18 |
|
|
|
|
| 25 |
if os.getenv('SPACE_ID'):
|
| 26 |
demo = gr.mount_gradio_app(
|
| 27 |
flask_app,
|
| 28 |
+
"/api", # Prefijo para los endpoints de la API
|
| 29 |
+
lambda: True # Autenticaci贸n deshabilitada
|
| 30 |
)
|
| 31 |
|
| 32 |
def user_message(user_input: str, chat_history: List[Dict[str, str]]) -> Tuple[str, List[Dict[str, str]]]:
|
|
|
|
| 139 |
|
| 140 |
# Para desarrollo local
|
| 141 |
if __name__ == "__main__":
|
| 142 |
+
# Configuraci贸n para desarrollo local - versi贸n simplificada para Gradio 5.x
|
| 143 |
+
demo.launch(
|
| 144 |
+
server_name="0.0.0.0",
|
| 145 |
+
server_port=7860,
|
| 146 |
+
debug=True,
|
| 147 |
+
share=False
|
| 148 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|