pmeyhoefer commited on
Commit
ea28b54
·
verified ·
1 Parent(s): 19d815b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -12
app.py CHANGED
@@ -298,17 +298,32 @@ def initialize_agent():
298
  # --- Hauptfunktion run_and_submit_all (weitgehend unverändert) ---
299
  # Die Logik zum Holen der Fragen, Iterieren, Prompt erstellen, Agent aufrufen,
300
  # Antworten sammeln und Submitten bleibt gleich. Nur die Initialisierung oben ist anders.
 
301
  def run_and_submit_all( profile: gr.OAuthProfile | None, progress=gr.Progress(track_tqdm=True)):
302
  """
303
  Fetches all questions, runs the smolagents CodeAgent on them, submits all answers,
304
  and displays the results. Includes Gradio progress tracking.
305
  """
 
 
 
 
 
 
 
 
 
 
306
  space_id = os.getenv("SPACE_ID")
 
 
307
  if not profile:
308
- print("User not logged in.")
309
  return "Please Login to Hugging Face with the button.", None
310
- username = f"{profile.username}"
311
- print(f"User logged in: {username}")
 
 
312
 
313
  api_url = DEFAULT_API_URL
314
  questions_url = f"{api_url}/questions"
@@ -388,17 +403,22 @@ Let's begin the thinking process for Task {task_id}.
388
  submitted_answer = cleaned_response if cleaned_response else "Error: Agent returned empty response after cleaning."
389
  else:
390
  submitted_answer = "Error: Agent returned an empty or None response."
391
- print(f"Task {task_id} completed. Submitted Answer: '{submitted_answer}'")
 
392
 
393
  except Exception as e:
394
  error_msg = f"AGENT_RUN_ERROR on task {task_id} ({type(e).__name__}): {e}"
395
  print(error_msg)
396
  # Hier könnte man spezifischere Fehler von HfApiModel abfangen, falls bekannt
397
  submitted_answer = f"ERROR: Agent failed ({type(e).__name__})"
 
398
 
399
  finally:
400
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
401
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
402
 
403
  end_time = datetime.now(); duration = end_time - start_time
404
  print(f"Agent processing finished in {duration}.")
@@ -410,12 +430,15 @@ Let's begin the thinking process for Task {task_id}.
410
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
411
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
412
  print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
 
 
 
413
 
414
  # 5. Submit (unverändert)
415
  final_status = "Submission attempt finished."
416
  results_df = pd.DataFrame(results_log)
417
  try:
418
- response = requests.post(submit_url, json=submission_data, timeout=120)
419
  response.raise_for_status()
420
  result_data = response.json()
421
  final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"
@@ -423,17 +446,23 @@ Let's begin the thinking process for Task {task_id}.
423
  f"Message: {result_data.get('message', 'No message received.')}")
424
  print("Submission successful.")
425
  except requests.exceptions.HTTPError as e:
426
- error_detail = f"... {e.response.status_code}." # Gekürzte Fehlermeldung für Code-Lesbarkeit
427
- # (Vollständige Fehlerbehandlung wie zuvor)
428
  try:
429
  error_json = e.response.json(); api_error = error_json.get('detail', e.response.text)
430
- if isinstance(api_error, list) and len(api_error) > 0: error_detail += f" Detail: {api_error[0].get('msg', str(api_error))}"
431
- else: error_detail += f" Detail: {str(api_error)}"
432
- except: error_detail += f" Response: {e.response.text[:200]}"
 
 
 
 
 
 
 
433
  final_status = f"Submission Failed: {error_detail}"; print(final_status)
434
- except requests.exceptions.Timeout: final_status = "Submission Failed: Timeout."; print(final_status)
435
  except requests.exceptions.RequestException as e: final_status = f"Submission Failed: Network error - {e}"; print(final_status)
436
- except Exception as e: final_status = f"Submission Failed: Unexpected error ({type(e).__name__}): {e}"; print(final_status)
437
  finally: cleanup_temp_files()
438
 
439
  progress(1, desc="Done.")
 
298
  # --- Hauptfunktion run_and_submit_all (weitgehend unverändert) ---
299
  # Die Logik zum Holen der Fragen, Iterieren, Prompt erstellen, Agent aufrufen,
300
  # Antworten sammeln und Submitten bleibt gleich. Nur die Initialisierung oben ist anders.
301
+ # --- Hauptfunktion run_and_submit_all (MIT DEBUG-PRINT) ---
302
  def run_and_submit_all( profile: gr.OAuthProfile | None, progress=gr.Progress(track_tqdm=True)):
303
  """
304
  Fetches all questions, runs the smolagents CodeAgent on them, submits all answers,
305
  and displays the results. Includes Gradio progress tracking.
306
  """
307
+ # +++ DEBUGGING PRINT +++
308
+ print(f"--- Entering run_and_submit_all ---")
309
+ print(f"Received profile object: {profile}")
310
+ if profile:
311
+ print(f"Profile username: {getattr(profile, 'username', 'N/A')}")
312
+ print(f"Profile details: {vars(profile) if profile else 'N/A'}") # Zeige alle Attribute des Profils
313
+ else:
314
+ print("Profile object is None.")
315
+ # +++ END DEBUGGING PRINT +++
316
+
317
  space_id = os.getenv("SPACE_ID")
318
+
319
+ # *** HIER die eigentliche Prüfung ***
320
  if not profile:
321
+ print("Condition 'if not profile:' is TRUE. Returning login message.")
322
  return "Please Login to Hugging Face with the button.", None
323
+
324
+ # Ab hier sollte der Code nur laufen, wenn profile NICHT None ist
325
+ username = f"{profile.username}" # Jetzt sicher, da profile nicht None ist
326
+ print(f"Proceeding with run for user: {username}")
327
 
328
  api_url = DEFAULT_API_URL
329
  questions_url = f"{api_url}/questions"
 
403
  submitted_answer = cleaned_response if cleaned_response else "Error: Agent returned empty response after cleaning."
404
  else:
405
  submitted_answer = "Error: Agent returned an empty or None response."
406
+ # Kurze Pause nach jedem Agentenlauf, um Rate Limits etc. zu vermeiden (optional)
407
+ # time.sleep(0.5)
408
 
409
  except Exception as e:
410
  error_msg = f"AGENT_RUN_ERROR on task {task_id} ({type(e).__name__}): {e}"
411
  print(error_msg)
412
  # Hier könnte man spezifischere Fehler von HfApiModel abfangen, falls bekannt
413
  submitted_answer = f"ERROR: Agent failed ({type(e).__name__})"
414
+ # Bei API Fehlern ggf. kurz warten und erneut versuchen (nicht implementiert)
415
 
416
  finally:
417
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
418
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
419
+ # Logge die konkrete Antwort, die hinzugefügt wird
420
+ print(f"Task {task_id} logged. Answer added: '{submitted_answer[:100]}...'")
421
+
422
 
423
  end_time = datetime.now(); duration = end_time - start_time
424
  print(f"Agent processing finished in {duration}.")
 
430
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
431
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
432
  print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
433
+ # Debug: Zeige die ersten paar Antworten vor dem Senden
434
+ print(f"Sample answers payload: {answers_payload[:2]}")
435
+
436
 
437
  # 5. Submit (unverändert)
438
  final_status = "Submission attempt finished."
439
  results_df = pd.DataFrame(results_log)
440
  try:
441
+ response = requests.post(submit_url, json=submission_data, timeout=180) # Längeres Timeout für Submit
442
  response.raise_for_status()
443
  result_data = response.json()
444
  final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"
 
446
  f"Message: {result_data.get('message', 'No message received.')}")
447
  print("Submission successful.")
448
  except requests.exceptions.HTTPError as e:
449
+ error_detail = f"Server responded with status {e.response.status_code}."
 
450
  try:
451
  error_json = e.response.json(); api_error = error_json.get('detail', e.response.text)
452
+ # Verbesserte Fehleranzeige für Validierungsfehler
453
+ if isinstance(api_error, list) and api_error and isinstance(api_error[0], dict):
454
+ error_msgs = [f"{err.get('loc', ['unknown'])[-1]}: {err.get('msg', '')}" for err in api_error]
455
+ error_detail += f" Details: {'; '.join(error_msgs)}"
456
+ elif isinstance(api_error, str):
457
+ error_detail += f" Detail: {api_error[:500]}" # Begrenze Länge
458
+ else:
459
+ error_detail += f" Detail: {str(api_error)[:500]}"
460
+ except requests.exceptions.JSONDecodeError:
461
+ error_detail += f" Raw Response: {e.response.text[:500]}" # Begrenze Länge
462
  final_status = f"Submission Failed: {error_detail}"; print(final_status)
463
+ except requests.exceptions.Timeout: final_status = "Submission Failed: The request timed out after 180 seconds."; print(final_status)
464
  except requests.exceptions.RequestException as e: final_status = f"Submission Failed: Network error - {e}"; print(final_status)
465
+ except Exception as e: final_status = f"Submission Failed: Unexpected error during submission ({type(e).__name__}): {e}"; print(final_status)
466
  finally: cleanup_temp_files()
467
 
468
  progress(1, desc="Done.")