Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,57 +2,69 @@ import os
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import pandas as pd
|
|
|
|
|
5 |
from dotenv import load_dotenv
|
6 |
|
7 |
load_dotenv() # Cargar variables de entorno
|
8 |
|
|
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
11 |
-
# Función para ejecutar y enviar todas las respuestas
|
12 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
13 |
"""
|
14 |
-
|
15 |
"""
|
16 |
-
space_id = os.getenv("SPACE_ID") # ID del espacio para
|
17 |
|
18 |
if profile:
|
19 |
username = f"{profile.username}"
|
20 |
print(f"Usuario logueado: {username}")
|
21 |
else:
|
22 |
print("Usuario no logueado.")
|
23 |
-
return "Por favor,
|
24 |
|
25 |
api_url = DEFAULT_API_URL
|
26 |
questions_url = f"{api_url}/questions"
|
27 |
attachments_url = f"{api_url}/files/"
|
28 |
submit_url = f"{api_url}/submit"
|
29 |
|
30 |
-
# Crear agente (modificado)
|
31 |
try:
|
32 |
print("Iniciando agente...")
|
33 |
-
agent = agent.BasicAgent() #
|
34 |
except Exception as e:
|
35 |
-
print(f"Error al
|
36 |
-
return f"Error al
|
37 |
|
38 |
-
# 2.
|
39 |
-
print(f"
|
40 |
try:
|
41 |
response = requests.get(questions_url, timeout=15)
|
42 |
response.raise_for_status()
|
43 |
questions_data = response.json()
|
44 |
if not questions_data:
|
45 |
print("La lista de preguntas está vacía.")
|
46 |
-
return "La lista de preguntas está vacía.", None
|
47 |
-
print(f"
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
# 3. Ejecutar
|
53 |
results_log = []
|
54 |
answers_payload = []
|
55 |
-
print(f"Ejecutando
|
56 |
for item in questions_data:
|
57 |
task_id = item.get("task_id")
|
58 |
question_text = item.get("question", "")
|
@@ -60,47 +72,51 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
60 |
if attachment_b64:
|
61 |
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
62 |
if not task_id or question_text is None:
|
63 |
-
print(f"Saltando
|
64 |
continue
|
65 |
try:
|
66 |
-
submitted_answer = agent.forward(question_text) #
|
67 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
68 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
69 |
except Exception as e:
|
70 |
-
print(f"Error ejecutando agente
|
71 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
-
#
|
74 |
-
submission_data = {"username": username.strip(), "agent_code": "agent_code_placeholder", "answers": answers_payload}
|
75 |
try:
|
76 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
77 |
response.raise_for_status()
|
78 |
result_data = response.json()
|
79 |
-
final_status =
|
|
|
|
|
|
|
|
|
|
|
80 |
print("Envío exitoso.")
|
81 |
-
|
|
|
82 |
except requests.exceptions.RequestException as e:
|
83 |
-
|
84 |
-
|
|
|
|
|
85 |
|
86 |
-
# Interfaz Gradio
|
87 |
with gr.Blocks() as demo:
|
88 |
-
gr.Markdown("#
|
89 |
-
gr.Markdown("""
|
90 |
-
**Instrucciones:**
|
91 |
-
1. Modifica este espacio con tu lógica de agente y las herramientas necesarias.
|
92 |
-
2. Inicia sesión en Hugging Face con el botón abajo.
|
93 |
-
3. Haz clic en 'Ejecutar Evaluación y Enviar Todas las Respuestas' para obtener resultados.
|
94 |
-
|
95 |
-
**Aviso:**
|
96 |
-
Puede tomar tiempo procesar las respuestas, así que ten paciencia.
|
97 |
-
""")
|
98 |
-
|
99 |
gr.LoginButton()
|
100 |
run_button = gr.Button("Ejecutar Evaluación y Enviar Todas las Respuestas")
|
101 |
status_output = gr.Textbox(label="Resultado de Ejecución / Envío", lines=5, interactive=False)
|
102 |
results_table = gr.DataFrame(label="Preguntas y Respuestas del Agente", wrap=True)
|
103 |
-
|
104 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
105 |
|
106 |
if __name__ == "__main__":
|
|
|
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 |
load_dotenv() # Cargar variables de entorno
|
10 |
|
11 |
+
# Constants
|
12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
|
|
|
14 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
15 |
"""
|
16 |
+
Obtiene todas las preguntas, ejecuta el BasicAgent sobre ellas, envía las respuestas y muestra los resultados.
|
17 |
"""
|
18 |
+
space_id = os.getenv("SPACE_ID") # Obtener el ID del espacio para enviar el enlace al código
|
19 |
|
20 |
if profile:
|
21 |
username = f"{profile.username}"
|
22 |
print(f"Usuario logueado: {username}")
|
23 |
else:
|
24 |
print("Usuario no logueado.")
|
25 |
+
return "Por favor, inicie sesión en Hugging Face.", None
|
26 |
|
27 |
api_url = DEFAULT_API_URL
|
28 |
questions_url = f"{api_url}/questions"
|
29 |
attachments_url = f"{api_url}/files/"
|
30 |
submit_url = f"{api_url}/submit"
|
31 |
|
|
|
32 |
try:
|
33 |
print("Iniciando agente...")
|
34 |
+
agent = agent.BasicAgent() # Aquí inicializamos el agente
|
35 |
except Exception as e:
|
36 |
+
print(f"Error al inicializar el agente: {e}")
|
37 |
+
return f"Error al inicializar el agente: {e}", None
|
38 |
|
39 |
+
# 2. Obtener preguntas
|
40 |
+
print(f"Obteniendo preguntas de: {questions_url}")
|
41 |
try:
|
42 |
response = requests.get(questions_url, timeout=15)
|
43 |
response.raise_for_status()
|
44 |
questions_data = response.json()
|
45 |
if not questions_data:
|
46 |
print("La lista de preguntas está vacía.")
|
47 |
+
return "La lista de preguntas está vacía o en formato incorrecto.", None
|
48 |
+
print(f"Obtenidas {len(questions_data)} preguntas.")
|
49 |
+
for q in questions_data:
|
50 |
+
file_name = q.get("file_name", "")
|
51 |
+
task_id = q.get("task_id")
|
52 |
+
if file_name and task_id:
|
53 |
+
try:
|
54 |
+
att_response = requests.get(f"{attachments_url}{task_id}", timeout=15)
|
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 |
+
# 3. Ejecutar agente sobre preguntas
|
65 |
results_log = []
|
66 |
answers_payload = []
|
67 |
+
print(f"Ejecutando agente sobre {len(questions_data)} preguntas...")
|
68 |
for item in questions_data:
|
69 |
task_id = item.get("task_id")
|
70 |
question_text = item.get("question", "")
|
|
|
72 |
if attachment_b64:
|
73 |
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
74 |
if not task_id or question_text is None:
|
75 |
+
print(f"Saltando elemento con task_id o pregunta faltante: {item}")
|
76 |
continue
|
77 |
try:
|
78 |
+
submitted_answer = agent.forward(question_text) # Aquí ejecutamos el agente para obtener la respuesta
|
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 ejecutando agente sobre tarea {task_id}: {e}")
|
83 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR AGENTE: {e}"})
|
84 |
+
|
85 |
+
if not answers_payload:
|
86 |
+
print("El agente no generó respuestas.")
|
87 |
+
return "El agente no generó respuestas.", pd.DataFrame(results_log)
|
88 |
+
|
89 |
+
# 4. Preparar la sumisión
|
90 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
91 |
+
print(f"Enviando respuestas para el usuario '{username}'...")
|
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 |
+
status_message = f"Error al enviar respuestas: {e}"
|
109 |
+
print(status_message)
|
110 |
+
results_df = pd.DataFrame(results_log)
|
111 |
+
return status_message, results_df
|
112 |
|
113 |
+
# Interfaz de Gradio
|
114 |
with gr.Blocks() as demo:
|
115 |
+
gr.Markdown("# Evaluador de Agente Básico")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
gr.LoginButton()
|
117 |
run_button = gr.Button("Ejecutar Evaluación y Enviar Todas las Respuestas")
|
118 |
status_output = gr.Textbox(label="Resultado de Ejecución / Envío", lines=5, interactive=False)
|
119 |
results_table = gr.DataFrame(label="Preguntas y Respuestas del Agente", wrap=True)
|
|
|
120 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
121 |
|
122 |
if __name__ == "__main__":
|