Ubik80 commited on
Commit
19bb099
·
verified ·
1 Parent(s): 95e45af
Files changed (1) hide show
  1. app.py +63 -14
app.py CHANGED
@@ -1,29 +1,81 @@
1
- ## app.py
2
  import os
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
-
7
- from tools import AnswerTool # Solo AnswerTool
 
 
 
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  class BasicAgent:
13
  def __init__(self):
14
-
15
- self.tool = AnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  def __call__(self, question: str, task_id: str = None) -> str:
18
-
19
- return self.tool.forward(question)
 
 
 
 
20
 
21
 
22
  def run_and_submit_all(username):
23
  if not username:
24
  return "Please enter your Hugging Face username.", None
25
 
26
-
27
  try:
28
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
29
  if resp.status_code == 429:
@@ -33,7 +85,6 @@ def run_and_submit_all(username):
33
  except Exception as e:
34
  return f"Error fetching questions: {e}", None
35
 
36
-
37
  agent = BasicAgent()
38
  results = []
39
  payload = []
@@ -43,7 +94,7 @@ def run_and_submit_all(username):
43
  if not (tid and text):
44
  continue
45
  try:
46
- ans = agent(text)
47
  except Exception as e:
48
  ans = f"ERROR: {e}"
49
  results.append({"Task ID": tid, "Question": text, "Answer": ans})
@@ -52,7 +103,6 @@ def run_and_submit_all(username):
52
  if not payload:
53
  return "Agent returned no answers.", pd.DataFrame(results)
54
 
55
-
56
  submission = {
57
  "username": username,
58
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
@@ -80,12 +130,11 @@ def test_random_question(username):
80
  try:
81
  q = requests.get(f"{DEFAULT_API_URL}/random-question", timeout=15).json()
82
  question = q.get("question", "")
83
- ans = BasicAgent()(question)
84
  return question, ans
85
  except Exception as e:
86
  return f"Error during test: {e}", ""
87
 
88
- # --- Gradio UI ---
89
  with gr.Blocks() as demo:
90
  gr.Markdown("# Basic Agent Evaluation Runner")
91
  gr.Markdown(
@@ -106,7 +155,7 @@ with gr.Blocks() as demo:
106
  question_out = gr.Textbox(label="Random Question", lines=3, interactive=False)
107
  answer_out = gr.Textbox(label="Agent Answer", lines=3, interactive=False)
108
 
109
- run_btn.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_out, table_out])
110
  test_btn.click(fn=test_random_question, inputs=[username_input], outputs=[question_out, answer_out])
111
 
112
  if __name__ == "__main__":
 
1
+ app.py
2
  import os
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
+ from pathlib import Path
7
+ import tempfile
8
+ from smolagents import CodeAgent, OpenAIServerModel
9
+ from smolagents import DuckDuckGoSearchTool, WikipediaSearchTool
10
+ from tools import AnswerTool, SpeechToTextTool, ExcelToTextTool
11
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+
16
+ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
17
+ """
18
+ Try GET /files/{task_id}.
19
+ • On HTTP 200 → save to a temp dir and return local path.
20
+ • On 404 → return None.
21
+ """
22
+ url = f"{base_api_url}/files/{task_id}"
23
+ try:
24
+ resp = requests.get(url, timeout=30)
25
+ if resp.status_code == 404:
26
+ return None
27
+ resp.raise_for_status()
28
+ except requests.exceptions.HTTPError as e:
29
+ raise e
30
+
31
+ cdisp = resp.headers.get("content-disposition", "")
32
+ filename = task_id
33
+ if "filename=" in cdisp:
34
+ import re
35
+ m = re.search(r'filename="([^\"]+)"', cdisp)
36
+ if m:
37
+ filename = m.group(1)
38
+
39
+ tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
40
+ tmp_dir.mkdir(exist_ok=True)
41
+ file_path = tmp_dir / filename
42
+ with open(file_path, "wb") as f:
43
+ f.write(resp.content)
44
+ return str(file_path)
45
+
46
  class BasicAgent:
47
  def __init__(self):
48
+ model = OpenAIServerModel(model_id="gpt-4o")
49
+ tools = [
50
+ SpeechToTextTool(),
51
+ ExcelToTextTool(),
52
+ DuckDuckGoSearchTool(),
53
+ WikipediaSearchTool(),
54
+ AnswerTool(),
55
+ ]
56
+ self.agent = CodeAgent(
57
+ model=model,
58
+ tools=tools,
59
+ add_base_tools=False,
60
+ additional_authorized_imports=["pandas", "openpyxl"],
61
+ max_steps=4,
62
+ verbosity_level=0,
63
+ planning_interval=1,
64
+ )
65
 
66
  def __call__(self, question: str, task_id: str = None) -> str:
67
+ prompt = question
68
+ if task_id:
69
+ file_path = download_file_if_any(DEFAULT_API_URL, task_id)
70
+ if file_path:
71
+ prompt += f"\n\n---\nA file was downloaded for this task and saved locally at:\n{file_path}\n---\n"
72
+ return self.agent.run(prompt)
73
 
74
 
75
  def run_and_submit_all(username):
76
  if not username:
77
  return "Please enter your Hugging Face username.", None
78
 
 
79
  try:
80
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
81
  if resp.status_code == 429:
 
85
  except Exception as e:
86
  return f"Error fetching questions: {e}", None
87
 
 
88
  agent = BasicAgent()
89
  results = []
90
  payload = []
 
94
  if not (tid and text):
95
  continue
96
  try:
97
+ ans = agent(text, task_id=tid)
98
  except Exception as e:
99
  ans = f"ERROR: {e}"
100
  results.append({"Task ID": tid, "Question": text, "Answer": ans})
 
103
  if not payload:
104
  return "Agent returned no answers.", pd.DataFrame(results)
105
 
 
106
  submission = {
107
  "username": username,
108
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
 
130
  try:
131
  q = requests.get(f"{DEFAULT_API_URL}/random-question", timeout=15).json()
132
  question = q.get("question", "")
133
+ ans = BasicAgent()(question, task_id=q.get("task_id"))
134
  return question, ans
135
  except Exception as e:
136
  return f"Error during test: {e}", ""
137
 
 
138
  with gr.Blocks() as demo:
139
  gr.Markdown("# Basic Agent Evaluation Runner")
140
  gr.Markdown(
 
155
  question_out = gr.Textbox(label="Random Question", lines=3, interactive=False)
156
  answer_out = gr.Textbox(label="Agent Answer", lines=3, interactive=False)
157
 
158
+ run_btn.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_out, table_out])
159
  test_btn.click(fn=test_random_question, inputs=[username_input], outputs=[question_out, answer_out])
160
 
161
  if __name__ == "__main__":