GattoNero commited on
Commit
e9e5834
Β·
verified Β·
1 Parent(s): 312cb43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -116
app.py CHANGED
@@ -32,6 +32,7 @@ import re
32
  import importlib.metadata
33
  import random
34
  import time
 
35
 
36
 
37
  set_global_handler("simple") # imposta un handler semplice per il logging
@@ -94,6 +95,17 @@ class BasicAgent:
94
  description="Takes a list of item names (such as menu categories) and returns a string tagging each item as either food or not. The result is a comma-separated list like 'burgers: True, soda: False'."
95
  )
96
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  # Registra il tool
99
  #Settings.tools = [ingredient_tool]
@@ -106,7 +118,7 @@ class BasicAgent:
106
 
107
 
108
  self.agent = OpenAIAgent.from_tools(
109
- tools = [ingredient_tool, log_thought_tool, sum_list_tool, search_tool, is_food_tool, final_answer],
110
  llm = llm,
111
  verbose = True,
112
  max_steps=30
@@ -526,6 +538,11 @@ blackList = [
526
  "question":"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
527
  "Level":"1",
528
  "file_name":"cca530fc-4052-43b2-b130-b30968d8aa44.png"
 
 
 
 
 
529
  }
530
  ]
531
 
@@ -552,7 +569,7 @@ def create_mock_questions():
552
  return whiteList
553
 
554
 
555
- tempMock = [{"task_id":"8e867cd7-cff9-4e6c-867a-ff5ddc2550be","question":"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.","Level":"1","file_name":""},{"task_id":"a1e91b78-d3d8-4675-bb8d-62741b4b68a6","question":"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?","Level":"1","file_name":""},{"task_id":"2d83110e-a098-4ebb-9987-066c06fa42d0","question":".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI","Level":"1","file_name":""},{"task_id":"cca530fc-4052-43b2-b130-b30968d8aa44","question":"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.","Level":"1","file_name":"cca530fc-4052-43b2-b130-b30968d8aa44.png"},{"task_id":"4fc2f1ae-8625-45b5-ab34-ad4433bc21f8","question":"Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?","Level":"1","file_name":""},{"task_id":"6f37996b-2ac7-44b0-8e68-6d28256631b4","question":"Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.","Level":"1","file_name":""},{"task_id":"9d191bce-651d-4746-be2d-7ef8ecadb9c2","question":"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"","Level":"1","file_name":""},{"task_id":"cabe07ed-9eca-40ea-8ead-410ef5e83f91","question":"What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?","Level":"1","file_name":""},{"task_id":"3cef3a44-215e-4aed-8e3b-b1e3f08063b7","question":"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.","Level":"1","file_name":""},{"task_id":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3","question":"Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.","Level":"1","file_name":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"},{"task_id":"305ac316-eef6-4446-960a-92d80d542f82","question":"Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.","Level":"1","file_name":""},{"task_id":"f918266a-b3e0-4914-865d-4faa564f1aef","question":"What is the final numeric output from the attached Python code?","Level":"1","file_name":"f918266a-b3e0-4914-865d-4faa564f1aef.py"},{"task_id":"3f57289b-8c60-48be-bd80-01f8099ca449","question":"How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?","Level":"1","file_name":""},{"task_id":"1f975693-876d-457b-a649-393859e79bf3","question":"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.","Level":"1","file_name":"1f975693-876d-457b-a649-393859e79bf3.mp3"},{"task_id":"840bfca7-4f7b-481a-8794-c560c340185d","question":"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?","Level":"1","file_name":""},{"task_id":"bda648d7-d618-4883-88f4-3466eabd860e","question":"Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.","Level":"1","file_name":""},{"task_id":"cf106601-ab4f-4af9-b045-5295fe67b37d","question":"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.","Level":"1","file_name":""},{"task_id":"a0c07678-e491-4bbc-8f0b-07405144218f","question":"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.","Level":"1","file_name":""},{"task_id":"7bd855d8-463d-4ed5-93ca-5fe35145f733","question":"The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.","Level":"1","file_name":"7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"},{"task_id":"5a0c1adf-205e-4841-a666-7c3ef95def9d","question":"What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?","Level":"1","file_name":""}]
556
 
557
 
558
 
@@ -644,18 +661,37 @@ def web_search(query: str) -> str:
644
  time.sleep(1.5)
645
  print_coso(f"tool web_search formattedResult: {results}")
646
  return results
647
- '''
648
- def web_search(query: str) -> str:
649
- print_coso(f"tool web_search con query: {query}")
650
  try:
651
- with DDGS() as ddgs:
652
- results = ddgs.text(query)
653
- if not results:
654
- return "No results found."
655
- return "\n".join([r["body"] for r in results[:3]])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  except Exception as e:
657
- return f"Error: {e}"
658
- '''
659
 
660
  def log_thought(thought: str) -> str:
661
  print_coso(f"Tool log_thought: {thought}")
@@ -686,148 +722,152 @@ def print_coso(scritta: str):
686
  # (Keep Constants as is)
687
  # --- Constants ---
688
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
689
 
690
- ##Roba per la valutazione
691
-
692
- def run_and_submit_all( profile: gr.OAuthProfile | None):
693
- """
694
- Fetches all questions, runs the BasicAgent on them, submits all answers,
695
- and displays the results.
696
- """
697
- # --- Determine HF Space Runtime URL and Repo URL ---
698
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
699
 
700
  if profile:
701
- username= f"{profile.username}"
702
  print(f"User logged in: {username}")
703
  else:
704
- print("User not logged in.")
705
  return "Please Login to Hugging Face with the button.", None
706
 
707
  api_url = DEFAULT_API_URL
708
  questions_url = f"{api_url}/questions"
709
  submit_url = f"{api_url}/submit"
710
 
711
- # 1. Instantiate Agent ( modify this part to create your agent)
712
  try:
713
  agent = BasicAgent()
714
  except Exception as e:
715
- print(f"Error instantiating agent: {e}")
716
  return f"Error initializing agent: {e}", None
717
- # 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)
718
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
719
- print(agent_code)
720
 
721
- # 2. Fetch Questions
722
- print(f"Fetching questions from: {questions_url}")
723
  try:
724
- #qui per servizio get domande
725
  if DOMANDE_MOCKATE:
726
  total_questions = create_mock_questions()
727
  else:
728
- print_coso("lancio servizio questions")
729
- responseFromService = tempMock #requests.get(questions_url, timeout=30)
730
- response = process_questions(responseFromService)
731
- #response.raise_for_status()
732
- total_questions = response#.json()
733
-
734
- questions_data = total_questions[:min(20, len(total_questions))]
735
- print_coso(f"questions_data: {questions_data}")
736
  if not questions_data:
737
- print("Fetched questions list is empty.")
738
- return "Fetched questions list is empty or invalid format.", None
739
- print(f"Fetched {len(questions_data)} questions.")
740
- except requests.exceptions.RequestException as e:
741
- print(f"Error fetching questions: {e}")
742
- return f"Error fetching questions: {e}", None
743
- except requests.exceptions.JSONDecodeError as e:
744
- print(f"Error decoding JSON response from questions endpoint: {e}")
745
- print(f"Response text: {response.text[:500]}")
746
- return f"Error decoding server response for questions: {e}", None
747
  except Exception as e:
748
- print(f"An unexpected error occurred fetching questions: {e}")
749
- return f"An unexpected error occurred fetching questions: {e}", None
750
 
751
- # 3. Run your Agent
752
- results_log = []
753
  answers_payload = []
754
- print(f"Running agent on {len(questions_data)} questions...")
 
 
755
  for item in questions_data:
756
  task_id = item.get("task_id")
757
- question_text = item.get("question")
758
- if not task_id or question_text is None:
759
- print(f"Skipping item with missing task_id or question: {item}")
760
  continue
761
  try:
762
  file_name = item.get("file_name")
763
- print_coso(f"file_name riga in 3. Run your Agent: {file_name}")
764
- submitted_answer = agent(question_text, file_name) #mock
765
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
766
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
767
  except Exception as e:
768
- print(f"Error running agent on task {task_id}: {e}")
769
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
770
 
771
  if not answers_payload:
772
- print("Agent did not produce any answers to submit.")
773
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
774
 
775
- # 4. Prepare Submission
776
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
777
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
778
- print(status_update)
 
 
 
 
 
 
779
 
780
- # 5. Submit
781
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
782
  try:
 
 
 
 
783
 
 
 
 
 
 
 
 
 
784
 
785
-
786
- response = requests.post(submit_url, json=submission_data, timeout=60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
  response.raise_for_status()
788
- result_data = response.json()
789
- print_coso(result_data)
790
  final_status = (
791
- f"Submission Successful!\n"
792
- f"User: {result_data.get('username')}\n"
793
- f"Overall Score: {result_data.get('score', 'N/A')}% "
794
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
795
- f"Message: {result_data.get('message', 'No message received.')}"
796
  )
797
- print("Submission successful.")
798
- results_df = pd.DataFrame(results_log)
 
799
 
800
- print(f"coso final_status: {final_status} - results_df: {results_df}")
801
- return final_status, results_df
802
-
803
 
804
-
805
- except requests.exceptions.HTTPError as e:
806
- error_detail = f"Server responded with status {e.response.status_code}."
807
- try:
808
- error_json = e.response.json()
809
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
810
- except requests.exceptions.JSONDecodeError:
811
- error_detail += f" Response: {e.response.text[:500]}"
812
- status_message = f"Submission Failed: {error_detail}"
813
- print(status_message)
814
- results_df = pd.DataFrame(results_log)
815
- return status_message, results_df
816
- except requests.exceptions.Timeout:
817
- status_message = "Submission Failed: The request timed out."
818
- print(status_message)
819
- results_df = pd.DataFrame(results_log)
820
- return status_message, results_df
821
- except requests.exceptions.RequestException as e:
822
- status_message = f"Submission Failed: Network error - {e}"
823
- print(status_message)
824
- results_df = pd.DataFrame(results_log)
825
- return status_message, results_df
826
  except Exception as e:
827
- status_message = f"An unexpected error occurred during submission: {e}"
828
- print(status_message)
829
- results_df = pd.DataFrame(results_log)
830
- return status_message, results_df
831
 
832
 
833
  # --- Build Gradio Interface using Blocks ---
@@ -849,15 +889,15 @@ with gr.Blocks() as demo:
849
  gr.LoginButton()
850
 
851
  run_button = gr.Button("Run Evaluation & Submit All Answers")
852
-
 
 
853
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
854
- # Removed max_rows=10 from DataFrame constructor
855
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
856
-
857
- run_button.click(
858
- fn=run_and_submit_all,
859
- outputs=[status_output, results_table]
860
- )
861
 
862
  if __name__ == "__main__":
863
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
32
  import importlib.metadata
33
  import random
34
  import time
35
+ import yt_dlp
36
 
37
 
38
  set_global_handler("simple") # imposta un handler semplice per il logging
 
95
  description="Takes a list of item names (such as menu categories) and returns a string tagging each item as either food or not. The result is a comma-separated list like 'burgers: True, soda: False'."
96
  )
97
 
98
+ transcribe_youtube_tool = FunctionTool.from_defaults(
99
+ name="transcribe_youtube_audio",
100
+ fn=transcribe_youtube_audio,
101
+ description=(
102
+ "Use this tool when the task involves a YouTube link and requires analyzing the spoken content of the video. "
103
+ "It downloads the audio from the given YouTube URL and transcribes it using Whisper. "
104
+ "Use this to extract speech from interviews, discussions, lectures, or any video where the spoken content is relevant. "
105
+ "Returns only the transcribed text."
106
+ )
107
+ )
108
+
109
 
110
  # Registra il tool
111
  #Settings.tools = [ingredient_tool]
 
118
 
119
 
120
  self.agent = OpenAIAgent.from_tools(
121
+ tools = [ingredient_tool, log_thought_tool, sum_list_tool, search_tool, is_food_tool, transcribe_youtube_tool, final_answer],
122
  llm = llm,
123
  verbose = True,
124
  max_steps=30
 
538
  "question":"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
539
  "Level":"1",
540
  "file_name":"cca530fc-4052-43b2-b130-b30968d8aa44.png"
541
+ },
542
+ {"task_id":"a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
543
+ "question":"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?"
544
+ ,"Level":"1",
545
+ "file_name":""
546
  }
547
  ]
548
 
 
569
  return whiteList
570
 
571
 
572
+ tempMock = [{"task_id":"8e867cd7-cff9-4e6c-867a-ff5ddc2550be","question":"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.","Level":"1","file_name":""},,{"task_id":"2d83110e-a098-4ebb-9987-066c06fa42d0","question":".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI","Level":"1","file_name":""},{"task_id":"cca530fc-4052-43b2-b130-b30968d8aa44","question":"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.","Level":"1","file_name":"cca530fc-4052-43b2-b130-b30968d8aa44.png"},{"task_id":"4fc2f1ae-8625-45b5-ab34-ad4433bc21f8","question":"Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?","Level":"1","file_name":""},{"task_id":"6f37996b-2ac7-44b0-8e68-6d28256631b4","question":"Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.","Level":"1","file_name":""},{"task_id":"9d191bce-651d-4746-be2d-7ef8ecadb9c2","question":"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"","Level":"1","file_name":""},{"task_id":"cabe07ed-9eca-40ea-8ead-410ef5e83f91","question":"What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?","Level":"1","file_name":""},{"task_id":"3cef3a44-215e-4aed-8e3b-b1e3f08063b7","question":"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.","Level":"1","file_name":""},{"task_id":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3","question":"Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.","Level":"1","file_name":"99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"},{"task_id":"305ac316-eef6-4446-960a-92d80d542f82","question":"Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.","Level":"1","file_name":""},{"task_id":"f918266a-b3e0-4914-865d-4faa564f1aef","question":"What is the final numeric output from the attached Python code?","Level":"1","file_name":"f918266a-b3e0-4914-865d-4faa564f1aef.py"},{"task_id":"3f57289b-8c60-48be-bd80-01f8099ca449","question":"How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?","Level":"1","file_name":""},{"task_id":"1f975693-876d-457b-a649-393859e79bf3","question":"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.","Level":"1","file_name":"1f975693-876d-457b-a649-393859e79bf3.mp3"},{"task_id":"840bfca7-4f7b-481a-8794-c560c340185d","question":"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?","Level":"1","file_name":""},{"task_id":"bda648d7-d618-4883-88f4-3466eabd860e","question":"Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.","Level":"1","file_name":""},{"task_id":"cf106601-ab4f-4af9-b045-5295fe67b37d","question":"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.","Level":"1","file_name":""},{"task_id":"a0c07678-e491-4bbc-8f0b-07405144218f","question":"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.","Level":"1","file_name":""},{"task_id":"7bd855d8-463d-4ed5-93ca-5fe35145f733","question":"The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.","Level":"1","file_name":"7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"},{"task_id":"5a0c1adf-205e-4841-a666-7c3ef95def9d","question":"What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?","Level":"1","file_name":""}]
573
 
574
 
575
 
 
661
  time.sleep(1.5)
662
  print_coso(f"tool web_search formattedResult: {results}")
663
  return results
664
+
665
+
666
+ def transcribe_youtube_audio(url: str) -> str:
667
  try:
668
+ print_coso(f"Downloading audio from: {url}")
669
+
670
+ # Setup download options
671
+ ydl_opts = {
672
+ 'format': 'bestaudio/best',
673
+ 'outtmpl': '/tmp/audio.%(ext)s',
674
+ 'quiet': True,
675
+ 'postprocessors': [{
676
+ 'key': 'FFmpegExtractAudio',
677
+ 'preferredcodec': 'mp3',
678
+ 'preferredquality': '192',
679
+ }],
680
+ }
681
+
682
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
683
+ ydl.download([url])
684
+
685
+ # Transcribe
686
+ audio_path = '/tmp/audio.mp3'
687
+ model = whisper.load_model("base")
688
+ result = model.transcribe(audio_path)
689
+
690
+ print_coso(f"transcribe_youtube_audio result: {result['text']}")
691
+ return result["text"]
692
+
693
  except Exception as e:
694
+ return f"Error transcribing YouTube audio: {e}"
 
695
 
696
  def log_thought(thought: str) -> str:
697
  print_coso(f"Tool log_thought: {thought}")
 
722
  # (Keep Constants as is)
723
  # --- Constants ---
724
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
725
+ CACHE_FILE = "cached_submission.json"
726
 
727
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
728
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
729
 
730
  if profile:
731
+ username = profile.username
732
  print(f"User logged in: {username}")
733
  else:
 
734
  return "Please Login to Hugging Face with the button.", None
735
 
736
  api_url = DEFAULT_API_URL
737
  questions_url = f"{api_url}/questions"
738
  submit_url = f"{api_url}/submit"
739
 
 
740
  try:
741
  agent = BasicAgent()
742
  except Exception as e:
 
743
  return f"Error initializing agent: {e}", None
744
+
745
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
746
+ print(f"[INFO] Agent code link: {agent_code}")
747
 
748
+ # 1. Fetch Questions
 
749
  try:
 
750
  if DOMANDE_MOCKATE:
751
  total_questions = create_mock_questions()
752
  else:
753
+ print("[INFO] Fetching questions...")
754
+ response = requests.get(questions_url, timeout=30)
755
+ response.raise_for_status()
756
+ total_questions = process_questions(response.json())
757
+
758
+ questions_data = total_questions[:20]
 
 
759
  if not questions_data:
760
+ return "No questions fetched.", None
761
+ print(f"[INFO] Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
 
762
  except Exception as e:
763
+ return f"[ERROR] Could not fetch questions: {e}", None
 
764
 
765
+ # 2. Run Agent
 
766
  answers_payload = []
767
+ results_log = []
768
+
769
+ print(f"[INFO] Running agent on {len(questions_data)} questions...")
770
  for item in questions_data:
771
  task_id = item.get("task_id")
772
+ question = item.get("question")
773
+ if not task_id or not question:
 
774
  continue
775
  try:
776
  file_name = item.get("file_name")
777
+ answer = agent(question, file_name)
778
+ answers_payload.append({
779
+ "task_id": task_id,
780
+ "submitted_answer": answer,
781
+ })
782
+ results_log.append({
783
+ "Task ID": task_id,
784
+ "Question": question,
785
+ "Submitted Answer": answer,
786
+ })
787
  except Exception as e:
788
+ traceback.print_exc()
789
+ results_log.append({
790
+ "Task ID": task_id,
791
+ "Question": question,
792
+ "Submitted Answer": f"[ERROR]: {e}"
793
+ })
794
 
795
  if not answers_payload:
 
796
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
797
 
798
+ # 3. Save locally
799
+ submission_data = {
800
+ "username": username,
801
+ "agent_code": agent_code,
802
+ "answers": answers_payload,
803
+ }
804
+
805
+ with open(CACHE_FILE, "w") as f:
806
+ json.dump(submission_data, f, indent=2)
807
+ print(f"[INFO] Saved answers locally to {CACHE_FILE}")
808
 
809
+ # 4. Submit answers
 
810
  try:
811
+ print(f"[INFO] Submitting {len(answers_payload)} answers...")
812
+ response = requests.post(submit_url, json=submission_data, timeout=120)
813
+ response.raise_for_status()
814
+ result = response.json()
815
 
816
+ final_status = (
817
+ f"βœ… Submission Successful!\n"
818
+ f"User: {result.get('username')}\n"
819
+ f"Score: {result.get('score', '?')}% "
820
+ f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')})\n"
821
+ f"Message: {result.get('message', '')}"
822
+ )
823
+ return final_status, pd.DataFrame(results_log)
824
 
825
+ except requests.exceptions.Timeout:
826
+ return f"❌ Submission failed: Timeout.", pd.DataFrame(results_log)
827
+ except requests.exceptions.RequestException as e:
828
+ return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
829
+ except Exception as e:
830
+ return f"❌ Unexpected error during submission: {e}", pd.DataFrame(results_log)
831
+
832
+
833
+ def retry_submission(profile: gr.OAuthProfile | None):
834
+ if not os.path.exists(CACHE_FILE):
835
+ return "❌ No cached submission file found.", None
836
+
837
+ try:
838
+ with open(CACHE_FILE, "r") as f:
839
+ cached_data = json.load(f)
840
+ response = requests.post(f"{DEFAULT_API_URL}/submit", json=cached_data, timeout=120)
841
  response.raise_for_status()
842
+ result = response.json()
843
+
844
  final_status = (
845
+ f"βœ… Retry Successful!\n"
846
+ f"User: {result.get('username')}\n"
847
+ f"Score: {result.get('score', '?')}% "
848
+ f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')})\n"
849
+ f"Message: {result.get('message', '')}"
850
  )
851
+ return final_status, pd.DataFrame(cached_data["answers"])
852
+ except Exception as e:
853
+ return f"❌ Retry submission failed: {e}", None
854
 
855
+ def print_cached_submission(profile: gr.OAuthProfile | None):
856
+ if not os.path.exists(CACHE_FILE):
857
+ return "⚠️ No cached submission file found.", None
858
 
859
+ try:
860
+ with open(CACHE_FILE, "r") as f:
861
+ data = json.load(f)
862
+ status = (
863
+ f"πŸ“„ Cached submission for user '{data.get('username')}'\n"
864
+ f"{len(data.get('answers', []))} answers ready for submission."
865
+ )
866
+ return status, pd.DataFrame(data["answers"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
867
  except Exception as e:
868
+ return f"❌ Could not load cached submission: {e}", None
869
+
870
+
 
871
 
872
 
873
  # --- Build Gradio Interface using Blocks ---
 
889
  gr.LoginButton()
890
 
891
  run_button = gr.Button("Run Evaluation & Submit All Answers")
892
+ retry_button = gr.Button("πŸ” Retry Last Submission")
893
+ print_cache_button = gr.Button("πŸ“„ Show Cached Submission")
894
+
895
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
896
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
897
+
898
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
899
+ retry_button.click(fn=retry_submission, outputs=[status_output, results_table])
900
+ print_cache_button.click(fn=print_cached_submission, outputs=[status_output, results_table])
 
901
 
902
  if __name__ == "__main__":
903
  print("\n" + "-"*30 + " App Starting " + "-"*30)