Rudraprasad commited on
Commit
5c0f112
·
verified ·
1 Parent(s): 18b740c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -107
app.py CHANGED
@@ -3,53 +3,96 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
6
 
7
- # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- # --- Tools Definitions ---
11
- def add_numbers(a, b):
12
- return a + b
13
-
14
- def reverse_text(text):
15
- return text[::-1]
16
-
17
- # --- Basic Agent Definition ---
18
- # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
19
- class BasicAgent:
20
- def __init__(self, tools=None):
21
- self.tools = tools or []
22
- print("BasicAgent initialized with tools.")
 
 
 
 
23
 
24
- def __call__(self, question: str) -> str:
25
- print(f"Agent received question (first 50 chars): {question[:50]}...")
26
 
27
- # Implement a basic logic to process tools
28
- if 'add' in question.lower():
29
- try:
30
- a, b = map(int, question.split()[-2:])
31
- answer = sum([a, b])
32
- print(f"Agent returning answer: {answer}")
33
- return str(answer)
34
- except Exception as e:
35
- return f"Error processing question: {e}"
 
 
 
 
 
 
 
36
 
37
- elif 'reverse' in question.lower():
38
- answer = question[::-1]
39
- print(f"Agent returning reversed answer: {answer}")
40
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- fixed_answer = "This is a default answer."
43
- print(f"Agent returning fixed answer: {fixed_answer}")
44
- return fixed_answer
45
 
46
- # --- Function to run the agent ---
 
 
 
 
 
 
 
 
 
47
  def run_and_submit_all(profile: gr.OAuthProfile | None):
48
  """
49
  Fetches all questions, runs the BasicAgent on them, submits all answers,
50
  and displays the results.
51
  """
52
- # --- Determine HF Space Runtime URL and Repo URL ---
53
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
54
 
55
  if profile:
@@ -63,17 +106,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
63
  questions_url = f"{api_url}/questions"
64
  submit_url = f"{api_url}/submit"
65
 
66
- # 1. Instantiate Agent (modify this part to create your agent)
67
  try:
68
- agent = BasicAgent(tools=[add_numbers, reverse_text]) # Adding tools here
69
  except Exception as e:
70
  print(f"Error instantiating agent: {e}")
71
  return f"Error initializing agent: {e}", None
72
- # In the case of an app running as a hugging Face space, this link points toward your codebase (useful for others so please keep it public)
73
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
74
- print(agent_code)
75
 
76
- # 2. Fetch Questions
77
  print(f"Fetching questions from: {questions_url}")
78
  try:
79
  response = requests.get(questions_url, timeout=15)
@@ -86,15 +126,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  except requests.exceptions.RequestException as e:
87
  print(f"Error fetching questions: {e}")
88
  return f"Error fetching questions: {e}", None
89
- except requests.exceptions.JSONDecodeError as e:
90
- print(f"Error decoding JSON response from questions endpoint: {e}")
91
- print(f"Response text: {response.text[:500]}")
92
- return f"Error decoding server response for questions: {e}", None
93
- except Exception as e:
94
- print(f"An unexpected error occurred fetching questions: {e}")
95
- return f"An unexpected error occurred fetching questions: {e}", None
96
 
97
- # 3. Run your Agent
98
  results_log = []
99
  answers_payload = []
100
  print(f"Running agent on {len(questions_data)} questions...")
@@ -116,12 +149,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
116
  print("Agent did not produce any answers to submit.")
117
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
118
 
119
- # 4. Prepare Submission
120
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
121
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
122
- print(status_update)
123
-
124
- # 5. Submit
125
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
126
  try:
127
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -137,56 +166,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
137
  print("Submission successful.")
138
  results_df = pd.DataFrame(results_log)
139
  return final_status, results_df
140
- except requests.exceptions.HTTPError as e:
141
- error_detail = f"Server responded with status {e.response.status_code}."
142
- try:
143
- error_json = e.response.json()
144
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
145
- except requests.exceptions.JSONDecodeError:
146
- error_detail += f" Response: {e.response.text[:500]}"
147
- status_message = f"Submission Failed: {error_detail}"
148
- print(status_message)
149
- results_df = pd.DataFrame(results_log)
150
- return status_message, results_df
151
- except requests.exceptions.Timeout:
152
- status_message = "Submission Failed: The request timed out."
153
- print(status_message)
154
- results_df = pd.DataFrame(results_log)
155
- return status_message, results_df
156
  except requests.exceptions.RequestException as e:
157
  status_message = f"Submission Failed: Network error - {e}"
158
  print(status_message)
159
  results_df = pd.DataFrame(results_log)
160
  return status_message, results_df
161
- except Exception as e:
162
- status_message = f"An unexpected error occurred during submission: {e}"
163
- print(status_message)
164
- results_df = pd.DataFrame(results_log)
165
- return status_message, results_df
166
-
167
 
168
  # --- Build Gradio Interface using Blocks ---
169
  with gr.Blocks() as demo:
170
- gr.Markdown("# Basic Agent Evaluation Runner")
171
  gr.Markdown(
172
  """
173
  **Instructions:**
174
 
175
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
176
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
177
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
178
-
179
- ---
180
- **Disclaimers:**
181
- 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).
182
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions in async.
183
  """
184
  )
185
 
186
  gr.LoginButton()
187
 
188
  run_button = gr.Button("Run Evaluation & Submit All Answers")
189
-
190
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
191
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
192
 
@@ -196,25 +197,4 @@ with gr.Blocks() as demo:
196
  )
197
 
198
  if __name__ == "__main__":
199
- print("\n" + "-"*30 + " App Starting " + "-"*30)
200
- # Check for SPACE_HOST and SPACE_ID at startup for information
201
- space_host_startup = os.getenv("SPACE_HOST")
202
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
203
-
204
- if space_host_startup:
205
- print(f"✅ SPACE_HOST found: {space_host_startup}")
206
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
207
- else:
208
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
209
-
210
- if space_id_startup: # Print repo URLs if SPACE_ID is found
211
- print(f"✅ SPACE_ID found: {space_id_startup}")
212
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
213
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
214
- else:
215
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
216
-
217
- print("-"*(60 + len(" App Starting ")) + "\n")
218
-
219
- print("Launching Gradio Interface for Basic Agent Evaluation...")
220
  demo.launch(debug=True, share=False)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from bs4 import BeautifulSoup
7
+ import re
8
 
9
+ # Constants
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
+ # --- Generalized Tools ---
13
+ class KnowledgeExtractionTool:
14
+ def __init__(self):
15
+ self.api_url = DEFAULT_API_URL
16
+
17
+ def fetch_data(self, url):
18
+ """Fetches data from a URL (Wikipedia or other sources)"""
19
+ response = requests.get(url)
20
+ if response.status_code == 200:
21
+ return response.text
22
+ return None
23
+
24
+ def extract_winners_from_wikipedia(self, url):
25
+ """Extracts competition winners from a Wikipedia page"""
26
+ page_content = self.fetch_data(url)
27
+ if not page_content:
28
+ return []
29
 
30
+ soup = BeautifulSoup(page_content, 'html.parser')
31
+ winners_data = []
32
 
33
+ # Look for the table of winners
34
+ winners_table = soup.find('table', {'class': 'wikitable'})
35
+ if winners_table:
36
+ for row in winners_table.find_all('tr')[1:]: # Skipping the header row
37
+ cells = row.find_all('td')
38
+ if len(cells) > 3:
39
+ name = cells[0].text.strip() # Winner's name
40
+ year = int(cells[1].text.strip()) # Year
41
+ nationality = cells[3].text.strip() # Nationality
42
+ winners_data.append({"name": name, "year": year, "nationality": nationality})
43
+ return winners_data
44
+
45
+ def filter_winners(self, winners_data, year_threshold=1977, countries_to_check=None):
46
+ """Filters winners by year and nationality (if country no longer exists)"""
47
+ if not countries_to_check:
48
+ countries_to_check = ["Yugoslavia", "Soviet Union", "East Germany"] # Example list
49
 
50
+ filtered_winners = []
51
+ for winner in winners_data:
52
+ if winner["year"] > year_threshold and any(country in winner["nationality"] for country in countries_to_check):
53
+ filtered_winners.append(winner)
54
+ return filtered_winners
55
+
56
+ def extract_first_name(self, full_name):
57
+ """Extract the first name from a full name string"""
58
+ return full_name.split()[0] if full_name else None
59
+
60
+ def process_question(self, question):
61
+ """Generalized function to process a wide variety of questions"""
62
+ if "Malko Competition" in question and "first name" in question:
63
+ print("Processing Malko Competition query...")
64
+
65
+ # Fetch data from Wikipedia (or other sources)
66
+ winners_data = self.extract_winners_from_wikipedia("https://en.wikipedia.org/wiki/Malko_Competition")
67
+
68
+ # Filter by year and nationality of winners
69
+ filtered_winners = self.filter_winners(winners_data)
70
+
71
+ # Extract and return the first name
72
+ if filtered_winners:
73
+ first_name = self.extract_first_name(filtered_winners[0]["name"])
74
+ return f"The first name of the winner is: {first_name}"
75
+ else:
76
+ return "No winners found with the specified conditions."
77
 
78
+ # Add other types of questions and their handling here as needed
79
+ return "Question could not be processed."
 
80
 
81
+ # --- Basic Agent Definition ---
82
+ class BasicAgent:
83
+ def __init__(self):
84
+ self.knowledge_tool = KnowledgeExtractionTool()
85
+
86
+ def __call__(self, question: str) -> str:
87
+ print(f"Processing question: {question}")
88
+ return self.knowledge_tool.process_question(question)
89
+
90
+ # --- Run and Submit All Function ---
91
  def run_and_submit_all(profile: gr.OAuthProfile | None):
92
  """
93
  Fetches all questions, runs the BasicAgent on them, submits all answers,
94
  and displays the results.
95
  """
 
96
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
97
 
98
  if profile:
 
106
  questions_url = f"{api_url}/questions"
107
  submit_url = f"{api_url}/submit"
108
 
109
+ # Instantiate Agent
110
  try:
111
+ agent = BasicAgent()
112
  except Exception as e:
113
  print(f"Error instantiating agent: {e}")
114
  return f"Error initializing agent: {e}", None
 
 
 
115
 
116
+ # Fetch Questions
117
  print(f"Fetching questions from: {questions_url}")
118
  try:
119
  response = requests.get(questions_url, timeout=15)
 
126
  except requests.exceptions.RequestException as e:
127
  print(f"Error fetching questions: {e}")
128
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
129
 
130
+ # Run agent on each question
131
  results_log = []
132
  answers_payload = []
133
  print(f"Running agent on {len(questions_data)} questions...")
 
149
  print("Agent did not produce any answers to submit.")
150
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
151
 
152
+ # Prepare and submit answers
153
+ submission_data = {"username": username.strip(), "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main", "answers": answers_payload}
 
 
 
 
154
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
155
  try:
156
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
166
  print("Submission successful.")
167
  results_df = pd.DataFrame(results_log)
168
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  except requests.exceptions.RequestException as e:
170
  status_message = f"Submission Failed: Network error - {e}"
171
  print(status_message)
172
  results_df = pd.DataFrame(results_log)
173
  return status_message, results_df
 
 
 
 
 
 
174
 
175
  # --- Build Gradio Interface using Blocks ---
176
  with gr.Blocks() as demo:
177
+ gr.Markdown("# Generalized Agent Evaluation Runner")
178
  gr.Markdown(
179
  """
180
  **Instructions:**
181
 
182
+ 1. Clone this space and modify the code to define your agent's logic, tools, and packages.
183
+ 2. Log in to your Hugging Face account using the button below.
184
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
 
 
185
  """
186
  )
187
 
188
  gr.LoginButton()
189
 
190
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
191
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
192
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
193
 
 
197
  )
198
 
199
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  demo.launch(debug=True, share=False)