ShigatoraShuz commited on
Commit
0be212f
·
verified ·
1 Parent(s): ede29af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -1
app.py CHANGED
@@ -85,4 +85,187 @@ class BasicAgent:
85
  return cleaned.rstrip(".")
86
  except Exception as e:
87
  print(f"Agent error: {e}")
88
- return f"Error: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  return cleaned.rstrip(".")
86
  except Exception as e:
87
  print(f"Agent error: {e}")
88
+ return f"Error: {e}"
89
+
90
+
91
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
92
+ """
93
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
94
+ and displays the results.
95
+ """
96
+ space_id = os.getenv("SPACE_ID")
97
+
98
+ if profile:
99
+ username = f"{profile.username}"
100
+ print(f"User logged in: {username}")
101
+ else:
102
+ print("User not logged in.")
103
+ return "Please Login to Hugging Face with the button.", None
104
+
105
+ api_url = DEFAULT_API_URL
106
+ questions_url = f"{api_url}/questions"
107
+ submit_url = f"{api_url}/submit"
108
+
109
+ # 1. Instantiate Agent
110
+ try:
111
+ agent = BasicAgent()
112
+ except Exception as e:
113
+ print(f"Error instantiating agent: {e}")
114
+ return f"Error initializing agent: {e}", None
115
+
116
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
117
+ print(agent_code)
118
+
119
+ # 2. Fetch Questions
120
+ print(f"Fetching questions from: {questions_url}")
121
+ try:
122
+ response = requests.get(questions_url, timeout=15)
123
+ response.raise_for_status()
124
+ questions_data = response.json()
125
+ if not questions_data:
126
+ print("Fetched questions list is empty.")
127
+ return "Fetched questions list is empty or invalid format.", None
128
+ print(f"Fetched {len(questions_data)} questions.")
129
+ except requests.exceptions.RequestException as e:
130
+ print(f"Error fetching questions: {e}")
131
+ return f"Error fetching questions: {e}", None
132
+ except requests.exceptions.JSONDecodeError as e:
133
+ print(f"Error decoding JSON response from questions endpoint: {e}")
134
+ return f"Error decoding server response for questions: {e}", None
135
+ except Exception as e:
136
+ print(f"An unexpected error occurred fetching questions: {e}")
137
+ return f"An unexpected error occurred fetching questions: {e}", None
138
+
139
+ # 3. Run your Agent
140
+ results_log = []
141
+ answers_payload = []
142
+ print(f"Running agent on {len(questions_data)} questions...")
143
+ for item in questions_data:
144
+ task_id = item.get("task_id")
145
+ question_text = item.get("question")
146
+ if not task_id or question_text is None:
147
+ print(f"Skipping item with missing task_id or question: {item}")
148
+ continue
149
+ try:
150
+ submitted_answer = agent(question_text, task_id)
151
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
152
+ results_log.append(
153
+ {
154
+ "Task ID": task_id,
155
+ "Question": question_text,
156
+ "Submitted Answer": submitted_answer,
157
+ }
158
+ )
159
+ except Exception as e:
160
+ print(f"Error running agent on task {task_id}: {e}")
161
+ results_log.append(
162
+ {
163
+ "Task ID": task_id,
164
+ "Question": question_text,
165
+ "Submitted Answer": f"AGENT ERROR: {e}",
166
+ }
167
+ )
168
+
169
+ if not answers_payload:
170
+ print("Agent did not produce any answers to submit.")
171
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
172
+
173
+ # 4. Prepare Submission
174
+ submission_data = {
175
+ "username": username.strip(),
176
+ "agent_code": agent_code,
177
+ "answers": answers_payload,
178
+ }
179
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
180
+ print(status_update)
181
+
182
+ # 5. Submit
183
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
184
+ try:
185
+ response = requests.post(submit_url, json=submission_data, timeout=60)
186
+ response.raise_for_status()
187
+ result_data = response.json()
188
+ final_status = (
189
+ f"Submission Successful!\n"
190
+ f"User: {result_data.get('username')}\n"
191
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
192
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
193
+ f"Message: {result_data.get('message', 'No message received.')}"
194
+ )
195
+ print("Submission successful.")
196
+ results_df = pd.DataFrame(results_log)
197
+ return final_status, results_df
198
+ except requests.exceptions.HTTPError as e:
199
+ error_detail = f"Server responded with status {e.response.status_code}."
200
+ try:
201
+ error_json = e.response.json()
202
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
203
+ except requests.exceptions.JSONDecodeError:
204
+ error_detail += f" Response: {e.response.text[:500]}"
205
+ status_message = f"Submission Failed: {error_detail}"
206
+ print(status_message)
207
+ results_df = pd.DataFrame(results_log)
208
+ return status_message, results_df
209
+ except requests.exceptions.Timeout:
210
+ status_message = "Submission Failed: The request timed out. Please try again."
211
+ print(status_message)
212
+ results_df = pd.DataFrame(results_log)
213
+ return status_message, results_df
214
+ except requests.exceptions.RequestException as e:
215
+ status_message = f"Submission Failed: Network error - {e}"
216
+ print(status_message)
217
+ results_df = pd.DataFrame(results_log)
218
+ return status_message, results_df
219
+ except Exception as e:
220
+ status_message = f"An unexpected error occurred during submission: {e}"
221
+ print(status_message)
222
+ results_df = pd.DataFrame(results_log)
223
+ return status_message, results_df
224
+
225
+
226
+ # --- Build Gradio Interface using Blocks ---
227
+ with gr.Blocks() as demo:
228
+ gr.Markdown("# Basic Agent Evaluation Runner")
229
+ gr.Markdown(
230
+ """
231
+ **Instructions:**
232
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
233
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
234
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
235
+ """
236
+ )
237
+
238
+ gr.LoginButton()
239
+
240
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
241
+
242
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
243
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
244
+
245
+ run_button.click(
246
+ fn=run_and_submit_all,
247
+ outputs=[status_output, results_table],
248
+ )
249
+
250
+ if __name__ == "__main__":
251
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
252
+ space_host_startup = os.getenv("SPACE_HOST")
253
+ space_id_startup = os.getenv("SPACE_ID")
254
+
255
+ if space_host_startup:
256
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
257
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
258
+ else:
259
+ print("ℹ️ SPACE_HOST environment variable not found (running locally).")
260
+
261
+ if space_id_startup:
262
+ print(f"✅ SPACE_ID found: {space_id_startup}")
263
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
264
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
265
+ else:
266
+ print("ℹ️ SPACE_ID environment variable not found (running locally). Repo URL cannot be determined.")
267
+
268
+ print("-" * (60 + len(" App Starting ")) + "\n")
269
+
270
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
271
+ demo.launch(debug=True, share=False)