Ubik80 commited on
Commit
5b86e77
·
verified ·
1 Parent(s): d39820b

Update app.py

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