Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,111 +3,320 @@ import spaces
|
|
| 3 |
@spaces.GPU
|
| 4 |
def _gpu_placeholder():
|
| 5 |
return "ok"
|
|
|
|
| 6 |
import os
|
| 7 |
-
import
|
| 8 |
-
import requests
|
| 9 |
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
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
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 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 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
except Exception as e:
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
try:
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
try:
|
| 89 |
-
|
| 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 |
-
|
| 100 |
-
import pandas as pd
|
| 101 |
-
return final_status, pd.DataFrame(results_log)
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
with gr.Blocks() as demo:
|
| 105 |
-
gr.Markdown("#
|
| 106 |
gr.LoginButton()
|
| 107 |
btn = gr.Button("Run Evaluation & Submit All Answers")
|
| 108 |
-
status = gr.Textbox(label="
|
| 109 |
-
table = gr.DataFrame(label="
|
| 110 |
-
btn.click(
|
| 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)
|