Files changed (1) hide show
  1. app.py +409 -195
app.py CHANGED
@@ -1,196 +1,410 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
-
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
-
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
-
30
- if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
- else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
-
37
- api_url = DEFAULT_API_URL
38
- questions_url = f"{api_url}/questions"
39
- submit_url = f"{api_url}/submit"
40
-
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
- try:
43
- agent = BasicAgent()
44
- except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
-
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
53
- try:
54
- response = requests.get(questions_url, timeout=15)
55
- response.raise_for_status()
56
- questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
- except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
74
- answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
- continue
82
- try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
-
90
- if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
- try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
- response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
- except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
-
142
-
143
- # --- Build Gradio Interface using Blocks ---
144
- with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
- **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
158
- """
159
- )
160
-
161
- gr.LoginButton()
162
-
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
-
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
-
169
- run_button.click(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
- )
173
-
174
- if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
-
180
- if space_host_startup:
181
- print(f"✅ SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
- else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
-
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
- else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
-
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
-
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  demo.launch(debug=True, share=False)
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import requests
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import wikipediaapi
9
+ from pypdf import PdfReader
10
+ from youtube_transcript_api import YouTubeTranscriptApi
11
+ from smolagents import (
12
+ CodeAgent,
13
+ InferenceClientModel,
14
+ LiteLLMModel,
15
+ WebSearchTool,
16
+ VisitWebpageTool,
17
+ tool,
18
+ )
19
+
20
+ # --- 1. API Constants & Cache ---
21
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
+ CACHE_FILE = "cached_answers.json"
23
+
24
+
25
+ # --- 2. Advanced Multimodal & Research Tools for GAIA ---
26
+
27
+ @tool
28
+ def search_wikipedia(query: str) -> str:
29
+ """
30
+ Fetches the full summary and sections of a Wikipedia page for an exact entity or topic.
31
+ Use this whenever a question mentions Wikipedia, historical facts, discographies, or biographies.
32
+ Args:
33
+ query: Exact title of the Wikipedia article to look up (e.g., "Mercedes Sosa", "Eliud Kipchoge").
34
+ """
35
+ try:
36
+ wiki = wikipediaapi.Wikipedia(user_agent="GAIA_Agent/1.0", language="en")
37
+ page = wiki.page(query)
38
+ if not page.exists():
39
+ return f"No Wikipedia page found for '{query}'. Try searching via web_search first to get the exact title."
40
+ return f"Title: {page.title}\nURL: {page.fullurl}\nContent:\n{page.text[:18000]}"
41
+ except Exception as e:
42
+ return f"Wikipedia error: {e}"
43
+
44
+
45
+ @tool
46
+ def get_youtube_transcript(youtube_url_or_id: str) -> str:
47
+ """
48
+ Extracts the full text transcript/captions of a YouTube video.
49
+ Use this whenever a question includes a youtube.com or youtu.be link!
50
+ Args:
51
+ youtube_url_or_id: The full YouTube URL or the 11-character video ID.
52
+ """
53
+ try:
54
+ match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", youtube_url_or_id)
55
+ video_id = match.group(1) if match else youtube_url_or_id.strip()
56
+ ytt_api = YouTubeTranscriptApi()
57
+ fetched = ytt_api.fetch(video_id)
58
+ lines = [f"[{int(snippet.start)}s] {snippet.text}" for snippet in fetched]
59
+ return "\n".join(lines)[:18000]
60
+ except Exception as e:
61
+ return f"Error fetching YouTube transcript: {e}"
62
+
63
+
64
+ @tool
65
+ def read_pdf_file(file_path: str) -> str:
66
+ """
67
+ Extracts all text from a local PDF (.pdf) file.
68
+ Args:
69
+ file_path: Path to the local PDF file.
70
+ """
71
+ try:
72
+ reader = PdfReader(file_path)
73
+ text = []
74
+ for idx, page in enumerate(reader.pages):
75
+ text.append(f"--- Page {idx + 1} ---\n{page.extract_text()}")
76
+ return "\n".join(text)[:20000]
77
+ except Exception as e:
78
+ return f"Error reading PDF: {e}"
79
+
80
+
81
+ @tool
82
+ def read_text_or_code_file(file_path: str) -> str:
83
+ """
84
+ Reads the text content of a local file (.txt, .py, .csv, .md, .json, .pdb).
85
+ Args:
86
+ file_path: Path to the local file downloaded for the task.
87
+ """
88
+ try:
89
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
90
+ return f.read()[:20000]
91
+ except Exception as e:
92
+ return f"Error reading file: {e}"
93
+
94
+
95
+ @tool
96
+ def read_excel_or_csv(file_path: str) -> str:
97
+ """
98
+ Reads an Excel (.xlsx, .xls) or CSV (.csv) file and returns its columns, summary stats, and full table data.
99
+ Args:
100
+ file_path: Path to the local Excel or CSV file.
101
+ """
102
+ try:
103
+ if file_path.endswith(".csv"):
104
+ df = pd.read_csv(file_path)
105
+ else:
106
+ df = pd.read_excel(file_path)
107
+ return (
108
+ f"Columns: {list(df.columns)}\n"
109
+ f"Shape: {df.shape}\n"
110
+ f"Data:\n{df.to_string()}\n"
111
+ f"Numeric Summary:\n{df.describe().to_string()}"
112
+ )
113
+ except Exception as e:
114
+ return f"Error reading spreadsheet: {e}"
115
+
116
+
117
+ @tool
118
+ def inspect_image_or_audio(file_path: str, task_instruction: str) -> str:
119
+ """
120
+ Uses a multimodal model to transcribe audio (.mp3, .wav) or analyze images (.png, .jpg, .webp) such as chessboards, charts, or handwriting.
121
+ Args:
122
+ file_path: Path to the local audio or image file.
123
+ task_instruction: Specific question or instruction about the image or audio (e.g., "Transcribe this audio word for word" or "List the exact coordinates of all pieces on this chessboard").
124
+ """
125
+ try:
126
+ # Route 1: Gemini Multimodal API (Handles both Audio and Images natively)
127
+ if os.getenv("GEMINI_API_KEY"):
128
+ from google import genai
129
+ client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
130
+ uploaded_file = client.files.upload(file=file_path)
131
+ response = client.models.generate_content(
132
+ model="gemini-2.5-flash",
133
+ contents=[uploaded_file, task_instruction],
134
+ )
135
+ return response.text
136
+
137
+ # Route 2: Hugging Face Serverless ASR fallback for audio if no Gemini key
138
+ if file_path.lower().endswith((".mp3", ".wav", ".m4a", ".flac")):
139
+ from huggingface_hub import InferenceClient
140
+ hf_client = InferenceClient(token=os.getenv("HF_TOKEN"))
141
+ result = hf_client.automatic_speech_recognition(file_path, model="openai/whisper-large-v3-turbo")
142
+ return f"Audio Transcription: {result.text}"
143
+
144
+ return "Multimodal inspection requires GEMINI_API_KEY secret for images or HF_TOKEN for audio."
145
+ except Exception as e:
146
+ return f"Error inspecting media file: {e}"
147
+
148
+
149
+ # --- 3. Upgraded GAIAAgent with Planning & Two-Stage Answer Verification ---
150
+ class GAIAAgent:
151
+ def __init__(self):
152
+ print("Initializing Upgraded GAIAAgent...")
153
+
154
+ if os.getenv("GEMINI_API_KEY"):
155
+ print("Using Gemini 2.5 Flash via LiteLLMModel")
156
+ self.model = LiteLLMModel(
157
+ model_id="gemini/gemini-2.5-flash",
158
+ api_key=os.getenv("GEMINI_API_KEY"),
159
+ temperature=0.0,
160
+ )
161
+ else:
162
+ print("Using Qwen/Qwen2.5-Coder-32B-Instruct via InferenceClientModel")
163
+ self.model = InferenceClientModel(
164
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
165
+ token=os.getenv("HF_TOKEN"),
166
+ temperature=0.0,
167
+ )
168
+
169
+ self.agent = CodeAgent(
170
+ tools=[
171
+ WebSearchTool(),
172
+ VisitWebpageTool(),
173
+ search_wikipedia,
174
+ get_youtube_transcript,
175
+ read_pdf_file,
176
+ read_text_or_code_file,
177
+ read_excel_or_csv,
178
+ inspect_image_or_audio,
179
+ ],
180
+ model=self.model,
181
+ additional_authorized_imports=[
182
+ "pandas", "numpy", "datetime", "math", "re", "json",
183
+ "csv", "openpyxl", "pypdf", "collections", "itertools",
184
+ "statistics", "urllib", "bs4"
185
+ ],
186
+ max_steps=12,
187
+ planning_interval=3, # Re-evaluates plan every 3 steps so it never gets stuck
188
+ )
189
+
190
+ def clean_and_verify_answer(self, question: str, raw_answer: str) -> str:
191
+ """
192
+ Two-stage post-processor:
193
+ 1. Uses an LLM formatter pass to ensure strict GAIA Exact-Match compliance.
194
+ 2. Applies regex sanitization as a safety net.
195
+ """
196
+ raw_str = str(raw_answer).strip()
197
+
198
+ verification_prompt = f"""You are a strict GAIA benchmark answer extractor.
199
+ Given the original QUESTION and the AGENT'S RAW OUTPUT, extract ONLY the exact final answer required by the question.
200
+
201
+ RULES:
202
+ 1. Output ONLY the final answer string. Do NOT include any explanation, prefix, or "FINAL ANSWER:".
203
+ 2. If the question asks for a number/count, output ONLY digits (e.g., 14, not "14 albums" or "fourteen") unless units are explicitly requested.
204
+ 3. If the question asks for currency/money, follow the unit requested (e.g., if it asks "in USD" or "$", strip extra text).
205
+ 4. If the question asks for a comma-separated or alphabetical list, double-check the alphabetical/numerical sorting and use ", " (comma + single space) between items.
206
+ 5. Notice if the question is written backwards/reversed—if so, answer the decoded question directly.
207
+ 6. Do NOT wrap the output in quotes.
208
+
209
+ QUESTION:
210
+ {question}
211
+
212
+ AGENT'S RAW OUTPUT:
213
+ {raw_str}
214
+
215
+ EXACT FINAL ANSWER:"""
216
+
217
+ try:
218
+ messages = [{"role": "user", "content": [{"type": "text", "text": verification_prompt}]}]
219
+ response = self.model(messages)
220
+ verified = response.content.strip()
221
+ except Exception:
222
+ verified = raw_str
223
+
224
+ # Final Regex Safety Net
225
+ ans = re.sub(r"^(final answer|exact final answer)\s*[:\-]?\s*", "", verified, flags=re.IGNORECASE).strip()
226
+ ans = ans.strip('"\'`')
227
+ if ans.endswith(".") and len(ans) < 50:
228
+ ans = ans[:-1].strip()
229
+ return ans
230
+
231
+ def __call__(self, question: str, file_path: str | None = None) -> str:
232
+ prompt = f"""You are an elite autonomous agent solving a GAIA benchmark question.
233
+
234
+ STRATEGY GUIDELINES:
235
+ 1. Read the question carefully. If the text is reversed or encoded, write a 1-line Python snippet to reverse/decode it first!
236
+ 2. If a local file path is attached:
237
+ - For `.mp3`, `.wav`, `.png`, `.jpg`: call `inspect_image_or_audio(file_path, task_instruction=...)`.
238
+ - For `.xlsx`, `.csv`: call `read_excel_or_csv(file_path)` or write pandas code directly to filter/sum accurately.
239
+ - For `.pdf`: call `read_pdf_file(file_path)`.
240
+ - For `.py`, `.txt`: call `read_text_or_code_file(file_path)`.
241
+ 3. If the question mentions a YouTube link, ALWAYS call `get_youtube_transcript` first.
242
+ 4. If the question asks about Wikipedia, biographies, albums, or historical facts, use `search_wikipedia` in addition to `web_search`.
243
+ 5. Always use Python code to compute math, counts, sorting, or filtering rather than doing mental math.
244
+
245
+ QUESTION:
246
+ {question}
247
+ """
248
+ if file_path:
249
+ prompt += f"\nATTACHED LOCAL FILE PATH: {file_path}\n"
250
+
251
+ prompt += """
252
+ When calling `final_answer(...)`, pass ONLY the exact answer required by the question and nothing else.
253
+ """
254
+ try:
255
+ raw_result = self.agent.run(prompt)
256
+ cleaned = self.clean_and_verify_answer(question, raw_result)
257
+ print(f"Raw Output: {raw_result} --> ✅ Verified Final Answer: {cleaned}")
258
+ return cleaned
259
+ except Exception as e:
260
+ print(f"❌ Agent execution error: {e}")
261
+ return "Error"
262
+
263
+
264
+ # --- 4. Helper to Download Attached Files via GET /files/{task_id} ---
265
+ def download_task_file(api_url: str, task_id: str, file_name: str) -> str | None:
266
+ if not file_name:
267
+ return None
268
+ os.makedirs("downloads", exist_ok=True)
269
+ local_path = os.path.join("downloads", f"{task_id}_{file_name}")
270
+ if os.path.exists(local_path) and os.path.getsize(local_path) > 0:
271
+ return local_path
272
+
273
+ file_url = f"{api_url}/files/{task_id}"
274
+ try:
275
+ print(f"Downloading attachment from {file_url} ...")
276
+ resp = requests.get(file_url, timeout=30)
277
+ if resp.status_code == 200:
278
+ with open(local_path, "wb") as f:
279
+ f.write(resp.content)
280
+ return local_path
281
+ except Exception as e:
282
+ print(f"Warning: Failed to download file for task {task_id}: {e}")
283
+ return None
284
+
285
+
286
+ # --- 5. Cache Helpers (Avoid Re-Running Solved Questions) ---
287
+ def load_cache() -> dict:
288
+ if os.path.exists(CACHE_FILE):
289
+ try:
290
+ with open(CACHE_FILE, "r", encoding="utf-8") as f:
291
+ return json.load(f)
292
+ except Exception:
293
+ return {}
294
+ return {}
295
+
296
+
297
+ def save_cache(cache: dict):
298
+ with open(CACHE_FILE, "w", encoding="utf-8") as f:
299
+ json.dump(cache, f, indent=2, ensure_ascii=False)
300
+
301
+
302
+ # --- 6. Main Evaluation & Submission Loop ---
303
+ def run_and_submit_all(profile: gr.OAuthProfile | None, use_cache: bool = True):
304
+ space_id = os.getenv("SPACE_ID")
305
+
306
+ if profile:
307
+ username = f"{profile.username}"
308
+ print(f"User logged in: {username}")
309
+ else:
310
+ return "⚠️ Please Login to Hugging Face with the button above first!", None
311
+
312
+ api_url = DEFAULT_API_URL
313
+ questions_url = f"{api_url}/questions"
314
+ submit_url = f"{api_url}/submit"
315
+
316
+ try:
317
+ agent = GAIAAgent()
318
+ except Exception as e:
319
+ return f"Error initializing agent: {e}", None
320
+
321
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "https://huggingface.co/spaces"
322
+
323
+ print(f"Fetching questions from: {questions_url}")
324
+ try:
325
+ response = requests.get(questions_url, timeout=30)
326
+ response.raise_for_status()
327
+ questions_data = response.json()
328
+ except Exception as e:
329
+ return f"Error fetching questions: {e}", None
330
+
331
+ cache = load_cache() if use_cache else {}
332
+ results_log = []
333
+ answers_payload = []
334
+
335
+ for idx, item in enumerate(questions_data, 1):
336
+ task_id = item.get("task_id")
337
+ question_text = item.get("question")
338
+ file_name = item.get("file_name")
339
+
340
+ if not task_id or question_text is None:
341
+ continue
342
+
343
+ print(f"\n--- [{idx}/{len(questions_data)}] Task {task_id} ---")
344
+
345
+ # Use cached answer if available and valid
346
+ if use_cache and task_id in cache and cache[task_id] not in ("Error", "", None):
347
+ submitted_answer = cache[task_id]
348
+ print(f"⚡ Loaded from cache: {submitted_answer}")
349
+ else:
350
+ local_file = download_task_file(api_url, task_id, file_name)
351
+ submitted_answer = agent(question_text, file_path=local_file)
352
+ cache[task_id] = submitted_answer
353
+ save_cache(cache)
354
+ time.sleep(2) # Gentle pause to prevent API/search rate-limiting
355
+
356
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
357
+ results_log.append({
358
+ "Task ID": task_id,
359
+ "Question": question_text,
360
+ "File": file_name or "None",
361
+ "Submitted Answer": submitted_answer,
362
+ })
363
+
364
+ submission_data = {
365
+ "username": username.strip(),
366
+ "agent_code": agent_code,
367
+ "answers": answers_payload,
368
+ }
369
+
370
+ print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
371
+ try:
372
+ response = requests.post(submit_url, json=submission_data, timeout=60)
373
+ response.raise_for_status()
374
+ result_data = response.json()
375
+ final_status = (
376
+ f"🎉 Submission Successful!\n"
377
+ f"User: {result_data.get('username')}\n"
378
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
379
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
380
+ f"Message: {result_data.get('message', 'No message received.')}"
381
+ )
382
+ return final_status, pd.DataFrame(results_log)
383
+ except Exception as e:
384
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
385
+
386
+
387
+ # --- 7. Gradio UI ---
388
+ with gr.Blocks() as demo:
389
+ gr.Markdown("# 🕵🏻‍♂️ Upgraded Multimodal GAIA Agent Runner")
390
+ gr.Markdown(
391
+ "1. Log in to your Hugging Face account using the button below.\n"
392
+ "2. Click **Run Evaluation & Submit All Answers** to run the multimodal `CodeAgent` with Wikipedia, YouTube, Audio/Vision, and Two-Stage Exact-Match Verification."
393
+ )
394
+ gr.LoginButton()
395
+ use_cache_checkbox = gr.Checkbox(
396
+ value=True,
397
+ label="Use local answer cache (skips questions already solved in previous runs)"
398
+ )
399
+ run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
400
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=6, interactive=False)
401
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
402
+
403
+ run_button.click(
404
+ fn=run_and_submit_all,
405
+ inputs=[gr.State(), use_cache_checkbox],
406
+ outputs=[status_output, results_table],
407
+ )
408
+
409
+ if __name__ == "__main__":
410
  demo.launch(debug=True, share=False)