ShigatoraShuz commited on
Commit
4dbfe56
·
verified ·
1 Parent(s): 49847b8

Update app.py

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