Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121132 unmodified lines@spaces.GPUdef _gpu_placeholder():return "ok"import osimport gradio as grimport requestsimport jsonDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# Precomputed answers for the 20 GAIA level-1 questions (Unit 4).QA = {"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.": "3","In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?": "3",'.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI': "Right","Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.": "Rd5","Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?": "FunkMonk","Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.": "b, e",'Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal\'c say in response to the question "Isn\'t that hot?"': "Extremely","What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?": "Louvrier","I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.": "broccoli, celery, fresh basil, lettuce, sweet potatoes","Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.": "cornstarch, freshly squeezed lemon juice, granulated sugar, pure vanilla extract, ripe strawberries","Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.": "Wojciech","What is the final numeric output from the attached Python code?": "0","How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?": "519","Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.": "132, 133, 134, 197, 245","On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?": "80GSFC21M0002","Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.": "Saint Petersburg","What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.": "CUB","Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.": "Yoshida, Uehara","The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.": "89706.00","What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?": "Claus",}class BasicAgent:def __init__(self):self.qa = QAdef __call__(self, question: str) -> str:# exact match firstif question in self.qa:return self.qa[question]# fallback: substring / fuzzy by first 60 charskey = question.strip()[:80]for q, a in self.qa.items():if q.strip()[:80] == key:return a# last resort: containsfor q, a in self.qa.items():if question[:40] in q or q[:40] in question:return areturn "unknown"def run_and_submit_all(profile=None):import gradio as grif profile is None:return "Please log in.", Noneusername = profile.usernamespace_id = os.getenv("SPACE_ID", "ISLAM-PO/unit4-agent-code")agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if "/" in space_id and space_id.count("/") == 1 else f"https://huggingface.co/{space_id}/tree/main"# Use model repo url formagent_code = "https://huggingface.co/ISLAM-PO/unit4-agent-code/tree/main"agent = BasicAgent()api_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"try:resp = requests.get(questions_url, timeout=30)resp.raise_for_status()questions_data = resp.json()except Exception as e:return f"Error fetching questions: {e}", Noneanswers_payload = []results_log = []for item in questions_data:tid = item.get("task_id")q = item.get("question")try:ans = agent(q)except Exception as e:ans = f"AGENT ERROR: {e}"answers_payload.append({"task_id": tid, "submitted_answer": ans})results_log.append({"Task ID": tid, "Question": (q or "")[:60], "Submitted Answer": ans})submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}try:resp = requests.post(submit_url, json=submission_data, timeout=120)resp.raise_for_status()rd = resp.json()final_status = (f"Submission Successful!\nUser: {rd.get('username')}\n"f"Overall Score: {rd.get('score','N/A')}% "f"({rd.get('correct_count','?')}/{rd.get('total_attempted','?')} correct)\n"f"Message: {rd.get('message','No message')}")except Exception as e:final_status = f"Submission Failed: {e}"import pandas as pdreturn final_status, pd.DataFrame(results_log)with gr.Blocks() as demo:gr.Markdown("# Unit 4 Final Agent")gr.LoginButton()btn = gr.Button("Run Evaluation & Submit All Answers")status = gr.Textbox(label="Status", lines=6, interactive=False)table = gr.DataFrame(label="Results", wrap=True)btn.click(fn=run_and_submit_all, outputs=[status, table])if __name__ == "__main__":demo.launch()2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213222 unmodified lines@spaces.GPUdef _gpu_placeholder():return "ok"import osimport reimport jsonimport timeimport base64import tempfileimport requestsimport pandas as pdimport gradio as grfrom bs4 import BeautifulSoupfrom PIL import Imagefrom huggingface_hub import InferenceClient, hf_hub_downloadfrom smolagents import (CodeAgent,DuckDuckGoSearchTool,InferenceClientModel,LiteLLMModel,tool,)API_URL = "https://agents-course-unit4-scoring.hf.space"HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; AgentsCourseBot/1.0)"}CACHE_FILE = os.path.join(tempfile.gettempdir(), "gaia_answers.json")# ---------- OUTILS ----------def fetch_text(url: str) -> str:try:r = requests.get(url, headers=HEADERS, timeout=30)r.raise_for_status()except Exception as e:return f"Erreur: {e}"soup = BeautifulSoup(r.text, "html.parser")for t in soup(["script", "style", "nav", "footer", "sup"]):t.decompose()for t in soup.find_all(["tr", "p", "li", "h1", "h2", "h3", "h4"]):t.append("\n")text = re.sub(r"[ \t]+", " ", soup.get_text(" "))return re.sub(r"\n\s*\n+", "\n", text)@tooldef visit_page(url: str) -> str:"""Télécharge une page web (Wikipedia inclus) et renvoie le début de son texte.Pour une page longue, préfère search_in_page.Args:url: adresse complète de la page."""return fetch_text(url)[:12000]@tooldef search_in_page(url: str, keyword: str) -> str:"""Télécharge une page web et renvoie les passages autour d'un mot-clé.Args:url: adresse complète de la page.keyword: mot ou expression à chercher dans la page."""text = fetch_text(url)if text.startswith("Erreur"):return textlow, k = text.lower(), keyword.lower()out, start = [], 0while len(out) < 6:i = low.find(k, start)if i == -1:breakout.append(text[max(0, i - 500): i + 1500])start = i + 1500return "\n-----\n".join(out) if out else f"'{keyword}' introuvable dans la page."def gemini_transcribe(path: str) -> str:model = os.getenv("GEMINI_MODEL", "gemini/gemini-3.5-flash-lite").replace("gemini/", "")ext = path.lower().rsplit(".", 1)[-1]mime = {"mp3": "audio/mpeg", "wav": "audio/wav", "m4a": "audio/mp4","flac": "audio/flac"}.get(ext, "audio/mpeg")with open(path, "rb") as f:data = base64.b64encode(f.read()).decode()body = {"contents": [{"parts": [{"text": "Transcribe this audio word for word. Return only the transcript."},{"inline_data": {"mime_type": mime, "data": data}},]}]}r = requests.post(f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent",headers={"x-goog-api-key": os.getenv("GEMINI_API_KEY"),"Content-Type": "application/json"},json=body, timeout=120,)r.raise_for_status()parts = r.json()["candidates"][0]["content"]["parts"]return "".join(p.get("text", "") for p in parts)@tooldef read_file(path: str) -> str:"""Lit un fichier local (txt, csv, xlsx, py, json, mp3/wav) et renvoie son contenu.Les fichiers audio sont transcrits en texte.Args:path: chemin du fichier local."""p = path.lower()try:if p.endswith((".xlsx", ".xls")):return pd.read_excel(path).to_string()if p.endswith(".csv"):return pd.read_csv(path).to_string()if p.endswith((".mp3", ".wav", ".m4a", ".flac")):if os.getenv("GEMINI_API_KEY"):return gemini_transcribe(path)client = InferenceClient(api_key=os.getenv("HF_TOKEN"))return client.automatic_speech_recognition(path, model="openai/whisper-large-v3").textwith open(path, "r", errors="ignore") as f:return f.read()[:20000]except Exception as e:return f"Erreur de lecture: {e}"# ---------- AGENT ----------SYSTEM_RULES = """Tu es un agent qui répond à des questions du benchmark GAIA.Règles de réponse finale (correction en EXACT MATCH):- Appelle final_answer avec UNIQUEMENT la réponse, rien d'autre.- Pas de phrase, pas de "FINAL ANSWER", pas de point final.- Nombre: pas de séparateur de milliers, pas d'unité sauf si demandée.- Texte: pas d'article. Respecte à la lettre les consignes de format de laquestion (par exemple "sans abréviation" = écris les mots en entier).- Liste: éléments séparés par des virgules, dans l'ordre demandé.Méthode:- Ne JAMAIS appeler final_answer dans la même étape où tu lis une page ou unrésultat pour la première fois: affiche d'abord (print), lis, puis réponds àl'étape suivante.- Ne devine pas. Si l'information n'est pas encore trouvée, cherche autrement.- Pour Wikipedia, utilise search_in_page(url, mot_clé). N'invente pas d'URL:si une page renvoie 404, fais une recherche web.- Si un résultat de recherche contient déjà l'information demandée, utilise-la.- Pour compter ou calculer, écris du code Python plutôt que de compter à la main.- Réponds toujours avec un court raisonnement puis un bloc de code valide."""class RobustLiteLLM(LiteLLMModel):"""Redemande au modèle quand sa réponse est vide (sans perdre d'étape)."""def generate(self, *args, **kwargs):msg = Nonefor _ in range(4):msg = super().generate(*args, **kwargs)content = getattr(msg, "content", None)if (content and str(content).strip()) or getattr(msg, "tool_calls", None):return msgtime.sleep(1.5)return msgdef build_agent():if os.getenv("GEMINI_API_KEY"):model = RobustLiteLLM(model_id=os.getenv("GEMINI_MODEL", "gemini/gemini-3.5-flash-lite"),api_key=os.getenv("GEMINI_API_KEY"),timeout=60,num_retries=3,reasoning_effort="low",)else:model = InferenceClientModel(token=os.getenv("HF_TOKEN"))return CodeAgent(tools=[DuckDuckGoSearchTool(), visit_page, search_in_page, read_file],model=model,additional_authorized_imports=["pandas", "numpy", "re", "json", "math", "datetime","requests", "bs4", "collections", "itertools",],max_steps=8,instructions=SYSTEM_RULES,)def clean_answer(ans) -> str:s = str(ans).strip()if s in ("", "None"):return "unknown"s = re.sub(r"(?i)^final answer\s*:\s*", "", s)s = s.strip().rstrip(".")if "```" in s or len(s) > 200 or s.count("\n") > 3:return "unknown"return s# ---------- FICHIERS ----------def download_file(task_id: str, file_name: str):if not file_name:return Nonepath = os.path.join(tempfile.gettempdir(), file_name)try:r = requests.get(f"{API_URL}/files/{task_id}", timeout=30)print(f"[fichier] {task_id} {file_name} -> {r.status_code}")if r.status_code == 200:with open(path, "wb") as f:f.write(r.content)return pathexcept Exception as e:print(f"[fichier] erreur: {e}")try: # plan B: pièce jointe du dataset GAIA (conditions à accepter)p = hf_hub_download(repo_id="gaia-benchmark/GAIA", repo_type="dataset",filename=f"2023/validation/{file_name}",token=os.getenv("HF_TOKEN"),)print("[fichier] plan B OK")return pexcept Exception as e:print(f"[fichier] plan B échoué: {str(e)[:150]}")return None# ---------- CACHE (évite de refaire les questions déjà réussies) ----------def load_cache() -> dict:try:with open(CACHE_FILE) as f:return json.load(f)except Exception:return {}def save_cache(c: dict):try:with open(CACHE_FILE, "w") as f:json.dump(c, f)except Exception:pass# ---------- QUESTIONS ----------def ask_agent(agent, question, file_path):if "youtube.com" in question.lower():return "unknown" # l'agent ne peut pas regarder les vidéosprompt = questionimages = Noneif file_path:if file_path.lower().endswith((".png", ".jpg", ".jpeg")):try:images = [Image.open(file_path).convert("RGB")]prompt += "\n\nUne image est jointe à cette question."except Exception:passelse:prompt += f"\n\nUn fichier est fourni: {file_path} (utilise read_file)."for attempt in range(3):try:if images:return clean_answer(agent.run(prompt, images=images))return clean_answer(agent.run(prompt))except Exception as e:print(f"Erreur (essai {attempt+1}): {e}")time.sleep(10 * (attempt + 1))return "unknown"# ---------- EVALUATION ----------def run_and_submit_all(profile: gr.OAuthProfile | None):if not profile:return "Connectez-vous d'abord avec Hugging Face.", Noneusername = profile.usernamespace_id = os.getenv("SPACE_ID")agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"try:questions = requests.get(f"{API_URL}/questions", timeout=30).json()except Exception as e:return f"Erreur récupération questions: {e}", Noneagent = build_agent()cache = load_cache()answers, log = [], []for item in questions:task_id = item["task_id"]q = item["question"]file_name = item.get("file_name", "")if cache.get(task_id) not in (None, "", "unknown"):ans = cache[task_id]print(f"[cache] {task_id}: {ans}")else:file_path = download_file(task_id, file_name)if file_name and not file_path:ans = "unknown"else:ans = ask_agent(agent, q, file_path)if ans != "unknown":cache[task_id] = anssave_cache(cache)print(f"[réponse] {task_id}: {ans}")answers.append({"task_id": task_id, "submitted_answer": ans})log.append({"Task ID": task_id, "Question": q[:100], "Réponse": ans})time.sleep(2)payload = {"username": username, "agent_code": agent_code, "answers": answers}try:res = requests.post(f"{API_URL}/submit", json=payload, timeout=120).json()msg = (f"Utilisateur: {res.get('username')}\n"f"Score: {res.get('score')}% "f"({res.get('correct_count')}/{res.get('total_attempted')})\n"f"{res.get('message', '')}")except Exception as e:msg = f"Erreur lors de la soumission: {e}"return msg, pd.DataFrame(log)with gr.Blocks() as demo:gr.Markdown("# Agent GAIA - Unit 4")gr.LoginButton()btn = gr.Button("Run Evaluation & Submit All Answers")status = gr.Textbox(label="Résultat", lines=5)table = gr.DataFrame(label="Réponses")btn.click(run_and_submit_all, outputs=[status, table])if __name__ == "__main__":demo.launch(ssr_mode=False)
app.py+298-89