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()