polvallverdu commited on
Commit
bef69af
·
verified ·
1 Parent(s): 3ebbedf

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +443 -0
app.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import re
4
+ import base64
5
+ import json
6
+ import subprocess
7
+ import tempfile
8
+ import requests
9
+ import gradio as gr
10
+ import pandas as pd
11
+ from openrouter import OpenRouter
12
+
13
+ # --- Constants ---
14
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
+ MAIN_MODEL = "anthropic/claude-opus-4-8"
16
+ AUDIO_MODEL = "google/gemini-2.5-flash"
17
+
18
+ SYSTEM_PROMPT = """You are a precise research assistant answering questions for a benchmark evaluation.
19
+
20
+ CRITICAL RULES:
21
+ - Return ONLY the final answer, nothing else
22
+ - No explanations, no "the answer is", no "FINAL ANSWER:", no preamble
23
+ - For numbers: give exact digits only (e.g. "42" not "42 items")
24
+ - For names: exact spelling, exact capitalization
25
+ - For lists: comma-separated on one line unless asked otherwise
26
+ - For yes/no: just "yes" or "no"
27
+ - Answer exactly what is asked, nothing more"""
28
+
29
+ # --- Tool implementations ---
30
+
31
+ def web_search_fn(query: str) -> str:
32
+ try:
33
+ from duckduckgo_search import DDGS
34
+ results = []
35
+ with DDGS() as ddgs:
36
+ for r in ddgs.text(query, max_results=6):
37
+ results.append(f"Title: {r['title']}\nURL: {r['href']}\nSnippet: {r['body']}")
38
+ return "\n\n".join(results) if results else "No results found"
39
+ except Exception as e:
40
+ return f"Search error: {e}"
41
+
42
+ def web_fetch_fn(url: str) -> str:
43
+ try:
44
+ resp = requests.get(url, timeout=15, headers={"User-Agent": "Mozilla/5.0 (compatible)"})
45
+ text = resp.text
46
+ text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL | re.IGNORECASE)
47
+ text = re.sub(r'<style[^>]*>.*?</style>', '', text, flags=re.DOTALL | re.IGNORECASE)
48
+ text = re.sub(r'<[^>]+>', ' ', text)
49
+ text = re.sub(r'\s+', ' ', text).strip()
50
+ return text[:6000]
51
+ except Exception as e:
52
+ return f"Fetch error: {e}"
53
+
54
+ TOOLS = [
55
+ {
56
+ "type": "function",
57
+ "function": {
58
+ "name": "web_search",
59
+ "description": "Search the web for current information, facts, statistics, or recent events.",
60
+ "parameters": {
61
+ "type": "object",
62
+ "properties": {
63
+ "query": {"type": "string", "description": "Search query"}
64
+ },
65
+ "required": ["query"]
66
+ }
67
+ }
68
+ },
69
+ {
70
+ "type": "function",
71
+ "function": {
72
+ "name": "web_fetch",
73
+ "description": "Fetch and read the full content of a specific URL (Wikipedia articles, web pages, etc.).",
74
+ "parameters": {
75
+ "type": "object",
76
+ "properties": {
77
+ "url": {"type": "string", "description": "Full URL to fetch"}
78
+ },
79
+ "required": ["url"]
80
+ }
81
+ }
82
+ }
83
+ ]
84
+
85
+ TOOL_FNS = {
86
+ "web_search": lambda query: web_search_fn(query),
87
+ "web_fetch": lambda url: web_fetch_fn(url),
88
+ }
89
+
90
+
91
+ class BasicAgent:
92
+ def __init__(self):
93
+ self.client = OpenRouter(api_key=os.environ.get("OPENROUTER_API_KEY"))
94
+ self.api_url = DEFAULT_API_URL
95
+ print("BasicAgent initialized.")
96
+
97
+ def _download_file(self, task_id):
98
+ try:
99
+ url = f"{self.api_url}/files/{task_id}"
100
+ resp = requests.get(url, timeout=30)
101
+ if resp.status_code == 200:
102
+ content_type = resp.headers.get("Content-Type", "")
103
+ disposition = resp.headers.get("Content-Disposition", "")
104
+ filename = ""
105
+ if "filename=" in disposition:
106
+ filename = disposition.split("filename=")[-1].strip('" ')
107
+ return resp.content, content_type, filename
108
+ except Exception as e:
109
+ print(f"File download error for {task_id}: {e}")
110
+ return None, None, None
111
+
112
+ def _transcribe_audio(self, audio_bytes):
113
+ try:
114
+ b64 = base64.standard_b64encode(audio_bytes).decode()
115
+ response = self.client.chat.send(
116
+ model=AUDIO_MODEL,
117
+ messages=[
118
+ {
119
+ "role": "user",
120
+ "content": [
121
+ {
122
+ "type": "text",
123
+ "text": "Transcribe the following audio exactly as spoken, word for word. Return only the transcript text, nothing else."
124
+ },
125
+ {
126
+ "type": "input_audio",
127
+ "input_audio": {"data": b64, "format": "mp3"}
128
+ }
129
+ ]
130
+ }
131
+ ]
132
+ )
133
+ return response.choices[0].message.content or ""
134
+ except Exception as e:
135
+ print(f"Audio transcription failed: {e}")
136
+ return "[Audio transcription unavailable]"
137
+
138
+ def _execute_python(self, code_bytes):
139
+ with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="wb") as f:
140
+ f.write(code_bytes)
141
+ tmp_path = f.name
142
+ try:
143
+ result = subprocess.run(
144
+ ["python3", tmp_path],
145
+ capture_output=True, text=True, timeout=30
146
+ )
147
+ os.unlink(tmp_path)
148
+ return (result.stdout + result.stderr).strip()[:5000]
149
+ except subprocess.TimeoutExpired:
150
+ try:
151
+ os.unlink(tmp_path)
152
+ except Exception:
153
+ pass
154
+ return "[Execution timed out]"
155
+ except Exception as e:
156
+ return f"[Execution failed: {e}]"
157
+
158
+ def _parse_xlsx(self, xlsx_bytes):
159
+ try:
160
+ df = pd.read_excel(io.BytesIO(xlsx_bytes))
161
+ return df.to_string(index=True)[:10000]
162
+ except Exception as e:
163
+ return f"[XLSX parsing failed: {e}]"
164
+
165
+ def _run_agent_loop(self, user_content):
166
+ messages = [
167
+ {"role": "system", "content": SYSTEM_PROMPT},
168
+ {"role": "user", "content": user_content}
169
+ ]
170
+
171
+ for _ in range(12): # max tool-call iterations
172
+ response = self.client.chat.send(
173
+ model=MAIN_MODEL,
174
+ messages=messages,
175
+ tools=TOOLS,
176
+ tool_choice="auto"
177
+ )
178
+ choice = response.choices[0]
179
+ msg = choice.message
180
+ finish_reason = choice.finish_reason
181
+
182
+ tool_calls = getattr(msg, "tool_calls", None)
183
+ if finish_reason == "tool_calls" or tool_calls:
184
+ # Append assistant message with tool_calls
185
+ assistant_msg = {"role": "assistant", "content": msg.content}
186
+ if tool_calls:
187
+ assistant_msg["tool_calls"] = [
188
+ {
189
+ "id": tc.id,
190
+ "type": "function",
191
+ "function": {
192
+ "name": tc.function.name,
193
+ "arguments": tc.function.arguments
194
+ }
195
+ }
196
+ for tc in tool_calls
197
+ ]
198
+ messages.append(assistant_msg)
199
+
200
+ for tc in (tool_calls or []):
201
+ fn_name = tc.function.name
202
+ try:
203
+ fn_args = json.loads(tc.function.arguments)
204
+ except Exception:
205
+ fn_args = {}
206
+ fn = TOOL_FNS.get(fn_name)
207
+ result = fn(**fn_args) if fn else f"Unknown tool: {fn_name}"
208
+ messages.append({
209
+ "role": "tool",
210
+ "tool_call_id": tc.id,
211
+ "content": str(result)
212
+ })
213
+ else:
214
+ return (msg.content or "").strip()
215
+
216
+ return ""
217
+
218
+ def __call__(self, question: str, task_id: str = None) -> str:
219
+ print(f"Agent received question: {question[:80]}...")
220
+
221
+ user_content = []
222
+ extra_context = ""
223
+
224
+ if task_id:
225
+ file_bytes, content_type, filename = self._download_file(task_id)
226
+ if file_bytes:
227
+ ct = (content_type or "").lower()
228
+ fn = (filename or "").lower()
229
+
230
+ if "image" in ct or fn.endswith((".png", ".jpg", ".jpeg", ".gif", ".webp")):
231
+ b64 = base64.standard_b64encode(file_bytes).decode()
232
+ mime = "image/png" if ("png" in ct or fn.endswith(".png")) else "image/jpeg"
233
+ user_content.append({
234
+ "type": "image_url",
235
+ "image_url": {"url": f"data:{mime};base64,{b64}"}
236
+ })
237
+
238
+ elif "audio" in ct or "mpeg" in ct or fn.endswith((".mp3", ".wav", ".m4a")):
239
+ transcript = self._transcribe_audio(file_bytes)
240
+ extra_context = f"\n[Audio transcript:\n{transcript}]"
241
+
242
+ elif fn.endswith(".py") or "python" in ct or "text/x-python" in ct:
243
+ output = self._execute_python(file_bytes)
244
+ extra_context = f"\n[Python script output:\n{output}]"
245
+
246
+ elif ("spreadsheet" in ct or "excel" in ct or "openxmlformats" in ct
247
+ or fn.endswith((".xlsx", ".xls"))):
248
+ table = self._parse_xlsx(file_bytes)
249
+ extra_context = f"\n[Spreadsheet data:\n{table}]"
250
+
251
+ else:
252
+ try:
253
+ text = file_bytes.decode("utf-8")
254
+ extra_context = f"\n[File content:\n{text[:3000]}]"
255
+ except Exception:
256
+ extra_context = f"\n[Binary file, {len(file_bytes)} bytes — unable to parse]"
257
+
258
+ user_content.append({"type": "text", "text": question + extra_context})
259
+
260
+ try:
261
+ answer = self._run_agent_loop(user_content)
262
+ print(f"Agent answer: {answer[:120]}")
263
+ return answer
264
+ except Exception as e:
265
+ print(f"Agent error: {e}")
266
+ return f"Error: {e}"
267
+
268
+
269
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
270
+ """
271
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
272
+ and displays the results.
273
+ """
274
+ space_id = os.getenv("SPACE_ID")
275
+
276
+ if profile:
277
+ username = f"{profile.username}"
278
+ print(f"User logged in: {username}")
279
+ else:
280
+ print("User not logged in.")
281
+ return "Please Login to Hugging Face with the button.", None
282
+
283
+ if username != "polvallverdu":
284
+ return "This space is restricted to its owner.", None
285
+
286
+ api_url = DEFAULT_API_URL
287
+ questions_url = f"{api_url}/questions"
288
+ submit_url = f"{api_url}/submit"
289
+
290
+ # 1. Instantiate Agent
291
+ try:
292
+ agent = BasicAgent()
293
+ except Exception as e:
294
+ print(f"Error instantiating agent: {e}")
295
+ return f"Error initializing agent: {e}", None
296
+
297
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
298
+ print(agent_code)
299
+
300
+ # 2. Fetch Questions
301
+ print(f"Fetching questions from: {questions_url}")
302
+ try:
303
+ response = requests.get(questions_url, timeout=15)
304
+ response.raise_for_status()
305
+ questions_data = response.json()
306
+ if not questions_data:
307
+ print("Fetched questions list is empty.")
308
+ return "Fetched questions list is empty or invalid format.", None
309
+ print(f"Fetched {len(questions_data)} questions.")
310
+ except requests.exceptions.RequestException as e:
311
+ print(f"Error fetching questions: {e}")
312
+ return f"Error fetching questions: {e}", None
313
+ except requests.exceptions.JSONDecodeError as e:
314
+ print(f"Error decoding JSON response from questions endpoint: {e}")
315
+ print(f"Response text: {response.text[:500]}")
316
+ return f"Error decoding server response for questions: {e}", None
317
+ except Exception as e:
318
+ print(f"An unexpected error occurred fetching questions: {e}")
319
+ return f"An unexpected error occurred fetching questions: {e}", None
320
+
321
+ # 3. Run your Agent
322
+ results_log = []
323
+ answers_payload = []
324
+ print(f"Running agent on {len(questions_data)} questions...")
325
+ for item in questions_data:
326
+ task_id = item.get("task_id")
327
+ question_text = item.get("question")
328
+ if not task_id or question_text is None:
329
+ print(f"Skipping item with missing task_id or question: {item}")
330
+ continue
331
+ try:
332
+ submitted_answer = agent(question_text, task_id=task_id)
333
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
334
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
335
+ except Exception as e:
336
+ print(f"Error running agent on task {task_id}: {e}")
337
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
338
+
339
+ if not answers_payload:
340
+ print("Agent did not produce any answers to submit.")
341
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
342
+
343
+ # 4. Prepare Submission
344
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
345
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
346
+ print(status_update)
347
+
348
+ # 5. Submit
349
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
350
+ try:
351
+ response = requests.post(submit_url, json=submission_data, timeout=60)
352
+ response.raise_for_status()
353
+ result_data = response.json()
354
+ final_status = (
355
+ f"Submission Successful!\n"
356
+ f"User: {result_data.get('username')}\n"
357
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
358
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
359
+ f"Message: {result_data.get('message', 'No message received.')}"
360
+ )
361
+ print("Submission successful.")
362
+ results_df = pd.DataFrame(results_log)
363
+ return final_status, results_df
364
+ except requests.exceptions.HTTPError as e:
365
+ error_detail = f"Server responded with status {e.response.status_code}."
366
+ try:
367
+ error_json = e.response.json()
368
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
369
+ except requests.exceptions.JSONDecodeError:
370
+ error_detail += f" Response: {e.response.text[:500]}"
371
+ status_message = f"Submission Failed: {error_detail}"
372
+ print(status_message)
373
+ results_df = pd.DataFrame(results_log)
374
+ return status_message, results_df
375
+ except requests.exceptions.Timeout:
376
+ status_message = "Submission Failed: The request timed out."
377
+ print(status_message)
378
+ results_df = pd.DataFrame(results_log)
379
+ return status_message, results_df
380
+ except requests.exceptions.RequestException as e:
381
+ status_message = f"Submission Failed: Network error - {e}"
382
+ print(status_message)
383
+ results_df = pd.DataFrame(results_log)
384
+ return status_message, results_df
385
+ except Exception as e:
386
+ status_message = f"An unexpected error occurred during submission: {e}"
387
+ print(status_message)
388
+ results_df = pd.DataFrame(results_log)
389
+ return status_message, results_df
390
+
391
+
392
+ # --- Build Gradio Interface using Blocks ---
393
+ with gr.Blocks() as demo:
394
+ gr.Markdown("# Basic Agent Evaluation Runner")
395
+ gr.Markdown(
396
+ """
397
+ **Instructions:**
398
+
399
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
400
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
401
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
402
+
403
+ ---
404
+ **Disclaimers:**
405
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
406
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
407
+ """
408
+ )
409
+
410
+ gr.LoginButton()
411
+
412
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
413
+
414
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
415
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
416
+
417
+ run_button.click(
418
+ fn=run_and_submit_all,
419
+ outputs=[status_output, results_table]
420
+ )
421
+
422
+ if __name__ == "__main__":
423
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
424
+ space_host_startup = os.getenv("SPACE_HOST")
425
+ space_id_startup = os.getenv("SPACE_ID")
426
+
427
+ if space_host_startup:
428
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
429
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
430
+ else:
431
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
432
+
433
+ if space_id_startup:
434
+ print(f"✅ SPACE_ID found: {space_id_startup}")
435
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
436
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
437
+ else:
438
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
439
+
440
+ print("-"*(60 + len(" App Starting ")) + "\n")
441
+
442
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
443
+ demo.launch(debug=True, share=False)