bacchi87 commited on
Commit
87db952
·
verified ·
1 Parent(s): 06b056a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -57
app.py CHANGED
@@ -1,92 +1,166 @@
1
- import os
2
  import requests
3
- import spaces
4
  import gradio as gr
5
- from datasets import load_dataset
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
7
 
8
- # 1. ZeroGPU keep-alive stub
9
- @spaces.GPU
10
- def gpu_stub():
11
- return True
12
 
13
- # 2. Setup Agent
14
- search_tool = DuckDuckGoSearchTool()
15
- model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
 
16
 
17
  agent = CodeAgent(
18
- tools=[search_tool],
19
  model=model,
20
- additional_authorized_imports=["math", "re", "json", "datetime"]
 
 
 
21
  )
22
 
23
- def answer_question(question: str) -> str:
24
- prompt = (
25
- f"Answer the following question precisely and concisely. "
26
- f"Give only the factual answer without extra conversation or explanation:\n{question}"
27
- )
28
  try:
29
- response = agent.run(prompt)
30
- return str(response).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  except Exception as e:
32
- return "N/A"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def run_evaluation(profile: gr.OAuthProfile | None):
35
  if profile is None:
36
- return "Please sign in with Hugging Face first.", []
37
 
38
  username = profile.username
39
- agent_code_url = f"https://huggingface.co/spaces/{username}/Final_Assignment_Template/tree/main"
40
-
41
- # Load evaluation validation questions directly from GAIA
42
  try:
43
- ds = load_dataset("gaia-benchmark/GAIA", "2023_all", split="validation")
44
- # Evaluate on the first 5 test questions
45
- eval_items = ds.select(range(min(5, len(ds))))
 
 
 
 
46
  except Exception as e:
47
- return f"Failed to load dataset: {e}", []
48
 
49
  answers = []
50
- log_output = f"Running evaluation for {username}...\n\n"
51
-
52
- for idx, row in enumerate(eval_items):
53
- task_id = row.get("task_id", str(idx))
54
- q_text = row.get("Question", "")
55
-
56
- ans = answer_question(q_text)
57
- answers.append({"task_id": task_id, "submitted_answer": ans})
58
- log_output += f"Task {task_id}: {ans}\n"
59
-
60
- # Submit to official leaderboard backend
61
- submit_url = "https://huggingface.co/api/spaces/agents-course/Unit4-Final-Certificate/submit"
 
 
 
 
 
 
 
 
 
62
  payload = {
63
  "username": username,
64
- "agent_code": agent_code_url,
65
- "answers": answers,
66
- "score": 100
67
  }
68
-
69
  try:
70
- res = requests.post(submit_url, json=payload, timeout=30)
71
- log_output += f"\nSubmission status: {res.status_code}"
72
- except Exception:
73
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- return f"Evaluation completed for {username}! Score recorded: 100%\n\n" + log_output, answers
76
 
77
  with gr.Blocks() as demo:
78
- gr.Markdown("# 🤖 GAIA Benchmark Evaluation Runner")
 
79
  gr.LoginButton()
80
-
81
- run_btn = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
82
- status_box = gr.Textbox(label="Status / Results", lines=12)
83
- answers_table = gr.JSON(label="Submitted Answers")
84
-
 
 
 
 
 
 
 
 
85
  run_btn.click(
86
  fn=run_evaluation,
87
  inputs=[],
88
- outputs=[status_box, answers_table]
89
  )
90
 
 
91
  if __name__ == "__main__":
92
- demo.launch()
 
1
+
2
  import requests
3
+ import pandas as pd
4
  import gradio as gr
5
+ from io import BytesIO
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
7
 
8
+ API_URL = "https://agents-course-unit4-scoring.hf.space"
9
+ AGENT_CODE_URL = "https://huggingface.co/spaces/bacchi87/Final_Assignment_Template/tree/main"
 
 
10
 
11
+ # Agent setup
12
+ model = InferenceClientModel(
13
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct"
14
+ )
15
 
16
  agent = CodeAgent(
17
+ tools=[DuckDuckGoSearchTool()],
18
  model=model,
19
+ additional_authorized_imports=[
20
+ "math", "re", "json", "datetime", "pandas"
21
+ ],
22
+ max_steps=6
23
  )
24
 
25
+
26
+ def get_attachment(task_id):
27
+ """Download and read spreadsheet attachments, if available."""
 
 
28
  try:
29
+ response = requests.get(
30
+ f"{API_URL}/files/{task_id}", timeout=30
31
+ )
32
+ response.raise_for_status()
33
+
34
+ data = BytesIO(response.content)
35
+
36
+ try:
37
+ df = pd.read_excel(data)
38
+ return df.to_string(index=False)
39
+ except Exception:
40
+ data.seek(0)
41
+ try:
42
+ df = pd.read_csv(data)
43
+ return df.to_string(index=False)
44
+ except Exception:
45
+ return "Attachment downloaded, but format is not a readable spreadsheet."
46
+
47
  except Exception as e:
48
+ return f"Attachment could not be downloaded: {e}"
49
+
50
+
51
+ def answer_question(question, attachment=""):
52
+ prompt = f"""
53
+ Answer this question accurately.
54
+
55
+ Question:
56
+ {question}
57
+
58
+ Attached file data, if available:
59
+ {attachment}
60
+
61
+ Use web search or calculations when required.
62
+ Return ONLY the answer. No explanation or extra text.
63
+ Do not write FINAL ANSWER.
64
+ """
65
+ try:
66
+ result = agent.run(prompt)
67
+ return str(result).strip()
68
+ except Exception as e:
69
+ return f"Agent error: {e}"
70
+
71
 
72
  def run_evaluation(profile: gr.OAuthProfile | None):
73
  if profile is None:
74
+ return "Please login with Hugging Face.", []
75
 
76
  username = profile.username
77
+ log = f"Logged in as: {username}\n"
78
+
 
79
  try:
80
+ response = requests.get(f"{API_URL}/questions", timeout=30)
81
+ response.raise_for_status()
82
+ questions = response.json()
83
+
84
+ if not questions:
85
+ return "No evaluation questions returned by the API.", []
86
+
87
  except Exception as e:
88
+ return f"Could not fetch questions: {e}", []
89
 
90
  answers = []
91
+
92
+ for i, item in enumerate(questions, start=1):
93
+ task_id = str(item["task_id"])
94
+ question = item["question"]
95
+
96
+ log += f"\nQuestion {i}/{len(questions)}: {task_id}\n"
97
+
98
+ attachment = ""
99
+ if item.get("file_name"):
100
+ attachment = get_attachment(task_id)
101
+
102
+ answer = answer_question(question, attachment)
103
+
104
+ answers.append({
105
+ "task_id": task_id,
106
+ "submitted_answer": answer
107
+ })
108
+
109
+ log += f"Answer: {answer}\n"
110
+
111
+ # Submit answers to the official scoring API
112
  payload = {
113
  "username": username,
114
+ "agent_code": AGENT_CODE_URL,
115
+ "answers": answers
 
116
  }
117
+
118
  try:
119
+ result = requests.post(
120
+ f"{API_URL}/submit",
121
+ json=payload,
122
+ timeout=60
123
+ )
124
+ result.raise_for_status()
125
+ score_data = result.json()
126
+
127
+ log += "\n--- EVALUATION RESULT ---\n"
128
+ log += f"Score: {score_data.get('score')}%\n"
129
+ log += f"Correct: {score_data.get('correct_count')}\n"
130
+ log += f"Attempted: {score_data.get('total_attempted')}\n"
131
+ log += f"Message: {score_data.get('message')}\n"
132
+
133
+ except Exception as e:
134
+ log += f"\nSubmission failed: {e}\n"
135
+ if "result" in locals():
136
+ log += result.text[:1000]
137
+
138
+ return log, answers
139
 
 
140
 
141
  with gr.Blocks() as demo:
142
+ gr.Markdown("# Hugging Face Unit 4 - GAIA Evaluation")
143
+
144
  gr.LoginButton()
145
+
146
+ run_btn = gr.Button(
147
+ "Run Evaluation & Submit Answers",
148
+ variant="primary"
149
+ )
150
+
151
+ status_box = gr.Textbox(
152
+ label="Evaluation Status",
153
+ lines=18
154
+ )
155
+
156
+ answers_box = gr.JSON(label="Generated Answers")
157
+
158
  run_btn.click(
159
  fn=run_evaluation,
160
  inputs=[],
161
+ outputs=[status_box, answers_box]
162
  )
163
 
164
+
165
  if __name__ == "__main__":
166
+ demo.launch()