Spaces:
Sleeping
Sleeping
Download app.py from ilyassman/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/ilyassman/Final_Assignment_Template/resolve/main/app.py
- Command line
-
hf download hf://spaces/ilyassman/Final_Assignment_Template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ilyassman/Final_Assignment_Template/resolve/main/app.py
11.3 kB
| import spaces | |
| def _gpu_placeholder(): | |
| return "ok" | |
| import os | |
| import re | |
| import json | |
| import time | |
| import base64 | |
| import tempfile | |
| import requests | |
| import pandas as pd | |
| import gradio as gr | |
| from bs4 import BeautifulSoup | |
| from PIL import Image | |
| from huggingface_hub import InferenceClient, hf_hub_download | |
| from 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) | |
| def 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] | |
| def 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 text | |
| low, k = text.lower(), keyword.lower() | |
| out, start = [], 0 | |
| while len(out) < 6: | |
| i = low.find(k, start) | |
| if i == -1: | |
| break | |
| out.append(text[max(0, i - 500): i + 1500]) | |
| start = i + 1500 | |
| return "\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) | |
| def 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").text | |
| with 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 la | |
| question (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 un | |
| ré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 = None | |
| for _ 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 msg | |
| time.sleep(1.5) | |
| return msg | |
| def 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 None | |
| path = 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 path | |
| except 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 p | |
| except 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éos | |
| prompt = question | |
| images = None | |
| if 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: | |
| pass | |
| else: | |
| 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.", None | |
| username = profile.username | |
| space_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}", None | |
| agent = 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] = ans | |
| save_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) |