jjvelezo's picture
Update app.py
7db86c7 verified
raw
history blame
3.06 kB
import os
import gradio as gr
import requests
import pandas as pd
from huggingface_hub import login
from dotenv import load_dotenv
from agent import ejecutar_agente
# Cargar token desde secreto y hacer login
hf_token = os.getenv("HF_TOKEN")
if hf_token:
login(token=hf_token)
else:
raise ValueError("No se encontró el token de Hugging Face. Verifica el secreto HF_TOKEN.")
# Constantes
API_BASE_URL = "https://my-custom-api.hf.space"
def ejecutar_y_enviar_respuestas(profile: gr.OAuthProfile | None):
space_id = os.getenv("MY_SPACE_ID")
if profile:
username = profile.username
print(f"Usuario: {username}")
else:
return "Debes iniciar sesión en Hugging Face.", None
# Obtener preguntas
try:
response = requests.get(f"{API_BASE_URL}/questions", timeout=10)
response.raise_for_status()
preguntas = response.json()
except Exception as e:
return f"Error al obtener preguntas: {e}", None
if not preguntas:
return "No hay preguntas disponibles.", None
for p in preguntas:
task_id = p.get("task_id")
if task_id:
try:
archivo = requests.get(f"{API_BASE_URL}/files/{task_id}", timeout=10)
archivo.raise_for_status()
p["attachment_b64"] = archivo.text
except:
p["attachment_b64"] = None
# Ejecutar agente sobre preguntas
resultados = []
respuestas = []
for item in preguntas:
task_id = item.get("task_id")
pregunta = item.get("question", "")
adjunto = item.get("attachment_b64", "")
if adjunto:
pregunta += f"\n\n[ATTACHMENT:]\n{adjunto}"
try:
respuesta = ejecutar_agente(pregunta)
except Exception as e:
respuesta = f"ERROR: {e}"
respuestas.append({"task_id": task_id, "submitted_answer": respuesta})
resultados.append({"Task ID": task_id, "Question": pregunta, "Submitted Answer": respuesta})
# Enviar respuestas
payload = {
"username": username,
"agent_code": f"https://huggingface.co/spaces/{space_id}",
"answers": respuestas,
}
try:
envio = requests.post(f"{API_BASE_URL}/submit", json=payload, timeout=60)
envio.raise_for_status()
resultado_final = envio.json()
return f"¡Envío exitoso! Score: {resultado_final.get('score', 'N/A')}", pd.DataFrame(resultados)
except Exception as e:
return f"Error al enviar: {e}", pd.DataFrame(resultados)
# Interfaz Gradio
with gr.Blocks() as interfaz:
gr.Markdown("# Evaluador de Agente")
gr.Markdown("Inicia sesión, ejecuta el agente y envía tus respuestas.")
gr.LoginButton()
btn = gr.Button("Ejecutar Evaluación y Enviar Respuestas")
salida_estado = gr.Textbox(label="Estado", lines=4)
salida_tabla = gr.DataFrame(label="Resultados")
btn.click(fn=ejecutar_y_enviar_respuestas, outputs=[salida_estado, salida_tabla])
if __name__ == "__main__":
interfaz.launch()