File size: 5,682 Bytes
0385645
 
0430769
0385645
 
 
0430769
0385645
 
 
0430769
 
 
 
 
 
 
 
402abcf
 
57871b5
 
 
 
402abcf
57871b5
0385645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0430769
0385645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07e174e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b24886
 
 
1dbd212
 
 
 
 
 
 
 
 
2b24886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dbd212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b24886
c362d87
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Dict, Union
from datasets import load_dataset
import random
import os
from huggingface_hub import login

app = FastAPI()

# Logueo para acceder al dataset gated
token = os.getenv("token_curso")
if token:
    login(token)
else:
    print("鈿狅笍 WARNING: No se encontr贸 el token de autenticaci贸n en la variable token_curso")

# Carga y filtra nivel 1 GAIA (validation split)
#ds = load_dataset("gaia-benchmark/GAIA", "2023_level1", split="validation",trust_remote_code=True)
ds = load_dataset(
    "gaia-benchmark/GAIA",
    data_dir="2023_level1",
    split="validation",
    revision="refs/convert/parquet"
)

QUESTIONS = []
GROUND_TRUTH: Dict[str, str] = {}

for item in ds:
    task_id = str(item["task_id"])
    QUESTIONS.append({
        "task_id": task_id,
        "question": item["Question"]
    })
    GROUND_TRUTH[task_id] = str(item["Final answer"])

class AnswerItem(BaseModel):
    task_id: str
    submitted_answer: Union[str, int, float]

class Submission(BaseModel):
    username: str
    agent_code: str
    answers: List[AnswerItem]

class ScoreResponse(BaseModel):
    username: str
    score: float
    correct_count: int
    total_attempted: int
    message: str

@app.get("/questions")
def get_questions():
    # Devuelve las 20 preguntas aleatorias de nivel 1 cada vez
    chosen = random.sample(QUESTIONS, k=min(20, len(QUESTIONS)))
    return chosen

@app.post("/submit")
def submit(sub: Submission):
    correct = sum(
        1 for ans in sub.answers
        if GROUND_TRUTH.get(ans.task_id, "") == str(ans.submitted_answer).strip()
    )
    total = len(sub.answers)
    score = correct / total * 100 if total > 0 else 0.0
    return ScoreResponse(
        username=sub.username,
        score=score,
        correct_count=correct,
        total_attempted=total,
        message=f"Puntuaci贸n: {correct}/{total} = {score:.1f}%"
    )
 # GET /random-question: Fetch a single random question from the list.
@app.get("/random-question")
def get_random_question():
    if not QUESTIONS:
        return {"error": "No questions available"}
    question = random.choice(QUESTIONS)
    return question

# GET /files/{task_id}: Download a specific file associated with a given task ID.
@app.get("/files/{task_id}")
def get_file(task_id: str):
    file_path = f"files/{task_id}.txt"
    if not os.path.exists(file_path):
        return {"error": "File not found"}
    with open(file_path, "r") as file:
        content = file.read()
    return {"task_id": task_id, "content": content}   



from fastapi.responses import HTMLResponse

@app.get("/", response_class=HTMLResponse)
def read_root():
    return """
    <!DOCTYPE html>
    <html>
    <head>
      <title>GAIA Agents - Test Interface</title>
      <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f7f7fa; }
        h1 { color: #6d28d9; }
        button {
          background: #ec4899;
          color: white;
          border: none;
          padding: 10px 20px;
          margin: 10px 0;
          border-radius: 5px;
          font-size: 16px;
          cursor: pointer;
        }
        button:hover { background: #be185d; }
        #questions div {
          background: #fff;
          margin: 10px 0;
          padding: 10px;
          border-radius: 5px;
          box-shadow: 0 1px 4px rgba(0,0,0,0.05);
        }
        input[type="text"] {
          padding: 5px;
          border-radius: 3px;
          border: 1px solid #ddd;
          width: 60%;
        }
        #result { margin-top: 20px; }
      </style>
    </head>
    <body>
      <h1>GAIA Agents - Preguntas y Respuestas</h1>
      <button onclick="loadQuestions()">Cargar preguntas</button>
      <div id="questions"></div>
      <button onclick="submitAnswers()">Enviar respuestas</button>
      <div id="result"></div>
      <script>
        let answers = {};

        async function loadQuestions() {
          const resp = await fetch('/questions');
          const data = await resp.json();
          const container = document.getElementById('questions');
          container.innerHTML = '';
          data.forEach(q => {
            const div = document.createElement('div');
            div.innerHTML = `
              <p><b>${q.task_id}</b>: ${q.question}</p>
              <input type="text" id="answer_${q.task_id}" placeholder="Tu respuesta">
            `;
            container.appendChild(div);
          });
        }

        async function submitAnswers() {
          const container = document.getElementById('questions');
          answers = {};
          Array.from(container.querySelectorAll('input')).forEach(input => {
            const tid = input.id.replace('answer_', '');
            answers[tid] = input.value;
          });

          const payload = {
            username: "tu_usuario",
            agent_code: "https://huggingface.co/spaces/jbaselga/agentes-unit4/tree/main",
            answers: Object.entries(answers).map(([tid, ans]) => ({task_id: tid, submitted_answer: ans}))
          };

          const resp = await fetch('/submit', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
          });

          const result = await resp.json();
          document.getElementById('result').innerHTML = `<h3>Resultado</h3><p>${result.message}</p>`;
        }
      </script>
    </body>
    </html>
    """

import threading

def run_agent():
    import app
    app.main()

# Ejecuta el agente en un hilo aparte al arrancar el servidor
threading.Thread(target=run_agent, daemon=True).start()