Toumaima commited on
Commit
9bbb7c7
·
verified ·
1 Parent(s): 07548b5

Update app.py

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