File size: 7,203 Bytes
b0902bb
10e9b7d
b0902bb
 
 
10e9b7d
3c4371f
b0902bb
 
 
 
 
 
 
 
 
6f4a9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0902bb
 
 
 
 
 
 
10e9b7d
31243f4
b0902bb
6f4a9e5
 
 
 
b0902bb
 
 
eccf8e4
b0902bb
7d65c66
b0902bb
 
 
 
 
 
 
 
 
6f4a9e5
b0902bb
 
 
 
 
 
 
 
 
6f4a9e5
 
 
 
 
 
 
 
 
 
 
b0902bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
b0902bb
e80aab9
b0902bb
 
 
 
 
 
 
e80aab9
b0902bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
b0902bb
0ee0419
e514fd7
b0902bb
 
e514fd7
6f4a9e5
 
 
 
 
 
e514fd7
e80aab9
7e4a06b
b0902bb
 
 
 
 
e80aab9
b0902bb
 
e80aab9
 
 
b0902bb
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
194
import json
import os
from datetime import datetime, timezone
from pathlib import Path

import gradio as gr
import pandas as pd
import requests

from agent import API_URL, ResearchAgent, download_attachment


CACHE_DIR = Path(".gaia_cache")
CACHE_FILE = CACHE_DIR / "latest_answers.json"


def _load_cached_answers() -> dict[str, dict]:
    if not CACHE_FILE.exists():
        return {}
    try:
        data = json.loads(CACHE_FILE.read_text(encoding="utf-8"))
        rows = data.get("rows", [])
        return {
            str(row.get("Task ID")): row
            for row in rows
            if str(row.get("Submitted Answer") or "").strip()
        }
    except Exception:
        return {}


def run_and_submit_all(profile: gr.OAuthProfile | None, progress=gr.Progress()):
    if not profile:
        return "Please log in to Hugging Face with the login button.", None

    space_id = os.getenv("SPACE_ID")
    if not space_id:
        return "SPACE_ID is missing from the Space environment.", None

    try:
        agent = ResearchAgent()
        # Avoid repeating the same authorization failure across all 20 tasks.
        progress(0, desc="Checking Hugging Face inference authorization")
        preflight = agent.preflight()
        print(f"Inference preflight succeeded: {preflight!r}")
    except Exception as error:
        return f"Agent initialization failed: {error}", None

    try:
        response = requests.get(f"{API_URL}/questions", timeout=45)
        response.raise_for_status()
        questions = response.json()
        if not isinstance(questions, list) or not questions:
            raise RuntimeError("Question API returned an empty or invalid list.")
    except Exception as error:
        return f"Could not fetch evaluation questions: {error}", None

    answers = []
    rows = []
    attachments_dir = CACHE_DIR / "files"
    cached = _load_cached_answers()

    for index, item in enumerate(questions, start=1):
        task_id = str(item.get("task_id") or "")
        question = str(item.get("question") or "")
        file_name = str(item.get("file_name") or "")
        progress((index - 1, len(questions)), desc=f"Solving question {index}/{len(questions)}")

        answer = ""
        status = "Answered"
        cached_row = cached.get(task_id)
        if cached_row:
            answer = str(cached_row.get("Submitted Answer") or "").strip()
            status = "Reused cached answer"
        else:
            try:
                attachment = download_attachment(task_id, file_name, attachments_dir)
                answer = agent.answer(task_id, question, attachment)
            except Exception as error:
                status = f"ERROR: {error}"
                print(f"Task {task_id} failed: {error}")

        answers.append({"task_id": task_id, "submitted_answer": answer})
        rows.append(
            {
                "#": index,
                "Task ID": task_id,
                "Question": question,
                "File": file_name,
                "Submitted Answer": answer,
                "Status": status,
            }
        )

        CACHE_DIR.mkdir(parents=True, exist_ok=True)
        CACHE_FILE.write_text(
            json.dumps(
                {
                    "username": profile.username,
                    "space_id": space_id,
                    "saved_at": datetime.now(timezone.utc).isoformat(),
                    "answers": answers,
                    "rows": rows,
                },
                indent=2,
                ensure_ascii=False,
            ),
            encoding="utf-8",
        )

    progress((len(questions), len(questions)), desc="Submitting answers")
    submission = {
        "username": profile.username.strip(),
        "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
        "answers": answers,
    }

    try:
        response = requests.post(f"{API_URL}/submit", json=submission, timeout=180)
        response.raise_for_status()
        result = response.json()
        status = (
            "Submission successful!\n"
            f"User: {result.get('username')}\n"
            f"Overall score: {result.get('score', 'N/A')}% "
            f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
            f"Message: {result.get('message', '')}"
        )
    except requests.exceptions.HTTPError as error:
        detail = error.response.text[:1000] if error.response is not None else str(error)
        status = f"Submission failed with HTTP error: {detail}"
    except Exception as error:
        status = f"Submission failed: {error}"

    return status, pd.DataFrame(rows)


def submit_cached(profile: gr.OAuthProfile | None):
    if not profile:
        return "Please log in to Hugging Face with the login button.", None
    if not CACHE_FILE.exists():
        return "No cached run exists yet. Run the evaluation first.", None

    data = json.loads(CACHE_FILE.read_text(encoding="utf-8"))
    space_id = os.getenv("SPACE_ID") or data.get("space_id")
    submission = {
        "username": profile.username.strip(),
        "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
        "answers": data.get("answers", []),
    }
    try:
        response = requests.post(f"{API_URL}/submit", json=submission, timeout=180)
        response.raise_for_status()
        result = response.json()
        status = (
            "Cached answers submitted successfully!\n"
            f"Overall score: {result.get('score', 'N/A')}% "
            f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
            f"Message: {result.get('message', '')}"
        )
    except Exception as error:
        status = f"Cached submission failed: {error}"
    return status, pd.DataFrame(data.get("rows", []))


with gr.Blocks() as demo:
    gr.Markdown("# GAIA Multimodal Research Agent")
    gr.Markdown(
        """
        This public Space uses paid Hugging Face Inference Providers plus web,
        spreadsheet, Python, image, video-transcript, and audio tools.

        1. Add a private Space secret named **HF_INFERENCE_TOKEN** using a
           fine-grained token with **Make calls to Inference Providers** permission.
        2. Log in with the Hugging Face account that should receive the score.
        3. Click **Run Evaluation & Submit All Answers** and wait.
        4. Re-running automatically reuses successful answers and retries failed tasks.
        5. If only the final submission times out, use **Resubmit Cached Answers**.
        """
    )
    gr.LoginButton()
    with gr.Row():
        run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
        cached_button = gr.Button("Resubmit Cached Answers")
    status_output = gr.Textbox(label="Run / submission status", lines=6, interactive=False)
    results_table = gr.DataFrame(label="Questions and answers", wrap=True)

    run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
    cached_button.click(fn=submit_cached, outputs=[status_output, results_table])


if __name__ == "__main__":
    demo.queue(default_concurrency_limit=1).launch()