Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,51 +2,54 @@ import os
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
-
from smolagents import AzureOpenAIServerModel
|
6 |
from huggingface_hub import login
|
7 |
from dotenv import load_dotenv
|
|
|
8 |
|
9 |
-
|
|
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
|
14 |
-
def
|
15 |
"""
|
16 |
-
Obtiene
|
17 |
"""
|
18 |
-
|
|
|
19 |
|
20 |
if profile:
|
21 |
username = f"{profile.username}"
|
22 |
-
print(f"Usuario
|
23 |
else:
|
24 |
-
print("
|
25 |
-
return "
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
submit_url = f"{api_url}/submit"
|
31 |
|
32 |
try:
|
33 |
-
print("Iniciando
|
34 |
-
|
|
|
35 |
except Exception as e:
|
36 |
-
print(f"Error al inicializar
|
37 |
return f"Error al inicializar el agente: {e}", None
|
38 |
|
39 |
-
#
|
40 |
print(f"Obteniendo preguntas de: {questions_url}")
|
41 |
try:
|
42 |
response = requests.get(questions_url, timeout=15)
|
43 |
response.raise_for_status()
|
44 |
-
|
45 |
-
if not
|
46 |
print("La lista de preguntas está vacía.")
|
47 |
-
return "
|
48 |
-
print(f"
|
49 |
-
|
|
|
50 |
file_name = q.get("file_name", "")
|
51 |
task_id = q.get("task_id")
|
52 |
if file_name and task_id:
|
@@ -55,69 +58,83 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
55 |
att_response.raise_for_status()
|
56 |
q["attachment_b64"] = att_response.text
|
57 |
except Exception as e:
|
58 |
-
print(f"Error al obtener archivo adjunto para tarea {task_id}: {e}")
|
59 |
q["attachment_b64"] = None
|
60 |
except requests.exceptions.RequestException as e:
|
61 |
print(f"Error al obtener preguntas: {e}")
|
62 |
return f"Error al obtener preguntas: {e}", None
|
63 |
|
64 |
-
#
|
|
|
65 |
results_log = []
|
66 |
answers_payload = []
|
67 |
-
|
68 |
-
for item in
|
69 |
task_id = item.get("task_id")
|
70 |
question_text = item.get("question", "")
|
71 |
attachment_b64 = item.get("attachment_b64", "")
|
72 |
if attachment_b64:
|
73 |
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
74 |
-
if not task_id or question_text
|
75 |
-
print(f"Saltando
|
76 |
continue
|
77 |
try:
|
78 |
-
submitted_answer =
|
79 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
80 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
81 |
except Exception as e:
|
82 |
-
print(f"Error
|
83 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR
|
84 |
|
85 |
if not answers_payload:
|
86 |
-
|
87 |
-
return "El agente no generó respuestas.", pd.DataFrame(results_log)
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
print(
|
92 |
|
93 |
-
# 5. Enviar respuestas
|
94 |
try:
|
95 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
96 |
response.raise_for_status()
|
97 |
result_data = response.json()
|
98 |
-
final_status = (
|
99 |
-
f"¡Envío exitoso!\n"
|
100 |
-
f"Usuario: {result_data.get('username')}\n"
|
101 |
-
f"Puntuación total: {result_data.get('score', 'N/A')}% "
|
102 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correctas)"
|
103 |
-
)
|
104 |
print("Envío exitoso.")
|
105 |
results_df = pd.DataFrame(results_log)
|
106 |
return final_status, results_df
|
107 |
except requests.exceptions.RequestException as e:
|
108 |
-
|
109 |
-
print(
|
110 |
results_df = pd.DataFrame(results_log)
|
111 |
-
return
|
112 |
|
113 |
-
|
|
|
114 |
with gr.Blocks() as demo:
|
115 |
gr.Markdown("# Evaluador de Agente Básico")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
gr.LoginButton()
|
117 |
-
|
118 |
-
|
|
|
|
|
119 |
results_table = gr.DataFrame(label="Preguntas y Respuestas del Agente", wrap=True)
|
120 |
-
|
|
|
|
|
|
|
|
|
121 |
|
122 |
if __name__ == "__main__":
|
|
|
123 |
demo.launch(debug=True, share=False)
|
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import pandas as pd
|
|
|
5 |
from huggingface_hub import login
|
6 |
from dotenv import load_dotenv
|
7 |
+
import my_tokens
|
8 |
|
9 |
+
# Cargar variables de entorno
|
10 |
+
load_dotenv()
|
11 |
|
12 |
+
# Constantes
|
13 |
+
API_BASE_URL = "https://my-custom-api.hf.space"
|
14 |
|
15 |
+
def execute_agent_operations(profile: gr.OAuthProfile | None):
|
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 = f"{profile.username}"
|
24 |
+
print(f"Usuario conectado: {username}")
|
25 |
else:
|
26 |
+
print("No has iniciado sesión.")
|
27 |
+
return "Inicia sesión en Hugging Face.", None
|
28 |
|
29 |
+
questions_url = f"{API_BASE_URL}/questions"
|
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(questions_url, timeout=15)
|
45 |
response.raise_for_status()
|
46 |
+
questions = response.json()
|
47 |
+
if not questions:
|
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:
|
|
|
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 |
+
# Ejecutar el agente
|
68 |
+
print(f"Ejecutando agente en {len(questions)} preguntas...")
|
69 |
results_log = []
|
70 |
answers_payload = []
|
71 |
+
|
72 |
+
for item in questions:
|
73 |
task_id = item.get("task_id")
|
74 |
question_text = item.get("question", "")
|
75 |
attachment_b64 = item.get("attachment_b64", "")
|
76 |
if attachment_b64:
|
77 |
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
78 |
+
if not task_id or not question_text:
|
79 |
+
print(f"Saltando tarea con información incompleta: {item}")
|
80 |
continue
|
81 |
try:
|
82 |
+
submitted_answer = "Placeholder" # Aquí llamarías a tu agente para obtener la respuesta
|
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 |
+
print(f"Error al procesar la tarea {task_id}: {e}")
|
87 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
88 |
|
89 |
if not answers_payload:
|
90 |
+
return "El agente no produjo respuestas.", pd.DataFrame(results_log)
|
|
|
91 |
|
92 |
+
submission_data = {"username": username.strip(), "agent_code": f"https://huggingface.co/spaces/{space_id}", "answers": answers_payload}
|
93 |
+
status_update = f"Enviando respuestas para el usuario '{username}'..."
|
94 |
+
print(status_update)
|
95 |
|
|
|
96 |
try:
|
97 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
98 |
response.raise_for_status()
|
99 |
result_data = response.json()
|
100 |
+
final_status = f"¡Envío exitoso!\nPuntuación: {result_data.get('score', 'N/A')}"
|
|
|
|
|
|
|
|
|
|
|
101 |
print("Envío exitoso.")
|
102 |
results_df = pd.DataFrame(results_log)
|
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 demo:
|
113 |
gr.Markdown("# Evaluador de Agente Básico")
|
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 |
+
run_button = gr.Button("Ejecutar Evaluación y Enviar Respuestas")
|
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 |
+
run_button.click(
|
134 |
+
fn=execute_agent_operations,
|
135 |
+
outputs=[status_output, results_table]
|
136 |
+
)
|
137 |
|
138 |
if __name__ == "__main__":
|
139 |
+
print("Iniciando aplicación de evaluación de agente...")
|
140 |
demo.launch(debug=True, share=False)
|