Carolzinha2010 commited on
Commit
7bc047f
·
verified ·
1 Parent(s): aaa2c69

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -142
app.py CHANGED
@@ -464,145 +464,34 @@ Answer:"""
464
  return fixed_answer
465
 
466
 
467
- def run_and_submit_all( profile: gr.OAuthProfile | None, other_arg=None): # Modified to accept 2 arguments
468
- """
469
- Fetches all questions, runs the BasicAgent on them, submits all answers,
470
- and displays the results.
471
- """
472
- print("run_and_submit_all function started.") # Debugging print at function start
473
- # --- Determine HF Space Runtime URL and Repo URL ---
474
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
475
-
476
- if profile:
477
- username= f"{profile.username}"
478
- print(f"User logged in: {username}")
479
- else:
480
- print("User not logged in.")
481
- # --- SIMULAÇÃO PARA COLAB ---
482
- username = "colab_test_user" # <--- Adicione esta linha para simular um usuário no Colab
483
- print(f"User not logged in, simulating for Colab: {username}")
484
- # return "Please Login to Hugging Face with the button.", None # Comente esta linha para testar no Colab
485
-
486
- api_url = DEFAULT_API_URL
487
- questions_url = f"{api_url}/questions"
488
- submit_url = f"{api_url}/submit"
489
-
490
- # 1. Instantiate Agent ( modify this part to create your agent)
491
- print("Attempting to instantiate BasicAgent...") # Debugging print before instantiation
492
- try:
493
- agent = BasicAgent()
494
- print("BasicAgent instantiated successfully.") # Debugging print after instantiation
495
- except Exception as e:
496
- print(f"Error instantiating agent: {e}")
497
- return f"Error initializing agent: {e}", None
498
- # 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)
499
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "No SPACE_ID found, cannot generate agent_code URL."
500
- print(agent_code)
501
-
502
- # 2. Fetch Questions
503
- print(f"Fetching questions from: {questions_url}")
504
- questions_data = None # Initialize to None
505
- try:
506
- response = requests.get(questions_url, timeout=15)
507
- response.raise_for_status()
508
- questions_data = response.json()
509
- # Add check for empty or non-list questions_data immediately after fetching
510
- if not isinstance(questions_data, list) or not questions_data:
511
- print(f"Fetched questions_data is empty or not a list. Type: {type(questions_data)}")
512
- return "Fetched questions list is empty or invalid format.", None
513
- print(f"Fetched {len(questions_data)} questions.")
514
- except requests.exceptions.RequestException as e:
515
- print(f"Error fetching questions: {e}")
516
- return f"Error fetching questions: {e}", None
517
- except requests.exceptions.JSONDecodeError as e:
518
- print(f"Error decoding JSON response from questions endpoint: {e}")
519
- # Print the response text for debugging if JSON decoding fails
520
- print(f"Response text: {response.text[:500] if 'response' in locals() else 'No response object'}")
521
- return f"Error decoding server response for questions: {e}", None
522
- except Exception as e:
523
- print(f"An unexpected error occurred fetching questions: {e}")
524
- return f"An unexpected error occurred fetching questions: {e}", None
525
-
526
-
527
- # 3. Run your Agent
528
- results_log = []
529
- answers_payload = []
530
- print(f"Running agent on {len(questions_data)} questions...")
531
- # The check that questions_data is a list is now done immediately after fetching
532
- for item in questions_data:
533
- # Add check for None or non-dict item before accessing keys
534
- if item is None or not isinstance(item, dict):
535
- print(f"Skipping invalid item in questions_data: {item}")
536
- continue
537
- task_id = item.get("task_id")
538
- question_text = item.get("question")
539
- if not task_id or not isinstance(task_id, (str, int)) or not question_text or not isinstance(question_text, str):
540
- print(f"Skipping item with missing or invalid task_id or question: {item}")
541
- continue
542
- print(f"Processing Task ID: {task_id}") # Debugging task ID
543
- try:
544
- # Here, we only pass the question text for now, as the API doesn't support video input
545
- # The video processing logic is added but not triggered by this function
546
- submitted_answer = agent(question_text)
547
- print(f"Agent returned answer for {task_id}: {submitted_answer[:50]}...") # Debugging returned answer
548
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
549
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
550
- except Exception as e:
551
- print(f"Error running agent on task {task_id}: {e}")
552
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
553
-
554
- if not answers_payload:
555
- print("Agent did not produce any answers to submit.")
556
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
557
-
558
- # 4. Prepare Submission
559
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
560
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
561
- print(status_update)
562
-
563
- # 5. Submit
564
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
565
- try:
566
- response = requests.post(submit_url, json=submission_data, timeout=60)
567
- response.raise_for_status()
568
- result_data = response.json()
569
- final_status = (
570
- f"Submission Successful!\n"
571
- f"User: {result_data.get('username')}\n"
572
- f"Overall Score: {result_data.get('score', 'N/A')}% "
573
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
574
- f"Message: {result_data.get('message', 'No message received.')}"
575
- )
576
- print("Submission successful.")
577
- results_df = pd.DataFrame(results_log)
578
- return final_status, results_df
579
- except requests.exceptions.HTTPError as e:
580
- error_detail = f"Server responded with status {e.response.status_code}."
581
- try:
582
- error_json = e.response.json()
583
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
584
- status_message = f"Submission Failed: {error_detail}"
585
- print(status_message)
586
- # If submission fails, also return the results log so the user can see what was attempted
587
- results_df = pd.DataFrame(results_log)
588
- return status_message, results_df
589
- except requests.exceptions.JSONDecodeError:
590
- error_detail += f" Response: {e.response.text[:500]}"
591
- status_message = f"Submission Failed: {error_detail}"
592
- print(status_message)
593
- results_df = pd.DataFrame(results_log)
594
- return status_message, results_df
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
- except requests.exceptions.Timeout:
600
- status_message = "Submission Failed: The request timed out."
601
- print(status_message)
602
- results_df = pd.DataFrame(results_log)
603
- return status_message, results_df
604
- except requests.exceptions.RequestException as e:
605
- status_message = f"Submission Failed: Network error - {e}"
606
- print(status_message)
607
- results_df = pd.DataFrame(results_log)
608
- return status_message, results_df
 
464
  return fixed_answer
465
 
466
 
467
+ # --- Gradio Interface Setup ---
468
+ # Define the Gradio interface
469
+ with gr.Blocks() as demo:
470
+ gr.Markdown(
471
+ """
472
+ # Agente de IA para o Desafio Hugging Face
473
+ Este agente usa o Google Gemini para responder perguntas e a SerpAPI para realizar buscas na web.
474
+ Ele também tem uma funcionalidade (não ativada pelo desafio) para processar vídeos.
475
+ """
476
+ )
477
+
478
+ with gr.Row():
479
+ with gr.Column():
480
+ question_input = gr.Textbox(label="Sua Pergunta", placeholder="Ex: O que é inteligência artificial?")
481
+ # Não incluímos o input de vídeo aqui, pois o desafio não o usa diretamente
482
+ # video_input = gr.Video(label="Upload de Vídeo (Opcional)", type="filepath")
483
+ submit_button = gr.Button("Executar Agente e Submeter Respostas")
484
+ with gr.Column():
485
+ status_output = gr.Textbox(label="Status da Execução", interactive=False)
486
+ results_dataframe = gr.Dataframe(label="Resultados Detalhados", interactive=False, headers=["Task ID", "Question", "Submitted Answer"])
487
+
488
+ # Conectar o botão à função run_and_submit_all
489
+ # O componente gr.Login() fornece o 'profile' automaticamente quando o usuário faz login
490
+ submit_button.click(
491
+ fn=run_and_submit_all,
492
+ inputs=[gr.Login(every=None), None], # 'None' para o 'other_arg' que não estamos usando
493
+ outputs=[status_output, results_dataframe]
494
+ )
495
+
496
+ # Lançar o aplicativo Gradio
497
+ demo.launch(share=True) # share=True gera um link público para o seu Space (útil para testes)