ilyassman commited on
Commit
4de8fbd
·
verified ·
1 Parent(s): ba03248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +298 -89
app.py CHANGED
@@ -3,111 +3,320 @@ import spaces
3
  @spaces.GPU
4
  def _gpu_placeholder():
5
  return "ok"
 
6
  import os
7
- import gradio as gr
8
- import requests
9
  import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
-
13
- # Precomputed answers for the 20 GAIA level-1 questions (Unit 4).
14
- QA = {
15
- "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",
16
- "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?": "3",
17
- '.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI': "Right",
18
- "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",
19
- "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?": "FunkMonk",
20
- "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",
21
- '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",
22
- "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",
23
- "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",
24
- "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",
25
- "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",
26
- "What is the final numeric output from the attached Python code?": "0",
27
- "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?": "519",
28
- "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",
29
- "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",
30
- "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",
31
- "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",
32
- "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",
33
- "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",
34
- "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",
35
- }
36
-
37
-
38
- class BasicAgent:
39
- def __init__(self):
40
- self.qa = QA
41
- def __call__(self, question: str) -> str:
42
- # exact match first
43
- if question in self.qa:
44
- return self.qa[question]
45
- # fallback: substring / fuzzy by first 60 chars
46
- key = question.strip()[:80]
47
- for q, a in self.qa.items():
48
- if q.strip()[:80] == key:
49
- return a
50
- # last resort: contains
51
- for q, a in self.qa.items():
52
- if question[:40] in q or q[:40] in question:
53
- return a
54
  return "unknown"
 
55
 
 
56
 
57
- def run_and_submit_all(profile=None):
58
- import gradio as gr
59
- if profile is None:
60
- return "Please log in.", None
61
- username = profile.username
62
- space_id = os.getenv("SPACE_ID", "ISLAM-PO/unit4-agent-code")
63
- 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"
64
- # Use model repo url form
65
- agent_code = "https://huggingface.co/ISLAM-PO/unit4-agent-code/tree/main"
66
- agent = BasicAgent()
67
- api_url = DEFAULT_API_URL
68
- questions_url = f"{api_url}/questions"
69
- submit_url = f"{api_url}/submit"
70
  try:
71
- resp = requests.get(questions_url, timeout=30)
72
- resp.raise_for_status()
73
- questions_data = resp.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  except Exception as e:
75
- return f"Error fetching questions: {e}", None
76
- answers_payload = []
77
- results_log = []
78
- for item in questions_data:
79
- tid = item.get("task_id")
80
- q = item.get("question")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  try:
82
- ans = agent(q)
 
 
83
  except Exception as e:
84
- ans = f"AGENT ERROR: {e}"
85
- answers_payload.append({"task_id": tid, "submitted_answer": ans})
86
- results_log.append({"Task ID": tid, "Question": (q or "")[:60], "Submitted Answer": ans})
87
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
 
 
 
 
88
  try:
89
- resp = requests.post(submit_url, json=submission_data, timeout=120)
90
- resp.raise_for_status()
91
- rd = resp.json()
92
- final_status = (
93
- f"Submission Successful!\nUser: {rd.get('username')}\n"
94
- f"Overall Score: {rd.get('score','N/A')}% "
95
- f"({rd.get('correct_count','?')}/{rd.get('total_attempted','?')} correct)\n"
96
- f"Message: {rd.get('message','No message')}"
97
- )
98
  except Exception as e:
99
- final_status = f"Submission Failed: {e}"
100
- import pandas as pd
101
- return final_status, pd.DataFrame(results_log)
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  with gr.Blocks() as demo:
105
- gr.Markdown("# Unit 4 Final Agent")
106
  gr.LoginButton()
107
  btn = gr.Button("Run Evaluation & Submit All Answers")
108
- status = gr.Textbox(label="Status", lines=6, interactive=False)
109
- table = gr.DataFrame(label="Results", wrap=True)
110
- btn.click(fn=run_and_submit_all, outputs=[status, table])
111
 
112
  if __name__ == "__main__":
113
- demo.launch()
 
3
  @spaces.GPU
4
  def _gpu_placeholder():
5
  return "ok"
6
+
7
  import os
8
+ import re
 
9
  import json
10
+ import time
11
+ import base64
12
+ import tempfile
13
+ import requests
14
+ import pandas as pd
15
+ import gradio as gr
16
+ from bs4 import BeautifulSoup
17
+ from PIL import Image
18
+ from huggingface_hub import InferenceClient, hf_hub_download
19
+ from smolagents import (
20
+ CodeAgent,
21
+ DuckDuckGoSearchTool,
22
+ InferenceClientModel,
23
+ LiteLLMModel,
24
+ tool,
25
+ )
26
+
27
+ API_URL = "https://agents-course-unit4-scoring.hf.space"
28
+ HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; AgentsCourseBot/1.0)"}
29
+ CACHE_FILE = os.path.join(tempfile.gettempdir(), "gaia_answers.json")
30
+
31
+ # ---------- OUTILS ----------
32
+
33
+ def fetch_text(url: str) -> str:
34
+ try:
35
+ r = requests.get(url, headers=HEADERS, timeout=30)
36
+ r.raise_for_status()
37
+ except Exception as e:
38
+ return f"Erreur: {e}"
39
+ soup = BeautifulSoup(r.text, "html.parser")
40
+ for t in soup(["script", "style", "nav", "footer", "sup"]):
41
+ t.decompose()
42
+ for t in soup.find_all(["tr", "p", "li", "h1", "h2", "h3", "h4"]):
43
+ t.append("\n")
44
+ text = re.sub(r"[ \t]+", " ", soup.get_text(" "))
45
+ return re.sub(r"\n\s*\n+", "\n", text)
46
+
47
+
48
+ @tool
49
+ def visit_page(url: str) -> str:
50
+ """Télécharge une page web (Wikipedia inclus) et renvoie le début de son texte.
51
+ Pour une page longue, préfère search_in_page.
52
+ Args:
53
+ url: adresse complète de la page.
54
+ """
55
+ return fetch_text(url)[:12000]
56
+
57
+
58
+ @tool
59
+ def search_in_page(url: str, keyword: str) -> str:
60
+ """Télécharge une page web et renvoie les passages autour d'un mot-clé.
61
+ Args:
62
+ url: adresse complète de la page.
63
+ keyword: mot ou expression à chercher dans la page.
64
+ """
65
+ text = fetch_text(url)
66
+ if text.startswith("Erreur"):
67
+ return text
68
+ low, k = text.lower(), keyword.lower()
69
+ out, start = [], 0
70
+ while len(out) < 6:
71
+ i = low.find(k, start)
72
+ if i == -1:
73
+ break
74
+ out.append(text[max(0, i - 500): i + 1500])
75
+ start = i + 1500
76
+ return "\n-----\n".join(out) if out else f"'{keyword}' introuvable dans la page."
77
+
78
+
79
+ def gemini_transcribe(path: str) -> str:
80
+ model = os.getenv("GEMINI_MODEL", "gemini/gemini-3.5-flash-lite").replace("gemini/", "")
81
+ ext = path.lower().rsplit(".", 1)[-1]
82
+ mime = {"mp3": "audio/mpeg", "wav": "audio/wav", "m4a": "audio/mp4",
83
+ "flac": "audio/flac"}.get(ext, "audio/mpeg")
84
+ with open(path, "rb") as f:
85
+ data = base64.b64encode(f.read()).decode()
86
+ body = {"contents": [{"parts": [
87
+ {"text": "Transcribe this audio word for word. Return only the transcript."},
88
+ {"inline_data": {"mime_type": mime, "data": data}},
89
+ ]}]}
90
+ r = requests.post(
91
+ f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent",
92
+ headers={"x-goog-api-key": os.getenv("GEMINI_API_KEY"),
93
+ "Content-Type": "application/json"},
94
+ json=body, timeout=120,
95
+ )
96
+ r.raise_for_status()
97
+ parts = r.json()["candidates"][0]["content"]["parts"]
98
+ return "".join(p.get("text", "") for p in parts)
99
+
100
+
101
+ @tool
102
+ def read_file(path: str) -> str:
103
+ """Lit un fichier local (txt, csv, xlsx, py, json, mp3/wav) et renvoie son contenu.
104
+ Les fichiers audio sont transcrits en texte.
105
+ Args:
106
+ path: chemin du fichier local.
107
+ """
108
+ p = path.lower()
109
+ try:
110
+ if p.endswith((".xlsx", ".xls")):
111
+ return pd.read_excel(path).to_string()
112
+ if p.endswith(".csv"):
113
+ return pd.read_csv(path).to_string()
114
+ if p.endswith((".mp3", ".wav", ".m4a", ".flac")):
115
+ if os.getenv("GEMINI_API_KEY"):
116
+ return gemini_transcribe(path)
117
+ client = InferenceClient(api_key=os.getenv("HF_TOKEN"))
118
+ return client.automatic_speech_recognition(
119
+ path, model="openai/whisper-large-v3").text
120
+ with open(path, "r", errors="ignore") as f:
121
+ return f.read()[:20000]
122
+ except Exception as e:
123
+ return f"Erreur de lecture: {e}"
124
+
125
+
126
+ # ---------- AGENT ----------
127
+
128
+ SYSTEM_RULES = """Tu es un agent qui répond à des questions du benchmark GAIA.
129
+ Règles de réponse finale (correction en EXACT MATCH):
130
+ - Appelle final_answer avec UNIQUEMENT la réponse, rien d'autre.
131
+ - Pas de phrase, pas de "FINAL ANSWER", pas de point final.
132
+ - Nombre: pas de séparateur de milliers, pas d'unité sauf si demandée.
133
+ - Texte: pas d'article. Respecte à la lettre les consignes de format de la
134
+ question (par exemple "sans abréviation" = écris les mots en entier).
135
+ - Liste: éléments séparés par des virgules, dans l'ordre demandé.
136
+ Méthode:
137
+ - Ne JAMAIS appeler final_answer dans la même étape où tu lis une page ou un
138
+ résultat pour la première fois: affiche d'abord (print), lis, puis réponds à
139
+ l'étape suivante.
140
+ - Ne devine pas. Si l'information n'est pas encore trouvée, cherche autrement.
141
+ - Pour Wikipedia, utilise search_in_page(url, mot_clé). N'invente pas d'URL:
142
+ si une page renvoie 404, fais une recherche web.
143
+ - Si un résultat de recherche contient déjà l'information demandée, utilise-la.
144
+ - Pour compter ou calculer, écris du code Python plutôt que de compter à la main.
145
+ - Réponds toujours avec un court raisonnement puis un bloc de code valide.
146
+ """
147
+
148
+ class RobustLiteLLM(LiteLLMModel):
149
+ """Redemande au modèle quand sa réponse est vide (sans perdre d'étape)."""
150
+ def generate(self, *args, **kwargs):
151
+ msg = None
152
+ for _ in range(4):
153
+ msg = super().generate(*args, **kwargs)
154
+ content = getattr(msg, "content", None)
155
+ if (content and str(content).strip()) or getattr(msg, "tool_calls", None):
156
+ return msg
157
+ time.sleep(1.5)
158
+ return msg
159
 
160
+ def build_agent():
161
+ if os.getenv("GEMINI_API_KEY"):
162
+ model = RobustLiteLLM(
163
+ model_id=os.getenv("GEMINI_MODEL", "gemini/gemini-3.5-flash-lite"),
164
+ api_key=os.getenv("GEMINI_API_KEY"),
165
+ timeout=60,
166
+ num_retries=3,
167
+ reasoning_effort="low",
168
+ )
169
+ else:
170
+ model = InferenceClientModel(token=os.getenv("HF_TOKEN"))
171
+ return CodeAgent(
172
+ tools=[DuckDuckGoSearchTool(), visit_page, search_in_page, read_file],
173
+ model=model,
174
+ additional_authorized_imports=[
175
+ "pandas", "numpy", "re", "json", "math", "datetime",
176
+ "requests", "bs4", "collections", "itertools",
177
+ ],
178
+ max_steps=8,
179
+ instructions=SYSTEM_RULES,
180
+ )
181
+
182
+ def clean_answer(ans) -> str:
183
+ s = str(ans).strip()
184
+ if s in ("", "None"):
185
+ return "unknown"
186
+ s = re.sub(r"(?i)^final answer\s*:\s*", "", s)
187
+ s = s.strip().rstrip(".")
188
+ if "```" in s or len(s) > 200 or s.count("\n") > 3:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  return "unknown"
190
+ return s
191
 
192
+ # ---------- FICHIERS ----------
193
 
194
+ def download_file(task_id: str, file_name: str):
195
+ if not file_name:
196
+ return None
197
+ path = os.path.join(tempfile.gettempdir(), file_name)
 
 
 
 
 
 
 
 
 
198
  try:
199
+ r = requests.get(f"{API_URL}/files/{task_id}", timeout=30)
200
+ print(f"[fichier] {task_id} {file_name} -> {r.status_code}")
201
+ if r.status_code == 200:
202
+ with open(path, "wb") as f:
203
+ f.write(r.content)
204
+ return path
205
+ except Exception as e:
206
+ print(f"[fichier] erreur: {e}")
207
+ try: # plan B: pièce jointe du dataset GAIA (conditions à accepter)
208
+ p = hf_hub_download(
209
+ repo_id="gaia-benchmark/GAIA", repo_type="dataset",
210
+ filename=f"2023/validation/{file_name}",
211
+ token=os.getenv("HF_TOKEN"),
212
+ )
213
+ print("[fichier] plan B OK")
214
+ return p
215
  except Exception as e:
216
+ print(f"[fichier] plan B échoué: {str(e)[:150]}")
217
+ return None
218
+
219
+ # ---------- CACHE (évite de refaire les questions déjà réussies) ----------
220
+
221
+ def load_cache() -> dict:
222
+ try:
223
+ with open(CACHE_FILE) as f:
224
+ return json.load(f)
225
+ except Exception:
226
+ return {}
227
+
228
+ def save_cache(c: dict):
229
+ try:
230
+ with open(CACHE_FILE, "w") as f:
231
+ json.dump(c, f)
232
+ except Exception:
233
+ pass
234
+
235
+ # ---------- QUESTIONS ----------
236
+
237
+ def ask_agent(agent, question, file_path):
238
+ if "youtube.com" in question.lower():
239
+ return "unknown" # l'agent ne peut pas regarder les vidéos
240
+ prompt = question
241
+ images = None
242
+ if file_path:
243
+ if file_path.lower().endswith((".png", ".jpg", ".jpeg")):
244
+ try:
245
+ images = [Image.open(file_path).convert("RGB")]
246
+ prompt += "\n\nUne image est jointe à cette question."
247
+ except Exception:
248
+ pass
249
+ else:
250
+ prompt += f"\n\nUn fichier est fourni: {file_path} (utilise read_file)."
251
+ for attempt in range(3):
252
  try:
253
+ if images:
254
+ return clean_answer(agent.run(prompt, images=images))
255
+ return clean_answer(agent.run(prompt))
256
  except Exception as e:
257
+ print(f"Erreur (essai {attempt+1}): {e}")
258
+ time.sleep(10 * (attempt + 1))
259
+ return "unknown"
260
+
261
+ # ---------- EVALUATION ----------
262
+
263
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
264
+ if not profile:
265
+ return "Connectez-vous d'abord avec Hugging Face.", None
266
+ username = profile.username
267
+ space_id = os.getenv("SPACE_ID")
268
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
269
+
270
  try:
271
+ questions = requests.get(f"{API_URL}/questions", timeout=30).json()
 
 
 
 
 
 
 
 
272
  except Exception as e:
273
+ return f"Erreur récupération questions: {e}", None
 
 
274
 
275
+ agent = build_agent()
276
+ cache = load_cache()
277
+ answers, log = [], []
278
+ for item in questions:
279
+ task_id = item["task_id"]
280
+ q = item["question"]
281
+ file_name = item.get("file_name", "")
282
+
283
+ if cache.get(task_id) not in (None, "", "unknown"):
284
+ ans = cache[task_id]
285
+ print(f"[cache] {task_id}: {ans}")
286
+ else:
287
+ file_path = download_file(task_id, file_name)
288
+ if file_name and not file_path:
289
+ ans = "unknown"
290
+ else:
291
+ ans = ask_agent(agent, q, file_path)
292
+ if ans != "unknown":
293
+ cache[task_id] = ans
294
+ save_cache(cache)
295
+ print(f"[réponse] {task_id}: {ans}")
296
+ answers.append({"task_id": task_id, "submitted_answer": ans})
297
+ log.append({"Task ID": task_id, "Question": q[:100], "Réponse": ans})
298
+ time.sleep(2)
299
+
300
+ payload = {"username": username, "agent_code": agent_code, "answers": answers}
301
+ try:
302
+ res = requests.post(f"{API_URL}/submit", json=payload, timeout=120).json()
303
+ msg = (
304
+ f"Utilisateur: {res.get('username')}\n"
305
+ f"Score: {res.get('score')}% "
306
+ f"({res.get('correct_count')}/{res.get('total_attempted')})\n"
307
+ f"{res.get('message', '')}"
308
+ )
309
+ except Exception as e:
310
+ msg = f"Erreur lors de la soumission: {e}"
311
+ return msg, pd.DataFrame(log)
312
 
313
  with gr.Blocks() as demo:
314
+ gr.Markdown("# Agent GAIA - Unit 4")
315
  gr.LoginButton()
316
  btn = gr.Button("Run Evaluation & Submit All Answers")
317
+ status = gr.Textbox(label="Résultat", lines=5)
318
+ table = gr.DataFrame(label="Réponses")
319
+ btn.click(run_and_submit_all, outputs=[status, table])
320
 
321
  if __name__ == "__main__":
322
+ demo.launch(ssr_mode=False)