helene-rousset commited on
Commit
c3bf584
·
verified ·
1 Parent(s): d4549d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -5
app.py CHANGED
@@ -138,11 +138,138 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
138
  return status_message, results_df
139
 
140
 
141
- def save_fn(profile: gr.OAuthProfile | None):
142
- filename = "saved_answers.json"
143
- with open(filename, "w") as f:
144
- json.dump([], f, indent=2)
145
- return f"✅ Saved to {filename}", filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  # --- Build Gradio Interface using Blocks ---
148
  with gr.Blocks() as demo:
 
138
  return status_message, results_df
139
 
140
 
141
+ import os
142
+ import json
143
+ import requests
144
+
145
+ def update_and_resubmit_one_answer(task_id_to_redo: str, profile: gr.OAuthProfile | None):
146
+ """
147
+ Updates a single answer in saved_answers.json and re-submits the whole payload.
148
+ """
149
+
150
+ # --- Determine HF Space Runtime URL and Repo URL ---
151
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
152
+
153
+ if profile:
154
+ username= f"{profile.username}"
155
+ print(f"User logged in: {username}")
156
+ else:
157
+ print("User not logged in.")
158
+ return "Please Login to Hugging Face with the button.", None
159
+
160
+ api_url = DEFAULT_API_URL
161
+ questions_url = f"{api_url}/questions"
162
+ submit_url = f"{api_url}/submit"
163
+
164
+ # 1. Instantiate Agent ( modify this part to create your agent)
165
+ try:
166
+ agent = build_agent()
167
+ except Exception as e:
168
+ print(f"Error instantiating agent: {e}")
169
+ return f"Error initializing agent: {e}", None
170
+ # 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)
171
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
172
+ print(agent_code)
173
+
174
+ # 2. Fetch Questions
175
+ print(f"Fetching questions from: {questions_url}")
176
+ try:
177
+ response = requests.get(questions_url, timeout=15)
178
+ response.raise_for_status()
179
+ questions_data = response.json()
180
+ if not questions_data:
181
+ print("Fetched questions list is empty.")
182
+ return "Fetched questions list is empty or invalid format.", None
183
+ print(f"Fetched {len(questions_data)} questions.")
184
+ except requests.exceptions.RequestException as e:
185
+ print(f"Error fetching questions: {e}")
186
+ return f"Error fetching questions: {e}", None
187
+ except requests.exceptions.JSONDecodeError as e:
188
+ print(f"Error decoding JSON response from questions endpoint: {e}")
189
+ print(f"Response text: {response.text[:500]}")
190
+ return f"Error decoding server response for questions: {e}", None
191
+ except Exception as e:
192
+ print(f"An unexpected error occurred fetching questions: {e}")
193
+ return f"An unexpected error occurred fetching questions: {e}", None
194
+
195
+ # 3. Run your Agent
196
+ results_log = []
197
+ with open("saved_answers.json", "r") as f:
198
+ saved_payload = json.load(f)
199
+
200
+ new_payload = []
201
+ for a in saved_payload:
202
+ if a["task_id"] != task_id_to_redo:
203
+ new_payload.append(a)
204
+
205
+ print(f"Running agent on 1 question...")
206
+ for item in questions_data:
207
+ task_id = item.get("task_id")
208
+ if task_id == task_id_to_redo:
209
+ question_text = item.get("question")
210
+ try:
211
+ messages = [HumanMessage(content=json.dumps(item))]
212
+ response = agent.invoke({"messages": messages})
213
+ submitted_answer = response['messages'][-1].content
214
+ new_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
215
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
216
+ except Exception as e:
217
+ print(f"Error running agent on task {task_id}: {e}")
218
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
219
+
220
+
221
+ # 4. Prepare Submission
222
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": new_payload}
223
+ status_update = f"Agent finished. Submitting {len(new_payload)} answers for user '{username}'..."
224
+ print(status_update)
225
+
226
+ # Inside run_and_submit_all(), after results_log is built
227
+ with open("saved_answers.json", "w") as f:
228
+ json.dump(new_payload, f, indent=2)
229
+
230
+ # 5. Submit
231
+ print(f"Submitting {len(new_payload)} answers to: {submit_url}")
232
+ try:
233
+ response = requests.post(submit_url, json=submission_data, timeout=60)
234
+ response.raise_for_status()
235
+ result_data = response.json()
236
+ final_status = (
237
+ f"Submission Successful!\n"
238
+ f"User: {result_data.get('username')}\n"
239
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
240
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
241
+ f"Message: {result_data.get('message', 'No message received.')}"
242
+ )
243
+ print("Submission successful.")
244
+ results_df = pd.DataFrame(results_log)
245
+ return final_status, results_df
246
+ except requests.exceptions.HTTPError as e:
247
+ error_detail = f"Server responded with status {e.response.status_code}."
248
+ try:
249
+ error_json = e.response.json()
250
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
251
+ except requests.exceptions.JSONDecodeError:
252
+ error_detail += f" Response: {e.response.text[:500]}"
253
+ status_message = f"Submission Failed: {error_detail}"
254
+ print(status_message)
255
+ results_df = pd.DataFrame(results_log)
256
+ return status_message, results_df
257
+ except requests.exceptions.Timeout:
258
+ status_message = "Submission Failed: The request timed out."
259
+ print(status_message)
260
+ results_df = pd.DataFrame(results_log)
261
+ return status_message, results_df
262
+ except requests.exceptions.RequestException as e:
263
+ status_message = f"Submission Failed: Network error - {e}"
264
+ print(status_message)
265
+ results_df = pd.DataFrame(results_log)
266
+ return status_message, results_df
267
+ except Exception as e:
268
+ status_message = f"An unexpected error occurred during submission: {e}"
269
+ print(status_message)
270
+ results_df = pd.DataFrame(results_log)
271
+ return status_message, results_df
272
+
273
 
274
  # --- Build Gradio Interface using Blocks ---
275
  with gr.Blocks() as demo: