Upload app.py
#618
by DuyKhai - opened
app.py
CHANGED
|
@@ -1,196 +1,410 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 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 |
-
try:
|
| 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 |
-
return "
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
f"
|
| 109 |
-
f"
|
| 110 |
-
f"
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
return
|
| 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 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|