Spaces:
Build error
Build error
Create app.py
Browse files
app.py
CHANGED
|
@@ -466,6 +466,152 @@ Answer:"""
|
|
| 466 |
|
| 467 |
# --- Gradio Interface Setup ---
|
| 468 |
# Define the Gradio interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
with gr.Blocks() as demo:
|
| 470 |
gr.Markdown(
|
| 471 |
"""
|
|
|
|
| 466 |
|
| 467 |
# --- Gradio Interface Setup ---
|
| 468 |
# Define the Gradio interface
|
| 469 |
+
|
| 470 |
+
# MOVIDO PARA CIMA: A função run_and_submit_all precisa ser definida antes de ser usada no Gradio.
|
| 471 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None, other_arg=None): # Modified to accept 2 arguments
|
| 472 |
+
"""
|
| 473 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 474 |
+
and displays the results.
|
| 475 |
+
"""
|
| 476 |
+
print("run_and_submit_all function started.") # Debugging print at function start
|
| 477 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 478 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 479 |
+
|
| 480 |
+
if profile:
|
| 481 |
+
username= f"{profile.username}"
|
| 482 |
+
print(f"User logged in: {username}")
|
| 483 |
+
else:
|
| 484 |
+
print("User not logged in.")
|
| 485 |
+
# --- SIMULAÇÃO PARA COLAB ---
|
| 486 |
+
username = "colab_test_user" # <--- Adicione esta linha para simular um usuário no Colab
|
| 487 |
+
print(f"User not logged in, simulating for Colab: {username}")
|
| 488 |
+
# return "Please Login to Hugging Face with the button.", None # Comente esta linha para testar no Colab
|
| 489 |
+
|
| 490 |
+
api_url = DEFAULT_API_URL
|
| 491 |
+
questions_url = f"{api_url}/questions"
|
| 492 |
+
submit_url = f"{api_url}/submit"
|
| 493 |
+
|
| 494 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 495 |
+
print("Attempting to instantiate BasicAgent...") # Debugging print before instantiation
|
| 496 |
+
try:
|
| 497 |
+
agent = BasicAgent()
|
| 498 |
+
print("BasicAgent instantiated successfully.") # Debugging print after instantiation
|
| 499 |
+
except Exception as e:
|
| 500 |
+
print(f"Error instantiating agent: {e}")
|
| 501 |
+
return f"Error initializing agent: {e}", None
|
| 502 |
+
# 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)
|
| 503 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "No SPACE_ID found, cannot generate agent_code URL."
|
| 504 |
+
print(agent_code)
|
| 505 |
+
|
| 506 |
+
# 2. Fetch Questions
|
| 507 |
+
print(f"Fetching questions from: {questions_url}")
|
| 508 |
+
questions_data = None # Initialize to None
|
| 509 |
+
try:
|
| 510 |
+
response = requests.get(questions_url, timeout=15)
|
| 511 |
+
response.raise_for_status()
|
| 512 |
+
questions_data = response.json()
|
| 513 |
+
# Add check for empty or non-list questions_data immediately after fetching
|
| 514 |
+
if not isinstance(questions_data, list) or not questions_data:
|
| 515 |
+
print(f"Fetched questions_data is empty or not a list. Type: {type(questions_data)}")
|
| 516 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 517 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 518 |
+
except requests.exceptions.RequestException as e:
|
| 519 |
+
print(f"Error fetching questions: {e}")
|
| 520 |
+
return f"Error fetching questions: {e}", None
|
| 521 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 522 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 523 |
+
# Print the response text for debugging if JSON decoding fails
|
| 524 |
+
print(f"Response text: {response.text[:500] if 'response' in locals() else 'No response object'}")
|
| 525 |
+
return f"Error decoding server response for questions: {e}", None
|
| 526 |
+
except Exception as e:
|
| 527 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 528 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
# 3. Run your Agent
|
| 532 |
+
results_log = []
|
| 533 |
+
answers_payload = []
|
| 534 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 535 |
+
# The check that questions_data is a list is now done immediately after fetching
|
| 536 |
+
for item in questions_data:
|
| 537 |
+
# Add check for None or non-dict item before accessing keys
|
| 538 |
+
if item is None or not isinstance(item, dict):
|
| 539 |
+
print(f"Skipping invalid item in questions_data: {item}")
|
| 540 |
+
continue
|
| 541 |
+
task_id = item.get("task_id")
|
| 542 |
+
question_text = item.get("question")
|
| 543 |
+
if not task_id or not isinstance(task_id, (str, int)) or not question_text or not isinstance(question_text, str):
|
| 544 |
+
print(f"Skipping item with missing or invalid task_id or question: {item}")
|
| 545 |
+
continue
|
| 546 |
+
print(f"Processing Task ID: {task_id}") # Debugging task ID
|
| 547 |
+
try:
|
| 548 |
+
# Here, we only pass the question text for now, as the API doesn't support video input
|
| 549 |
+
# The video processing logic is added but not triggered by this function
|
| 550 |
+
submitted_answer = agent(question_text)
|
| 551 |
+
print(f"Agent returned answer for {task_id}: {submitted_answer[:50]}...") # Debugging returned answer
|
| 552 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 553 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 554 |
+
except Exception as e:
|
| 555 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 556 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 557 |
+
|
| 558 |
+
if not answers_payload:
|
| 559 |
+
print("Agent did not produce any answers to submit.")
|
| 560 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 561 |
+
|
| 562 |
+
# 4. Prepare Submission
|
| 563 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 564 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 565 |
+
print(status_update)
|
| 566 |
+
|
| 567 |
+
# 5. Submit
|
| 568 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 569 |
+
try:
|
| 570 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 571 |
+
response.raise_for_status()
|
| 572 |
+
result_data = response.json()
|
| 573 |
+
final_status = (
|
| 574 |
+
f"Submission Successful!\n"
|
| 575 |
+
f"User: {result_data.get('username')}\n"
|
| 576 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 577 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 578 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 579 |
+
)
|
| 580 |
+
print("Submission successful.")
|
| 581 |
+
results_df = pd.DataFrame(results_log)
|
| 582 |
+
return final_status, results_df
|
| 583 |
+
except requests.exceptions.HTTPError as e:
|
| 584 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 585 |
+
try:
|
| 586 |
+
error_json = e.response.json()
|
| 587 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 588 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 589 |
+
print(status_message)
|
| 590 |
+
# If submission fails, also return the results log so the user can see what was attempted
|
| 591 |
+
results_df = pd.DataFrame(results_log)
|
| 592 |
+
return status_message, results_df
|
| 593 |
+
except requests.exceptions.JSONDecodeError:
|
| 594 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 595 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 596 |
+
print(status_message)
|
| 597 |
+
results_df = pd.DataFrame(results_log)
|
| 598 |
+
return status_message, results_df
|
| 599 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 600 |
+
print(status_message)
|
| 601 |
+
results_df = pd.DataFrame(results_log)
|
| 602 |
+
return status_message, results_df
|
| 603 |
+
except requests.exceptions.Timeout:
|
| 604 |
+
status_message = "Submission Failed: The request timed out."
|
| 605 |
+
print(status_message)
|
| 606 |
+
results_df = pd.DataFrame(results_log)
|
| 607 |
+
return status_message, results_df
|
| 608 |
+
except requests.exceptions.RequestException as e:
|
| 609 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 610 |
+
print(status_message)
|
| 611 |
+
results_df = pd.DataFrame(results_log)
|
| 612 |
+
return status_message, results_df
|
| 613 |
+
|
| 614 |
+
|
| 615 |
with gr.Blocks() as demo:
|
| 616 |
gr.Markdown(
|
| 617 |
"""
|