Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,36 +1,10 @@
|
|
1 |
-
import
|
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 |
-
|
8 |
-
# Cargar variables de entorno
|
9 |
-
load_dotenv()
|
10 |
-
API_BASE_URL = "https://my-custom-api.hf.space"
|
11 |
-
MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct") # o usa 'google/gemma-2b-it'
|
12 |
-
|
13 |
-
def call_model(prompt):
|
14 |
-
headers = {
|
15 |
-
"Authorization": f"Bearer {os.environ['HF_TOKEN']}",
|
16 |
-
"Content-Type": "application/json"
|
17 |
-
}
|
18 |
-
payload = {
|
19 |
-
"inputs": prompt,
|
20 |
-
"parameters": {"max_new_tokens": 512}
|
21 |
-
}
|
22 |
-
response = requests.post(
|
23 |
-
f"https://api-inference.huggingface.co/models/{MODEL_NAME}",
|
24 |
-
headers=headers,
|
25 |
-
json=payload,
|
26 |
-
timeout=60
|
27 |
-
)
|
28 |
-
result = response.json()
|
29 |
-
if isinstance(result, dict) and result.get("error"):
|
30 |
-
return f"ERROR: {result['error']}"
|
31 |
-
return result[0]["generated_text"] if isinstance(result, list) else result
|
32 |
|
33 |
def execute_agent_operations(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
34 |
space_id = os.getenv("MY_SPACE_ID")
|
35 |
|
36 |
if profile:
|
@@ -44,76 +18,83 @@ def execute_agent_operations(profile: gr.OAuthProfile | None):
|
|
44 |
attachments_url = f"{API_BASE_URL}/files/"
|
45 |
submit_url = f"{API_BASE_URL}/submit"
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
try:
|
48 |
response = requests.get(questions_url, timeout=15)
|
49 |
response.raise_for_status()
|
50 |
questions = response.json()
|
51 |
if not questions:
|
|
|
52 |
return "No se encontraron preguntas.", None
|
|
|
53 |
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
56 |
file_name = q.get("file_name", "")
|
57 |
-
|
|
|
58 |
try:
|
59 |
att_response = requests.get(f"{attachments_url}{task_id}", timeout=15)
|
60 |
att_response.raise_for_status()
|
61 |
q["attachment_b64"] = att_response.text
|
62 |
except Exception as e:
|
63 |
-
print(f"Error al obtener adjunto: {e}")
|
64 |
q["attachment_b64"] = None
|
65 |
-
except
|
|
|
66 |
return f"Error al obtener preguntas: {e}", None
|
67 |
|
|
|
|
|
68 |
results_log = []
|
69 |
answers_payload = []
|
70 |
-
|
71 |
for item in questions:
|
72 |
task_id = item.get("task_id")
|
73 |
question_text = item.get("question", "")
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
if not task_id or not
|
|
|
78 |
continue
|
79 |
-
|
80 |
try:
|
81 |
-
submitted_answer =
|
82 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
83 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
84 |
except Exception as e:
|
|
|
85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
86 |
|
87 |
if not answers_payload:
|
88 |
return "El agente no produjo respuestas.", pd.DataFrame(results_log)
|
89 |
|
90 |
-
submission_data = {
|
91 |
-
|
92 |
-
|
93 |
-
"answers": answers_payload
|
94 |
-
}
|
95 |
|
96 |
try:
|
97 |
-
|
98 |
-
|
99 |
-
result_data =
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
return
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
run_button = gr.Button("Ejecutar Evaluación y Enviar Respuestas")
|
110 |
-
status_output = gr.Textbox(label="Estado", lines=3)
|
111 |
-
results_table = gr.DataFrame(label="Respuestas del agente")
|
112 |
-
|
113 |
-
run_button.click(
|
114 |
-
fn=execute_agent_operations,
|
115 |
-
outputs=[status_output, results_table]
|
116 |
-
)
|
117 |
-
|
118 |
-
if __name__ == "__main__":
|
119 |
-
demo.launch(debug=True)
|
|
|
1 |
+
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
def execute_agent_operations(profile: gr.OAuthProfile | None):
|
4 |
+
"""
|
5 |
+
Obtiene preguntas, ejecuta el agente y envía respuestas.
|
6 |
+
"""
|
7 |
+
# Obtener el ID de espacio
|
8 |
space_id = os.getenv("MY_SPACE_ID")
|
9 |
|
10 |
if profile:
|
|
|
18 |
attachments_url = f"{API_BASE_URL}/files/"
|
19 |
submit_url = f"{API_BASE_URL}/submit"
|
20 |
|
21 |
+
try:
|
22 |
+
print("Iniciando Agente...")
|
23 |
+
# Aquí puedes instanciar tu agente como se define en agent.py
|
24 |
+
# agente = MiAgente()
|
25 |
+
except Exception as e:
|
26 |
+
print(f"Error al inicializar agente: {e}")
|
27 |
+
return f"Error al inicializar el agente: {e}", None
|
28 |
+
|
29 |
+
# Obtener las preguntas
|
30 |
+
print(f"Obteniendo preguntas de: {questions_url}")
|
31 |
try:
|
32 |
response = requests.get(questions_url, timeout=15)
|
33 |
response.raise_for_status()
|
34 |
questions = response.json()
|
35 |
if not questions:
|
36 |
+
print("La lista de preguntas está vacía.")
|
37 |
return "No se encontraron preguntas.", None
|
38 |
+
print(f"Se obtuvieron {len(questions)} preguntas.")
|
39 |
|
40 |
+
# Aquí agregamos el retraso entre cada solicitud para evitar el error 429
|
41 |
+
for i, q in enumerate(questions):
|
42 |
+
if i > 0: # Para no esperar después de la primera solicitud
|
43 |
+
time.sleep(2) # Espera de 2 segundos entre cada consulta
|
44 |
+
|
45 |
file_name = q.get("file_name", "")
|
46 |
+
task_id = q.get("task_id")
|
47 |
+
if file_name and task_id:
|
48 |
try:
|
49 |
att_response = requests.get(f"{attachments_url}{task_id}", timeout=15)
|
50 |
att_response.raise_for_status()
|
51 |
q["attachment_b64"] = att_response.text
|
52 |
except Exception as e:
|
53 |
+
print(f"Error al obtener archivo adjunto para la tarea {task_id}: {e}")
|
54 |
q["attachment_b64"] = None
|
55 |
+
except requests.exceptions.RequestException as e:
|
56 |
+
print(f"Error al obtener preguntas: {e}")
|
57 |
return f"Error al obtener preguntas: {e}", None
|
58 |
|
59 |
+
# Ejecutar el agente
|
60 |
+
print(f"Ejecutando agente en {len(questions)} preguntas...")
|
61 |
results_log = []
|
62 |
answers_payload = []
|
63 |
+
|
64 |
for item in questions:
|
65 |
task_id = item.get("task_id")
|
66 |
question_text = item.get("question", "")
|
67 |
+
attachment_b64 = item.get("attachment_b64", "")
|
68 |
+
if attachment_b64:
|
69 |
+
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
70 |
+
if not task_id or not question_text:
|
71 |
+
print(f"Saltando tarea con información incompleta: {item}")
|
72 |
continue
|
|
|
73 |
try:
|
74 |
+
submitted_answer = "Placeholder" # Aquí llamarías a tu agente para obtener la respuesta
|
75 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
76 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
77 |
except Exception as e:
|
78 |
+
print(f"Error al procesar la tarea {task_id}: {e}")
|
79 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
|
80 |
|
81 |
if not answers_payload:
|
82 |
return "El agente no produjo respuestas.", pd.DataFrame(results_log)
|
83 |
|
84 |
+
submission_data = {"username": username.strip(), "agent_code": f"https://huggingface.co/spaces/{space_id}", "answers": answers_payload}
|
85 |
+
status_update = f"Enviando respuestas para el usuario '{username}'..."
|
86 |
+
print(status_update)
|
|
|
|
|
87 |
|
88 |
try:
|
89 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
90 |
+
response.raise_for_status()
|
91 |
+
result_data = response.json()
|
92 |
+
final_status = f"¡Envío exitoso!\nPuntuación: {result_data.get('score', 'N/A')}"
|
93 |
+
print("Envío exitoso.")
|
94 |
+
results_df = pd.DataFrame(results_log)
|
95 |
+
return final_status, results_df
|
96 |
+
except requests.exceptions.RequestException as e:
|
97 |
+
error_message = f"Error al enviar: {e}"
|
98 |
+
print(error_message)
|
99 |
+
results_df = pd.DataFrame(results_log)
|
100 |
+
return error_message, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|