Update app.py
Browse files1234567891011121314151617181920212223242512 unmodified lines3839404142434445464748495012 unmodified lines6364656667686976 unmodified lines1461471481491501511521531541551566 unmodified lines1631641651661671681693 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196import osimport gradio as grimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.12 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# 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)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)12 unmodified linesreturn f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")76 unmodified linesgr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).6 unmodified linesrun_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(3 unmodified linesif __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798012 unmodified lines9394959697989910010110210310412 unmodified lines11711811912012112276 unmodified lines1992002012022032042052062076 unmodified lines2142152162172182193 unmodified lines223224225226227228229230231232233234235236import osimport gradio as grimport requestsimport re# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"WIKIPEDIA_API_URL = "https://en.wikipedia.org/w/api.php"# --- Basic Agent Definition ---class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Check if the question is related to Mercedes Sosa's albumsif "Mercedes Sosa" in question and "albums" in question:answer = self.get_mercedes_sosa_albums_2000_to_2009()return answerfixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef get_mercedes_sosa_albums_2000_to_2009(self) -> str:"""Fetch Mercedes Sosa's album list from Wikipedia and count the albums released between 2000-2009."""try:# Get data from Wikipedia API for Mercedes Sosa's pageresponse = requests.get(WIKIPEDIA_API_URL, params={'action': 'query','format': 'json','titles': 'Mercedes_Sosa','prop': 'extracts','exintro': True,'explaintext': True,})response.raise_for_status()data = response.json()page = list(data['query']['pages'].values())[0]extract = page.get('extract', '')# Find albums released between 2000 and 2009albums_2000s = self.extract_albums_from_text(extract, 2000, 2009)return f"Mercedes Sosa released {len(albums_2000s)} studio albums between 2000 and 2009."except requests.exceptions.RequestException as e:print(f"Error fetching Wikipedia data: {e}")return f"Error fetching data: {e}"except Exception as e:print(f"An unexpected error occurred: {e}")return f"An unexpected error occurred: {e}"def extract_albums_from_text(self, text: str, start_year: int, end_year: int) -> list:"""Extract album information from the Wikipedia extract text based on the year range."""albums = []# Simple regex pattern to find years and album names in the textpattern = r"(\d{4})[\s\-\:]?([A-Za-z0-9\s\(\)]+)"matches = re.findall(pattern, text)# Filter albums by the specified year rangefor year, album_name in matches:year = int(year)if start_year <= year <= end_year:albums.append((year, album_name.strip()))return albumsdef run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.12 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)12 unmodified linesreturn f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")76 unmodified linesgr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).6 unmodified linesrun_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(3 unmodified linesif __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)space_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID")if space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")if space_id_startup:print(f"✅ SPACE_ID found: {space_id_startup}")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)
app.py+62-22