Upload app.py
#42
by
silvada
- opened
app.py
CHANGED
@@ -1,196 +1,219 @@
|
|
1 |
-
import os
|
2 |
-
import gradio as gr
|
3 |
-
import requests
|
4 |
-
import inspect
|
5 |
-
import pandas as pd
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
def
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
print(f"
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
demo.launch(debug=True, share=False)
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import inspect
|
5 |
+
import pandas as pd
|
6 |
+
from smolagents import HfApiModel,CodeAgent,PythonInterpreterTool, UserInputTool, FinalAnswerTool, DuckDuckGoSearchTool, WikipediaSearchTool, WolframAlphaTool, VisitWebpageTool, SpeechToTextTool
|
7 |
+
|
8 |
+
|
9 |
+
# (Keep Constants as is)
|
10 |
+
# --- Constants ---
|
11 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
+
|
13 |
+
# --- Basic Agent Definition ---
|
14 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
15 |
+
class BasicAgent:
|
16 |
+
def __init__(self):
|
17 |
+
|
18 |
+
model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together")
|
19 |
+
self.agent = CodeAgent(
|
20 |
+
model=model,
|
21 |
+
tools=[
|
22 |
+
PythonInterpreterTool(),
|
23 |
+
UserInputTool(),
|
24 |
+
FinalAnswerTool(),
|
25 |
+
DuckDuckGoSearchTool(),
|
26 |
+
WikipediaSearchTool(),
|
27 |
+
WolframAlphaTool(),
|
28 |
+
VisitWebpageTool(),
|
29 |
+
SpeechToTextTool()
|
30 |
+
],
|
31 |
+
max_tokens=2000,
|
32 |
+
temperature=0.5,
|
33 |
+
top_p=0.9,
|
34 |
+
top_k=50,
|
35 |
+
frequency_penalty=0.5,
|
36 |
+
presence_penalty=0.5,
|
37 |
+
)
|
38 |
+
def __call__(self, question: str) -> str:
|
39 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
40 |
+
fixed_answer = self.agent.run(question)
|
41 |
+
# Here you can add any post-processing to the answer if needed
|
42 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
43 |
+
return fixed_answer
|
44 |
+
|
45 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
46 |
+
"""
|
47 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
48 |
+
and displays the results.
|
49 |
+
"""
|
50 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
51 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
52 |
+
|
53 |
+
if profile:
|
54 |
+
username= f"{profile.username}"
|
55 |
+
print(f"User logged in: {username}")
|
56 |
+
else:
|
57 |
+
print("User not logged in.")
|
58 |
+
return "Please Login to Hugging Face with the button.", None
|
59 |
+
|
60 |
+
api_url = DEFAULT_API_URL
|
61 |
+
questions_url = f"{api_url}/questions"
|
62 |
+
submit_url = f"{api_url}/submit"
|
63 |
+
|
64 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
65 |
+
try:
|
66 |
+
agent = BasicAgent()
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error instantiating agent: {e}")
|
69 |
+
return f"Error initializing agent: {e}", None
|
70 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
71 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
72 |
+
print(agent_code)
|
73 |
+
|
74 |
+
# 2. Fetch Questions
|
75 |
+
print(f"Fetching questions from: {questions_url}")
|
76 |
+
try:
|
77 |
+
response = requests.get(questions_url, timeout=15)
|
78 |
+
response.raise_for_status()
|
79 |
+
questions_data = response.json()
|
80 |
+
if not questions_data:
|
81 |
+
print("Fetched questions list is empty.")
|
82 |
+
return "Fetched questions list is empty or invalid format.", None
|
83 |
+
print(f"Fetched {len(questions_data)} questions.")
|
84 |
+
except requests.exceptions.RequestException as e:
|
85 |
+
print(f"Error fetching questions: {e}")
|
86 |
+
return f"Error fetching questions: {e}", None
|
87 |
+
except requests.exceptions.JSONDecodeError as e:
|
88 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
89 |
+
print(f"Response text: {response.text[:500]}")
|
90 |
+
return f"Error decoding server response for questions: {e}", None
|
91 |
+
except Exception as e:
|
92 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
93 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
94 |
+
|
95 |
+
# 3. Run your Agent
|
96 |
+
results_log = []
|
97 |
+
answers_payload = []
|
98 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
99 |
+
for item in questions_data:
|
100 |
+
task_id = item.get("task_id")
|
101 |
+
question_text = item.get("question")
|
102 |
+
if not task_id or question_text is None:
|
103 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
104 |
+
continue
|
105 |
+
try:
|
106 |
+
submitted_answer = agent(question_text)
|
107 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
108 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
109 |
+
except Exception as e:
|
110 |
+
print(f"Error running agent on task {task_id}: {e}")
|
111 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
112 |
+
|
113 |
+
if not answers_payload:
|
114 |
+
print("Agent did not produce any answers to submit.")
|
115 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
116 |
+
|
117 |
+
# 4. Prepare Submission
|
118 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
119 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
120 |
+
print(status_update)
|
121 |
+
|
122 |
+
# 5. Submit
|
123 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
124 |
+
try:
|
125 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
126 |
+
response.raise_for_status()
|
127 |
+
result_data = response.json()
|
128 |
+
final_status = (
|
129 |
+
f"Submission Successful!\n"
|
130 |
+
f"User: {result_data.get('username')}\n"
|
131 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
132 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
133 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
134 |
+
)
|
135 |
+
print("Submission successful.")
|
136 |
+
results_df = pd.DataFrame(results_log)
|
137 |
+
return final_status, results_df
|
138 |
+
except requests.exceptions.HTTPError as e:
|
139 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
140 |
+
try:
|
141 |
+
error_json = e.response.json()
|
142 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
143 |
+
except requests.exceptions.JSONDecodeError:
|
144 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
145 |
+
status_message = f"Submission Failed: {error_detail}"
|
146 |
+
print(status_message)
|
147 |
+
results_df = pd.DataFrame(results_log)
|
148 |
+
return status_message, results_df
|
149 |
+
except requests.exceptions.Timeout:
|
150 |
+
status_message = "Submission Failed: The request timed out."
|
151 |
+
print(status_message)
|
152 |
+
results_df = pd.DataFrame(results_log)
|
153 |
+
return status_message, results_df
|
154 |
+
except requests.exceptions.RequestException as e:
|
155 |
+
status_message = f"Submission Failed: Network error - {e}"
|
156 |
+
print(status_message)
|
157 |
+
results_df = pd.DataFrame(results_log)
|
158 |
+
return status_message, results_df
|
159 |
+
except Exception as e:
|
160 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
161 |
+
print(status_message)
|
162 |
+
results_df = pd.DataFrame(results_log)
|
163 |
+
return status_message, results_df
|
164 |
+
|
165 |
+
|
166 |
+
# --- Build Gradio Interface using Blocks ---
|
167 |
+
with gr.Blocks() as demo:
|
168 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
169 |
+
gr.Markdown(
|
170 |
+
"""
|
171 |
+
**Instructions:**
|
172 |
+
|
173 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
174 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
175 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
176 |
+
|
177 |
+
---
|
178 |
+
**Disclaimers:**
|
179 |
+
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).
|
180 |
+
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.
|
181 |
+
"""
|
182 |
+
)
|
183 |
+
|
184 |
+
gr.LoginButton()
|
185 |
+
|
186 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
187 |
+
|
188 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
189 |
+
# Removed max_rows=10 from DataFrame constructor
|
190 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
191 |
+
|
192 |
+
run_button.click(
|
193 |
+
fn=run_and_submit_all,
|
194 |
+
outputs=[status_output, results_table]
|
195 |
+
)
|
196 |
+
|
197 |
+
if __name__ == "__main__":
|
198 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
199 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
200 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
201 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
202 |
+
|
203 |
+
if space_host_startup:
|
204 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
205 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
206 |
+
else:
|
207 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
208 |
+
|
209 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
210 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
211 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
212 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
213 |
+
else:
|
214 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
215 |
+
|
216 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
217 |
+
|
218 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
219 |
demo.launch(debug=True, share=False)
|