Toumaima commited on
Commit
de04564
·
verified ·
1 Parent(s): 8b6eba4

Update app.py

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