File size: 11,331 Bytes
ba03248
 
 
 
 
4de8fbd
10e9b7d
4de8fbd
98427fa
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98427fa
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98427fa
4de8fbd
98427fa
4de8fbd
98427fa
4de8fbd
 
 
 
eccf8e4
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccf5af0
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31243f4
4de8fbd
 
 
31243f4
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
e80aab9
4de8fbd
ff4855a
4de8fbd
98427fa
4de8fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff4855a
 
4de8fbd
ff4855a
 
4de8fbd
 
 
ff4855a
 
4de8fbd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import spaces

@spaces.GPU
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)


@tool
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]


@tool
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)


@tool
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)