import os import gradio as gr import requests import openai from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool from pathlib import Path import tempfile from smolagents.tools import Tool import pathlib from typing import Union, Optional import pandas as pd from tabulate import tabulate # pragma: no cover – fallback path import re # --- Constants --- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" class SpeechToTextTool(Tool): """ Transcribes an audio file to text using the OpenAI Whisper API. Only local file paths are supported. """ name = "transcriber" description = ( "This tool sends an audio file to OpenAI Whisper and returns the " "transcribed text." ) inputs = { "audio": { "type": "string", "description": "Absolute or relative path to a local audio file.", } } output_type = "string" def forward(self, audio: str) -> str: path = Path(audio).expanduser().resolve() if not path.is_file(): raise FileNotFoundError(f"No such audio file: {path}") with path.open("rb") as fp: response = openai.audio.transcriptions.create( file=fp, model="whisper-1", response_format="text" ) return response class ExcelToTextTool(Tool): """Render an Excel worksheet as Markdown text.""" name = "excel_to_text" description = ( "Read an Excel file and return a Markdown table of the requested sheet. " "Accepts either the sheet name or the zero-based index." ) inputs = { "excel_path": { "type": "string", "description": "Path to the Excel file (.xlsx / .xls).", }, "sheet_name": { "type": "string", "description": "Worksheet name or zero‑based index as a string (optional).", "nullable": True, }, } output_type = "string" def forward( self, excel_path: str, sheet_name: Optional[str] = None, ) -> str: path = pathlib.Path(excel_path).expanduser().resolve() if not path.exists(): return f"Error: Excel file not found at {path}" try: sheet = 0 if not sheet_name or sheet_name == "" else ( int(sheet_name) if sheet_name.isdigit() else sheet_name ) df = pd.read_excel(path, sheet_name=sheet) if hasattr(df, "to_markdown"): return df.to_markdown(index=False) return tabulate(df, headers="keys", tablefmt="github", showindex=False) except Exception as exc: return f"Error reading Excel file: {exc}" def download_file_if_any(base_api_url: str, task_id: str) -> Optional[str]: """ Try GET /files/{task_id}. • On HTTP 200 → save to temp dir and return local path. • On 404 → return None. """ url = f"{base_api_url}/files/{task_id}" resp = requests.get(url, timeout=30) if resp.status_code == 404: return None resp.raise_for_status() # save to temp cdisp = resp.headers.get("content-disposition", "") filename = task_id if "filename=" in cdisp: m = re.search(r'filename="([^"]+)"', cdisp) if m: filename = m.group(1) tmp_dir = Path(tempfile.gettempdir()) / "gaia_files" tmp_dir.mkdir(exist_ok=True) file_path = tmp_dir / filename with open(file_path, "wb") as f: f.write(resp.content) return str(file_path) # --- Basic Agent Definition --- class BasicAgent: def __init__(self): self.agent = CodeAgent( model=OpenAIServerModel(model_id="gpt-4o"), tools=[ DuckDuckGoSearchTool(), WikipediaSearchTool(), SpeechToTextTool(), ExcelToTextTool() ], add_base_tools=True, additional_authorized_imports=['pandas', 'numpy', 'csv', 'subprocess'] ) print("BasicAgent initialized.") def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") raw = self.agent.run(question) clean = self._clean(raw) print(f"Agent returning cleaned answer: {clean}") return clean def _clean(self, text: str) -> str: """ Post-process the raw agent output to extract just the final answer. 1) If 'FINAL ANSWER:' appears, take what follows. 2) Otherwise, take the last non-blank line. 3) Strip trailing periods. """ # 1) look for "FINAL ANSWER:" marker m = re.search(r'FINAL ANSWER:\s*(.+)', text, re.IGNORECASE) if m: ans = m.group(1).strip() else: lines = [l.strip() for l in text.strip().splitlines() if l.strip()] ans = lines[-1] if lines else text.strip() # 2) remove any trailing period return ans.rstrip('.') def run_and_submit_all(username: str): """ Fetches questions, runs BasicAgent on each, submits answers, and returns (status_message, results_df). """ if not username or not username.strip(): return "Error: Please enter your username.", None api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit" try: agent = BasicAgent() except Exception as e: return f"Error initializing agent: {e}", None # fetch questions try: resp = requests.get(questions_url, timeout=15) resp.raise_for_status() questions = resp.json() except Exception as e: return f"Error fetching questions: {e}", None results = [] answers_payload = [] for item in questions: tid = item.get("task_id") qtext = item.get("question") if not tid or not qtext: continue # download file if any try: fp = download_file_if_any(api_url, tid) except Exception as e: fp = None prompt = qtext if fp: prompt += f"\n\n---\nA file was downloaded and saved at:\n{fp}\n---\n" try: ans = agent(prompt) except Exception as e: ans = f"AGENT ERROR: {e}" results.append({ "Task ID": tid, "Question": qtext, "Submitted Answer": ans }) answers_payload.append({"task_id": tid, "submitted_answer": ans}) if not answers_payload: return "Agent produced no answers.", pd.DataFrame(results) # submit submission = { "username": username.strip(), "agent_code": f"https://huggingface.co/spaces/l3xv/Final_Assignment_Template/tree/main", "answers": answers_payload } try: r2 = requests.post(submit_url, json=submission, timeout=60) r2.raise_for_status() res = r2.json() status = ( f"Submission Successful!\n" f"User: {res.get('username')}\n" f"Score: {res.get('score', 'N/A')}% " f"({res.get('correct_count', '?')}/{res.get('total_attempted', '?')})" ) except Exception as e: status = f"Submission Failed: {e}" return status, pd.DataFrame(results) # --- Gradio UI --- with gr.Blocks() as demo: gr.Markdown("# GAIA Agent Evaluation Runner") gr.Markdown("Enter your Hugging Face username below, then click **Run Evaluation & Submit All Answers**") username_input = gr.Textbox(label="Username", placeholder="hf_username") run_btn = gr.Button("Run Evaluation & Submit All Answers") status_box = gr.Textbox(label="Status / Submission Result", interactive=False, lines=3) results_tbl = gr.DataFrame(label="Questions & Answers", wrap=True) run_btn.click( fn=run_and_submit_all, inputs=[username_input], outputs=[status_box, results_tbl], ) if __name__ == "__main__": print("Launching GAIA Agent App…") demo.launch(debug=True, share=False)