Ubik80 commited on
Commit
3ad674f
·
verified ·
1 Parent(s): 9b3df85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -50
app.py CHANGED
@@ -1,14 +1,10 @@
1
- # app.py
2
  import os
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
- import tempfile
7
- from pathlib import Path
8
-
9
- from tools import AnswerTool, SpeechToTextTool, ExcelToTextTool
10
  from smolagents import CodeAgent, OpenAIServerModel
11
  from smolagents import DuckDuckGoSearchTool, WikipediaSearchTool
 
12
 
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -19,7 +15,6 @@ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
19
  Try GET /files/{task_id}.
20
  • On HTTP 200 → save to a temp dir and return local path.
21
  • On 404 → return None.
22
- • On other errors → raise so caller can log / handle.
23
  """
24
  url = f"{base_api_url}/files/{task_id}"
25
  try:
@@ -30,16 +25,14 @@ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
30
  except requests.exceptions.HTTPError as e:
31
  raise e
32
 
33
- # Determine filename from headers or default to task_id
34
- cd = resp.headers.get("content-disposition", "")
35
  filename = task_id
36
- if "filename=" in cd:
37
  import re
38
- m = re.search(r'filename="([^"]+)"', cd)
39
  if m:
40
  filename = m.group(1)
41
 
42
- # Save to temp dir
43
  tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
44
  tmp_dir.mkdir(exist_ok=True)
45
  file_path = tmp_dir / filename
@@ -47,41 +40,32 @@ def download_file_if_any(base_api_url: str, task_id: str) -> str | None:
47
  f.write(resp.content)
48
  return str(file_path)
49
 
50
-
51
  class BasicAgent:
52
  def __init__(self):
53
- # Initialize CodeAgent with GPT-4o, file/audio/excel, web and wiki tools, plus final answer
54
  model = OpenAIServerModel(model_id="gpt-4o")
55
- answer_tool = AnswerTool()
56
- speech_tool = SpeechToTextTool()
57
- excel_tool = ExcelToTextTool()
58
- web_tool = DuckDuckGoSearchTool()
59
- wiki_tool = WikipediaSearchTool()
60
-
 
61
  self.agent = CodeAgent(
62
  model=model,
63
- tools=[speech_tool, excel_tool, wiki_tool, web_tool, answer_tool],
64
  add_base_tools=False,
65
  additional_authorized_imports=["pandas", "openpyxl"],
66
  max_steps=4,
 
67
  planning_interval=1,
68
- verbosity_level=1
69
  )
70
 
71
- def __call__(self, task_id: str, question: str) -> str:
72
- # Pre-fetch any file for this task
73
- file_path = None
74
- try:
75
  file_path = download_file_if_any(DEFAULT_API_URL, task_id)
76
- except Exception:
77
- pass
78
-
79
- # Build prompt including file context if any
80
- if file_path:
81
- prompt = f"{question}\n\n---\nA file for this task was downloaded and saved at: {file_path}\n---"
82
- else:
83
- prompt = question
84
-
85
  return self.agent.run(prompt)
86
 
87
 
@@ -89,7 +73,6 @@ def run_and_submit_all(username):
89
  if not username:
90
  return "Please enter your Hugging Face username.", None
91
 
92
- # 1. Fetch questions
93
  try:
94
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
95
  if resp.status_code == 429:
@@ -99,19 +82,16 @@ def run_and_submit_all(username):
99
  except Exception as e:
100
  return f"Error fetching questions: {e}", None
101
 
102
- # 2. Instantiate agent
103
  agent = BasicAgent()
104
  results = []
105
  payload = []
106
-
107
- # 3. Run agent on all questions
108
  for q in questions:
109
  tid = q.get("task_id")
110
  text = q.get("question")
111
  if not (tid and text):
112
  continue
113
  try:
114
- ans = agent(tid, text)
115
  except Exception as e:
116
  ans = f"ERROR: {e}"
117
  results.append({"Task ID": tid, "Question": text, "Answer": ans})
@@ -120,11 +100,10 @@ def run_and_submit_all(username):
120
  if not payload:
121
  return "Agent returned no answers.", pd.DataFrame(results)
122
 
123
- # 4. Submit answers
124
  submission = {
125
  "username": username,
126
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
127
- "answers": payload
128
  }
129
  try:
130
  sub_resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
@@ -148,12 +127,11 @@ def test_random_question(username):
148
  try:
149
  q = requests.get(f"{DEFAULT_API_URL}/random-question", timeout=15).json()
150
  question = q.get("question", "")
151
- ans = BasicAgent()(q.get('task_id'), question)
152
  return question, ans
153
  except Exception as e:
154
  return f"Error during test: {e}", ""
155
 
156
- # --- Gradio UI ---
157
  with gr.Blocks() as demo:
158
  gr.Markdown("# Basic Agent Evaluation Runner")
159
  gr.Markdown(
@@ -169,15 +147,13 @@ with gr.Blocks() as demo:
169
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
170
  test_btn = gr.Button("Test Random Question")
171
 
172
- status_out = gr.Textbox(label="Status / Result", lines=5, interactive=False)
173
- table_out = gr.DataFrame(label="Full Results Table", wrap=True)
174
  question_out = gr.Textbox(label="Random Question", lines=3, interactive=False)
175
- answer_out = gr.Textbox(label="Agent Answer", lines=3, interactive=False)
176
 
177
- run_btn.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_out, table_out])
178
  test_btn.click(fn=test_random_question, inputs=[username_input], outputs=[question_out, answer_out])
179
 
180
  if __name__ == "__main__":
181
- demo.launch(debug=True, share=False)
182
-
183
-
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
 
 
 
5
  from smolagents import CodeAgent, OpenAIServerModel
6
  from smolagents import DuckDuckGoSearchTool, WikipediaSearchTool
7
+ from tools import AnswerTool, SpeechToTextTool, ExcelToTextTool
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
15
  Try GET /files/{task_id}.
16
  • On HTTP 200 → save to a temp dir and return local path.
17
  • On 404 → return None.
 
18
  """
19
  url = f"{base_api_url}/files/{task_id}"
20
  try:
 
25
  except requests.exceptions.HTTPError as e:
26
  raise e
27
 
28
+ cdisp = resp.headers.get("content-disposition", "")
 
29
  filename = task_id
30
+ if "filename=" in cdisp:
31
  import re
32
+ m = re.search(r'filename="([^\"]+)"', cdisp)
33
  if m:
34
  filename = m.group(1)
35
 
 
36
  tmp_dir = Path(tempfile.gettempdir()) / "gaia_files"
37
  tmp_dir.mkdir(exist_ok=True)
38
  file_path = tmp_dir / filename
 
40
  f.write(resp.content)
41
  return str(file_path)
42
 
 
43
  class BasicAgent:
44
  def __init__(self):
 
45
  model = OpenAIServerModel(model_id="gpt-4o")
46
+ tools = [
47
+ SpeechToTextTool(),
48
+ ExcelToTextTool(),
49
+ DuckDuckGoSearchTool(),
50
+ WikipediaSearchTool(),
51
+ AnswerTool(),
52
+ ]
53
  self.agent = CodeAgent(
54
  model=model,
55
+ tools=tools,
56
  add_base_tools=False,
57
  additional_authorized_imports=["pandas", "openpyxl"],
58
  max_steps=4,
59
+ verbosity_level=0,
60
  planning_interval=1,
 
61
  )
62
 
63
+ def __call__(self, question: str, task_id: str = None) -> str:
64
+ prompt = question
65
+ if task_id:
 
66
  file_path = download_file_if_any(DEFAULT_API_URL, task_id)
67
+ if file_path:
68
+ prompt += f"\n\n---\nA file was downloaded for this task and saved locally at:\n{file_path}\n---\n"
 
 
 
 
 
 
 
69
  return self.agent.run(prompt)
70
 
71
 
 
73
  if not username:
74
  return "Please enter your Hugging Face username.", None
75
 
 
76
  try:
77
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
78
  if resp.status_code == 429:
 
82
  except Exception as e:
83
  return f"Error fetching questions: {e}", None
84
 
 
85
  agent = BasicAgent()
86
  results = []
87
  payload = []
 
 
88
  for q in questions:
89
  tid = q.get("task_id")
90
  text = q.get("question")
91
  if not (tid and text):
92
  continue
93
  try:
94
+ ans = agent(text, task_id=tid)
95
  except Exception as e:
96
  ans = f"ERROR: {e}"
97
  results.append({"Task ID": tid, "Question": text, "Answer": ans})
 
100
  if not payload:
101
  return "Agent returned no answers.", pd.DataFrame(results)
102
 
 
103
  submission = {
104
  "username": username,
105
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
106
+ "answers": payload,
107
  }
108
  try:
109
  sub_resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
 
127
  try:
128
  q = requests.get(f"{DEFAULT_API_URL}/random-question", timeout=15).json()
129
  question = q.get("question", "")
130
+ ans = BasicAgent()(question, task_id=q.get("task_id"))
131
  return question, ans
132
  except Exception as e:
133
  return f"Error during test: {e}", ""
134
 
 
135
  with gr.Blocks() as demo:
136
  gr.Markdown("# Basic Agent Evaluation Runner")
137
  gr.Markdown(
 
147
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
148
  test_btn = gr.Button("Test Random Question")
149
 
150
+ status_out = gr.Textbox(label="Status / Result", lines=5, interactive=False)
151
+ table_out = gr.DataFrame(label="Full Results Table", wrap=True)
152
  question_out = gr.Textbox(label="Random Question", lines=3, interactive=False)
153
+ answer_out = gr.Textbox(label="Agent Answer", lines=3, interactive=False)
154
 
155
+ run_btn.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_out, table_out])
156
  test_btn.click(fn=test_random_question, inputs=[username_input], outputs=[question_out, answer_out])
157
 
158
  if __name__ == "__main__":
159
+ demo.launch(debug=True, share=False)