Annessha18 commited on
Commit
d20fc11
·
verified ·
1 Parent(s): 0bd8e11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -76
app.py CHANGED
@@ -1,21 +1,19 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- from transformers import pipeline
14
- import re
15
 
16
  class BasicAgent:
17
  def __init__(self):
18
  print("BasicAgent initialized.")
 
19
  self.generator = pipeline(
20
  "text2text-generation",
21
  model="google/flan-t5-large",
@@ -31,69 +29,74 @@ class BasicAgent:
31
 
32
  result = self.generator(prompt)[0]["generated_text"]
33
 
34
- # Strong cleanup
35
  answer = result.strip()
36
- answer = answer.replace("The answer is", "")
37
- answer = re.split(r"[.\n,]", answer)[0]
38
- answer = answer.strip()
 
 
 
39
 
40
  print(f"Final answer: {answer}")
41
  return answer
42
 
43
 
44
-
45
-
46
- def run_and_submit_all( profile: gr.OAuthProfile | None):
47
  """
48
  Fetches all questions, runs the BasicAgent on them, submits all answers,
49
  and displays the results.
50
  """
51
- # --- Determine HF Space Runtime URL and Repo URL ---
52
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
53
 
54
  if profile:
55
- username= f"{profile.username}"
56
  print(f"User logged in: {username}")
57
  else:
58
  print("User not logged in.")
59
- return "Please Login to Hugging Face with the button.", None
60
 
61
  api_url = DEFAULT_API_URL
62
  questions_url = f"{api_url}/questions"
63
  submit_url = f"{api_url}/submit"
64
 
65
- # 1. Instantiate Agent ( modify this part to create your agent)
66
  try:
67
  agent = BasicAgent()
68
  except Exception as e:
69
  print(f"Error instantiating agent: {e}")
70
- return f"Error initializing agent: {e}", None
71
- # 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)
72
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
 
 
 
73
  print(agent_code)
74
 
75
- # 2. Fetch Questions
76
  print(f"Fetching questions from: {questions_url}")
77
  try:
78
  response = requests.get(questions_url, timeout=15)
79
  response.raise_for_status()
80
  questions_data = response.json()
81
  if not questions_data:
82
- print("Fetched questions list is empty.")
83
- return "Fetched questions list is empty or invalid format.", None
84
  print(f"Fetched {len(questions_data)} questions.")
85
  except requests.exceptions.RequestException as e:
86
  print(f"Error fetching questions: {e}")
87
- return f"Error fetching questions: {e}", None
88
  except requests.exceptions.JSONDecodeError as e:
89
- print(f"Error decoding JSON response from questions endpoint: {e}")
90
- print(f"Response text: {response.text[:500]}")
91
- return f"Error decoding server response for questions: {e}", None
92
  except Exception as e:
93
- print(f"An unexpected error occurred fetching questions: {e}")
94
- return f"An unexpected error occurred fetching questions: {e}", None
95
 
96
- # 3. Run your Agent
97
  results_log = []
98
  answers_payload = []
99
  print(f"Running agent on {len(questions_data)} questions...")
@@ -106,22 +109,32 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
106
  try:
107
  submitted_answer = agent(question_text)
108
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
109
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
110
  except Exception as e:
111
- print(f"Error running agent on task {task_id}: {e}")
112
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
113
 
114
  if not answers_payload:
115
  print("Agent did not produce any answers to submit.")
116
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
117
 
118
- # 4. Prepare Submission
119
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
120
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
121
- print(status_update)
 
 
 
122
 
123
- # 5. Submit
124
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
125
  try:
126
  response = requests.post(submit_url, json=submission_data, timeout=60)
127
  response.raise_for_status()
@@ -136,58 +149,35 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
136
  print("Submission successful.")
137
  results_df = pd.DataFrame(results_log)
138
  return final_status, results_df
139
- except requests.exceptions.HTTPError as e:
140
- error_detail = f"Server responded with status {e.response.status_code}."
141
- try:
142
- error_json = e.response.json()
143
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
144
- except requests.exceptions.JSONDecodeError:
145
- error_detail += f" Response: {e.response.text[:500]}"
146
- status_message = f"Submission Failed: {error_detail}"
147
- print(status_message)
148
- results_df = pd.DataFrame(results_log)
149
- return status_message, results_df
150
- except requests.exceptions.Timeout:
151
- status_message = "Submission Failed: The request timed out."
152
- print(status_message)
153
- results_df = pd.DataFrame(results_log)
154
- return status_message, results_df
155
  except requests.exceptions.RequestException as e:
156
- status_message = f"Submission Failed: Network error - {e}"
157
  print(status_message)
158
  results_df = pd.DataFrame(results_log)
159
  return status_message, results_df
160
  except Exception as e:
161
- status_message = f"An unexpected error occurred during submission: {e}"
162
  print(status_message)
163
  results_df = pd.DataFrame(results_log)
164
  return status_message, results_df
165
 
166
 
167
- # --- Build Gradio Interface using Blocks ---
168
  with gr.Blocks() as demo:
169
  gr.Markdown("# Basic Agent Evaluation Runner")
170
  gr.Markdown(
171
  """
172
  **Instructions:**
173
 
174
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
175
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
176
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
177
-
178
- ---
179
- **Disclaimers:**
180
- 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).
181
- 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 seperate action or even to answer the questions in async.
182
  """
183
  )
184
 
185
  gr.LoginButton()
186
-
187
  run_button = gr.Button("Run Evaluation & Submit All Answers")
188
 
189
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
190
- # Removed max_rows=10 from DataFrame constructor
191
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
192
 
193
  run_button.click(
@@ -195,26 +185,26 @@ with gr.Blocks() as demo:
195
  outputs=[status_output, results_table]
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)
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import re
5
  import pandas as pd
6
 
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
  # --- Basic Agent Definition ---
11
+ from transformers import pipeline, set_seed
 
 
12
 
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
+ set_seed(42) # ensure reproducible outputs
17
  self.generator = pipeline(
18
  "text2text-generation",
19
  model="google/flan-t5-large",
 
29
 
30
  result = self.generator(prompt)[0]["generated_text"]
31
 
32
+ # --- Strong cleanup for GAIA exact answers ---
33
  answer = result.strip()
34
+ # Remove common prefixes
35
+ answer = re.sub(r"(?i)^(the answer is|answer:)\s*", "", answer)
36
+ # Take only first line or sentence
37
+ answer = re.split(r"[.\n]", answer)[0].strip()
38
+ # Remove trailing punctuation
39
+ answer = answer.rstrip(".,;:")
40
 
41
  print(f"Final answer: {answer}")
42
  return answer
43
 
44
 
45
+ # --- Run and Submit Function ---
46
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
 
47
  """
48
  Fetches all questions, runs the BasicAgent on them, submits all answers,
49
  and displays the results.
50
  """
51
+ space_id = os.getenv("SPACE_ID")
 
52
 
53
  if profile:
54
+ username = f"{profile.username}"
55
  print(f"User logged in: {username}")
56
  else:
57
  print("User not logged in.")
58
+ return "Please Login to Hugging Face with the button.", pd.DataFrame()
59
 
60
  api_url = DEFAULT_API_URL
61
  questions_url = f"{api_url}/questions"
62
  submit_url = f"{api_url}/submit"
63
 
64
+ # --- Instantiate Agent ---
65
  try:
66
  agent = BasicAgent()
67
  except Exception as e:
68
  print(f"Error instantiating agent: {e}")
69
+ return f"Error initializing agent: {e}", pd.DataFrame()
70
+
71
+ # --- Agent Code URL ---
72
+ if space_id:
73
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
74
+ else:
75
+ agent_code = "Agent code URL not available."
76
  print(agent_code)
77
 
78
+ # --- Fetch Questions ---
79
  print(f"Fetching questions from: {questions_url}")
80
  try:
81
  response = requests.get(questions_url, timeout=15)
82
  response.raise_for_status()
83
  questions_data = response.json()
84
  if not questions_data:
85
+ print("Fetched questions list is empty.")
86
+ return "Fetched questions list is empty or invalid format.", pd.DataFrame()
87
  print(f"Fetched {len(questions_data)} questions.")
88
  except requests.exceptions.RequestException as e:
89
  print(f"Error fetching questions: {e}")
90
+ return f"Error fetching questions: {e}", pd.DataFrame()
91
  except requests.exceptions.JSONDecodeError as e:
92
+ print(f"Error decoding JSON response: {e}")
93
+ print(f"Response text: {response.text[:500]}")
94
+ return f"Error decoding server response for questions: {e}", pd.DataFrame()
95
  except Exception as e:
96
+ print(f"Unexpected error fetching questions: {e}")
97
+ return f"Unexpected error fetching questions: {e}", pd.DataFrame()
98
 
99
+ # --- Run Agent ---
100
  results_log = []
101
  answers_payload = []
102
  print(f"Running agent on {len(questions_data)} questions...")
 
109
  try:
110
  submitted_answer = agent(question_text)
111
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
112
+ results_log.append({
113
+ "Task ID": task_id,
114
+ "Question": question_text,
115
+ "Submitted Answer": submitted_answer
116
+ })
117
  except Exception as e:
118
+ print(f"Error running agent on task {task_id}: {e}")
119
+ results_log.append({
120
+ "Task ID": task_id,
121
+ "Question": question_text,
122
+ "Submitted Answer": f"AGENT ERROR: {e}"
123
+ })
124
 
125
  if not answers_payload:
126
  print("Agent did not produce any answers to submit.")
127
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
128
 
129
+ # --- Prepare Submission ---
130
+ submission_data = {
131
+ "username": username.strip(),
132
+ "agent_code": agent_code,
133
+ "answers": answers_payload
134
+ }
135
+ print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
136
 
137
+ # --- Submit Answers ---
 
138
  try:
139
  response = requests.post(submit_url, json=submission_data, timeout=60)
140
  response.raise_for_status()
 
149
  print("Submission successful.")
150
  results_df = pd.DataFrame(results_log)
151
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  except requests.exceptions.RequestException as e:
153
+ status_message = f"Submission Failed: {e}"
154
  print(status_message)
155
  results_df = pd.DataFrame(results_log)
156
  return status_message, results_df
157
  except Exception as e:
158
+ status_message = f"Unexpected error during submission: {e}"
159
  print(status_message)
160
  results_df = pd.DataFrame(results_log)
161
  return status_message, results_df
162
 
163
 
164
+ # --- Gradio Interface ---
165
  with gr.Blocks() as demo:
166
  gr.Markdown("# Basic Agent Evaluation Runner")
167
  gr.Markdown(
168
  """
169
  **Instructions:**
170
 
171
+ 1. Clone this space and modify the code to define your agent's logic.
172
+ 2. Log in to your Hugging Face account using the button below.
173
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
 
 
174
  """
175
  )
176
 
177
  gr.LoginButton()
 
178
  run_button = gr.Button("Run Evaluation & Submit All Answers")
179
 
180
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
181
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
182
 
183
  run_button.click(
 
185
  outputs=[status_output, results_table]
186
  )
187
 
188
+
189
+ # --- Startup Logs ---
190
  if __name__ == "__main__":
191
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
192
  space_host_startup = os.getenv("SPACE_HOST")
193
+ space_id_startup = os.getenv("SPACE_ID")
194
 
195
  if space_host_startup:
196
  print(f"✅ SPACE_HOST found: {space_host_startup}")
197
+ print(f" Runtime URL: https://{space_host_startup}.hf.space")
198
  else:
199
+ print("ℹ️ SPACE_HOST not found (running locally?)")
200
 
201
+ if space_id_startup:
202
  print(f"✅ SPACE_ID found: {space_id_startup}")
203
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
204
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
205
  else:
206
+ print("ℹ️ SPACE_ID not found (running locally?)")
207
 
208
  print("-"*(60 + len(" App Starting ")) + "\n")
 
209
  print("Launching Gradio Interface for Basic Agent Evaluation...")
210
+ demo.launch(debug=True, share=False)