Synnove commited on
Commit
8b8a315
·
verified ·
1 Parent(s): f517477

testing client

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