Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,137 +4,94 @@ import requests
|
|
4 |
import pandas as pd
|
5 |
from huggingface_hub import login
|
6 |
from dotenv import load_dotenv
|
7 |
-
import
|
8 |
|
9 |
-
# Cargar
|
10 |
-
|
|
|
|
|
|
|
|
|
11 |
|
12 |
# Constantes
|
13 |
API_BASE_URL = "https://my-custom-api.hf.space"
|
14 |
|
15 |
-
def
|
16 |
-
"""
|
17 |
-
Obtiene preguntas, ejecuta el agente y envía respuestas.
|
18 |
-
"""
|
19 |
-
# Obtener el ID de espacio
|
20 |
space_id = os.getenv("MY_SPACE_ID")
|
21 |
|
22 |
if profile:
|
23 |
-
username =
|
24 |
-
print(f"Usuario
|
25 |
else:
|
26 |
-
|
27 |
-
return "Inicia sesión en Hugging Face.", None
|
28 |
|
29 |
-
|
30 |
-
attachments_url = f"{API_BASE_URL}/files/"
|
31 |
-
submit_url = f"{API_BASE_URL}/submit"
|
32 |
-
|
33 |
-
try:
|
34 |
-
print("Iniciando Agente...")
|
35 |
-
# Aquí puedes instanciar tu agente como se define en agent.py
|
36 |
-
# agente = MiAgente()
|
37 |
-
except Exception as e:
|
38 |
-
print(f"Error al inicializar agente: {e}")
|
39 |
-
return f"Error al inicializar el agente: {e}", None
|
40 |
-
|
41 |
-
# Obtener las preguntas
|
42 |
-
print(f"Obteniendo preguntas de: {questions_url}")
|
43 |
try:
|
44 |
-
response = requests.get(
|
45 |
response.raise_for_status()
|
46 |
-
|
47 |
-
|
48 |
-
print("La lista de preguntas está vacía.")
|
49 |
-
return "No se encontraron preguntas.", None
|
50 |
-
print(f"Se obtuvieron {len(questions)} preguntas.")
|
51 |
-
|
52 |
-
for q in questions:
|
53 |
-
file_name = q.get("file_name", "")
|
54 |
-
task_id = q.get("task_id")
|
55 |
-
if file_name and task_id:
|
56 |
-
try:
|
57 |
-
att_response = requests.get(f"{attachments_url}{task_id}", timeout=15)
|
58 |
-
att_response.raise_for_status()
|
59 |
-
q["attachment_b64"] = att_response.text
|
60 |
-
except Exception as e:
|
61 |
-
print(f"Error al obtener archivo adjunto para la tarea {task_id}: {e}")
|
62 |
-
q["attachment_b64"] = None
|
63 |
-
except requests.exceptions.RequestException as e:
|
64 |
-
print(f"Error al obtener preguntas: {e}")
|
65 |
return f"Error al obtener preguntas: {e}", None
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
task_id = item.get("task_id")
|
74 |
-
|
75 |
-
|
76 |
-
if
|
77 |
-
|
78 |
-
|
79 |
-
print(f"Saltando tarea con información incompleta: {item}")
|
80 |
-
continue
|
81 |
try:
|
82 |
-
|
83 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
84 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
85 |
except Exception as e:
|
86 |
-
|
87 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
88 |
|
89 |
-
|
90 |
-
|
91 |
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
95 |
|
96 |
try:
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
return final_status, results_df
|
104 |
-
except requests.exceptions.RequestException as e:
|
105 |
-
error_message = f"Error al enviar: {e}"
|
106 |
-
print(error_message)
|
107 |
-
results_df = pd.DataFrame(results_log)
|
108 |
-
return error_message, results_df
|
109 |
-
|
110 |
|
111 |
# Interfaz Gradio
|
112 |
-
with gr.Blocks() as
|
113 |
-
gr.Markdown("# Evaluador de Agente
|
114 |
-
gr.Markdown(""
|
115 |
-
**Instrucciones:**
|
116 |
-
|
117 |
-
1. Modifica el código para ajustar el agente a tus necesidades.
|
118 |
-
2. Inicia sesión en Hugging Face.
|
119 |
-
3. Haz clic en 'Ejecutar Evaluación y Enviar Respuestas' para procesar las preguntas.
|
120 |
-
|
121 |
-
---
|
122 |
-
**Avisos:**
|
123 |
-
Este espacio está diseñado para ser subóptimo con el fin de incentivar la personalización del código.
|
124 |
-
""")
|
125 |
|
126 |
gr.LoginButton()
|
|
|
127 |
|
128 |
-
|
129 |
-
|
130 |
-
status_output = gr.Textbox(label="Estado de Ejecución / Resultado del Envío", lines=5, interactive=False)
|
131 |
-
results_table = gr.DataFrame(label="Preguntas y Respuestas del Agente", wrap=True)
|
132 |
|
133 |
-
|
134 |
-
fn=execute_agent_operations,
|
135 |
-
outputs=[status_output, results_table]
|
136 |
-
)
|
137 |
|
138 |
if __name__ == "__main__":
|
139 |
-
|
140 |
-
demo.launch(debug=True, share=False)
|
|
|
4 |
import pandas as pd
|
5 |
from huggingface_hub import login
|
6 |
from dotenv import load_dotenv
|
7 |
+
from agent import ejecutar_agente
|
8 |
|
9 |
+
# Cargar token desde secreto y hacer login
|
10 |
+
hf_token = os.getenv("HF_TOKEN")
|
11 |
+
if hf_token:
|
12 |
+
login(token=hf_token)
|
13 |
+
else:
|
14 |
+
raise ValueError("No se encontró el token de Hugging Face. Verifica el secreto HF_TOKEN.")
|
15 |
|
16 |
# Constantes
|
17 |
API_BASE_URL = "https://my-custom-api.hf.space"
|
18 |
|
19 |
+
def ejecutar_y_enviar_respuestas(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
20 |
space_id = os.getenv("MY_SPACE_ID")
|
21 |
|
22 |
if profile:
|
23 |
+
username = profile.username
|
24 |
+
print(f"Usuario: {username}")
|
25 |
else:
|
26 |
+
return "Debes iniciar sesión en Hugging Face.", None
|
|
|
27 |
|
28 |
+
# Obtener preguntas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
try:
|
30 |
+
response = requests.get(f"{API_BASE_URL}/questions", timeout=10)
|
31 |
response.raise_for_status()
|
32 |
+
preguntas = response.json()
|
33 |
+
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
return f"Error al obtener preguntas: {e}", None
|
35 |
|
36 |
+
if not preguntas:
|
37 |
+
return "No hay preguntas disponibles.", None
|
38 |
+
|
39 |
+
for p in preguntas:
|
40 |
+
task_id = p.get("task_id")
|
41 |
+
if task_id:
|
42 |
+
try:
|
43 |
+
archivo = requests.get(f"{API_BASE_URL}/files/{task_id}", timeout=10)
|
44 |
+
archivo.raise_for_status()
|
45 |
+
p["attachment_b64"] = archivo.text
|
46 |
+
except:
|
47 |
+
p["attachment_b64"] = None
|
48 |
+
|
49 |
+
# Ejecutar agente sobre preguntas
|
50 |
+
resultados = []
|
51 |
+
respuestas = []
|
52 |
+
|
53 |
+
for item in preguntas:
|
54 |
task_id = item.get("task_id")
|
55 |
+
pregunta = item.get("question", "")
|
56 |
+
adjunto = item.get("attachment_b64", "")
|
57 |
+
if adjunto:
|
58 |
+
pregunta += f"\n\n[ATTACHMENT:]\n{adjunto}"
|
59 |
+
|
|
|
|
|
60 |
try:
|
61 |
+
respuesta = ejecutar_agente(pregunta)
|
|
|
|
|
62 |
except Exception as e:
|
63 |
+
respuesta = f"ERROR: {e}"
|
|
|
64 |
|
65 |
+
respuestas.append({"task_id": task_id, "submitted_answer": respuesta})
|
66 |
+
resultados.append({"Task ID": task_id, "Question": pregunta, "Submitted Answer": respuesta})
|
67 |
|
68 |
+
# Enviar respuestas
|
69 |
+
payload = {
|
70 |
+
"username": username,
|
71 |
+
"agent_code": f"https://huggingface.co/spaces/{space_id}",
|
72 |
+
"answers": respuestas,
|
73 |
+
}
|
74 |
|
75 |
try:
|
76 |
+
envio = requests.post(f"{API_BASE_URL}/submit", json=payload, timeout=60)
|
77 |
+
envio.raise_for_status()
|
78 |
+
resultado_final = envio.json()
|
79 |
+
return f"¡Envío exitoso! Score: {resultado_final.get('score', 'N/A')}", pd.DataFrame(resultados)
|
80 |
+
except Exception as e:
|
81 |
+
return f"Error al enviar: {e}", pd.DataFrame(resultados)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
# Interfaz Gradio
|
84 |
+
with gr.Blocks() as interfaz:
|
85 |
+
gr.Markdown("# Evaluador de Agente")
|
86 |
+
gr.Markdown("Inicia sesión, ejecuta el agente y envía tus respuestas.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
gr.LoginButton()
|
89 |
+
btn = gr.Button("Ejecutar Evaluación y Enviar Respuestas")
|
90 |
|
91 |
+
salida_estado = gr.Textbox(label="Estado", lines=4)
|
92 |
+
salida_tabla = gr.DataFrame(label="Resultados")
|
|
|
|
|
93 |
|
94 |
+
btn.click(fn=ejecutar_y_enviar_respuestas, outputs=[salida_estado, salida_tabla])
|
|
|
|
|
|
|
95 |
|
96 |
if __name__ == "__main__":
|
97 |
+
interfaz.launch()
|
|