Yago Bolivar commited on
Commit
2e3dd06
·
1 Parent(s): c5a6e89

feat: enhance BasicAgent to handle file inputs and improve question processing

Browse files
Files changed (1) hide show
  1. app.py +147 -49
app.py CHANGED
@@ -1,34 +1,117 @@
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
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,65 +121,78 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # 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)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
 
51
- # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
53
  try:
54
- response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
 
 
81
  continue
 
 
 
 
82
  try:
83
- submitted_answer = agent(question_text)
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
98
 
99
- # 5. Submit
100
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -118,7 +214,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
118
  error_json = e.response.json()
119
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
  except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
  status_message = f"Submission Failed: {error_detail}"
123
  print(status_message)
124
  results_df = pd.DataFrame(results_log)
@@ -142,19 +238,19 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
142
 
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
 
154
  ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
  """
159
  )
160
 
@@ -163,34 +259,36 @@ with gr.Blocks() as demo:
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
170
  fn=run_and_submit_all,
 
171
  outputs=[status_output, results_table]
172
  )
173
 
174
  if __name__ == "__main__":
175
  print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"✅ SPACE_HOST found: {space_host_startup}")
182
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
  else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
 
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect # Keep if you plan to use it for agent introspection later
5
  import pandas as pd
6
 
7
+ from src.file_processing_tool import FileIdentifier
8
+ from src.speech_to_text import transcribe_audio
9
+ from src.download_utils import download_file
10
+
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+ DOWNLOADED_FILES_DIR = "downloaded_task_files" # Directory to store downloaded files
14
+ # Ensure the directory for downloaded files exists when the app starts
15
+ os.makedirs(DOWNLOADED_FILES_DIR, exist_ok=True)
16
 
17
  # --- Basic Agent Definition ---
18
+ # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
19
  class BasicAgent:
20
  def __init__(self):
21
  print("BasicAgent initialized.")
22
+ self.file_identifier = FileIdentifier()
23
+ # You might initialize other tools here if needed (e.g., spreadsheet parser, OCR)
24
+
25
+ def __call__(self, question_data: dict) -> str:
26
+ question_text = question_data.get("question")
27
+ file_url = question_data.get("file_url")
28
+ task_id = question_data.get("task_id", "unknown_task") # For unique file naming
29
+
30
+ print(f"Agent received task_id: {task_id}, question: {question_text}, file_url: {file_url}")
31
+ downloaded_file_path = None
32
+
33
+ if file_url:
34
+ print(f"File URL provided: {file_url}")
35
+ # Construct a unique filename
36
+ original_filename = file_url.split('/')[-1] if file_url else "file"
37
+ # Basic sanitization for filename
38
+ safe_original_filename = "".join(c for c in original_filename if c.isalnum() or c in ['.', '_', '-']).strip()
39
+ if not safe_original_filename: # Handle cases where sanitization leaves an empty string
40
+ safe_original_filename = "downloaded_file"
41
+
42
+ unique_filename = f"{task_id}_{safe_original_filename}"
43
+
44
+ downloaded_file_path = download_file(file_url, DOWNLOADED_FILES_DIR, filename=unique_filename)
45
+
46
+ if not downloaded_file_path:
47
+ print(f"Error: Failed to download the associated file for task {task_id} from {file_url}.")
48
+ return "Error: Failed to download the associated file."
49
+
50
+ print(f"File downloaded to: {downloaded_file_path}")
51
+ file_info = self.file_identifier.identify_file(downloaded_file_path)
52
+ print(f"File info for {downloaded_file_path}: {file_info}")
53
+
54
+ if file_info.get("error"):
55
+ return f"Error processing file: {file_info['error']}"
56
 
57
+ if file_info["determined_type"] == "audio" and file_info["suggested_action"] == "speech-to-text":
58
+ print(f"File {downloaded_file_path} identified as audio, attempting transcription...")
59
+ transcribed_text = transcribe_audio(downloaded_file_path)
60
+
61
+ if "Error during transcription" in transcribed_text: # Basic error check
62
+ print(f"Transcription error for {downloaded_file_path}: {transcribed_text}")
63
+ return f"Could not transcribe audio: {transcribed_text}"
64
+
65
+ # Placeholder: Use the question and transcribed_text to form an answer
66
+ # In a real agent, you'd use an LLM or other logic here.
67
+ answer = f"The audio file says: {transcribed_text[:200]}... (This is a placeholder answer based on transcription)"
68
+ print(f"Returning answer based on audio: {answer}")
69
+ return answer
70
+
71
+ # Add more conditions for other file types and actions
72
+ # elif file_info["determined_type"] == "spreadsheet":
73
+ # # Call your spreadsheet parser
74
+ # # data = self.spreadsheet_parser.parse(downloaded_file_path)
75
+ # # answer = self.reason_about_spreadsheet(question_text, data)
76
+ # # return answer
77
+ # pass
78
+ # elif file_info["determined_type"] == "image":
79
+ # # Call your OCR/vision tool
80
+ # # details = self.ocr_tool.analyze(downloaded_file_path)
81
+ # # answer = self.reason_about_image(question_text, details)
82
+ # # return answer
83
+ # pass
84
+ else:
85
+ warning_msg = f"File type '{file_info['determined_type']}' (action: '{file_info['suggested_action']}') not yet handled for file: {os.path.basename(downloaded_file_path)}."
86
+ print(warning_msg)
87
+ # Fallback if file type is known but not handled, or if it's an unknown type
88
+ # You might still try to answer the question if it doesn't strictly depend on the file content.
89
+ return f"File received, but type '{file_info['determined_type']}' is not yet processed by this agent. Question: {question_text}"
90
+
91
+
92
+ # Fallback or question-only processing (if no file_url or file not handled)
93
+ # This is where you'd put logic for questions that don't involve files,
94
+ # or if a file was present but not processable by the current tools.
95
+ # For GAIA, many questions will have files.
96
+ if question_text:
97
+ # Placeholder for LLM call or other reasoning for text-only questions
98
+ default_answer = f"Received question: '{question_text}'. No specific file action taken or file not processable. (Default Response)"
99
+ print(f"Agent returning default text-based answer: {default_answer}")
100
+ return default_answer
101
+ else:
102
+ # Should not happen if GAIA questions always have text or file
103
+ return "No question text provided and no file processed."
104
+
105
+
106
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
107
  """
108
  Fetches all questions, runs the BasicAgent on them, submits all answers,
109
  and displays the results.
110
  """
111
+ space_id = os.getenv("SPACE_ID")
 
112
 
113
  if profile:
114
+ username = f"{profile.username}"
115
  print(f"User logged in: {username}")
116
  else:
117
  print("User not logged in.")
 
121
  questions_url = f"{api_url}/questions"
122
  submit_url = f"{api_url}/submit"
123
 
 
124
  try:
125
  agent = BasicAgent()
126
  except Exception as e:
127
  print(f"Error instantiating agent: {e}")
128
  return f"Error initializing agent: {e}", None
129
+
130
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "local_run_no_space_id"
131
+ print(f"Agent code reference: {agent_code}")
132
 
 
133
  print(f"Fetching questions from: {questions_url}")
134
  try:
135
+ response = requests.get(questions_url, timeout=30) # Increased timeout
136
  response.raise_for_status()
137
  questions_data = response.json()
138
  if not questions_data:
139
+ print("Fetched questions list is empty.")
140
+ return "Fetched questions list is empty or invalid format.", None
141
  print(f"Fetched {len(questions_data)} questions.")
142
  except requests.exceptions.RequestException as e:
143
  print(f"Error fetching questions: {e}")
144
  return f"Error fetching questions: {e}", None
145
  except requests.exceptions.JSONDecodeError as e:
146
+ print(f"Error decoding JSON response from questions endpoint: {e}")
147
+ print(f"Response text (first 500 chars): {response.text[:500] if response else 'No response object'}")
148
+ return f"Error decoding server response for questions: {e}", None
149
  except Exception as e:
150
  print(f"An unexpected error occurred fetching questions: {e}")
151
  return f"An unexpected error occurred fetching questions: {e}", None
152
 
 
153
  results_log = []
154
  answers_payload = []
155
  print(f"Running agent on {len(questions_data)} questions...")
156
  for item in questions_data:
157
  task_id = item.get("task_id")
158
+ question_text = item.get("question") # Can be None if file_url is primary
159
+ file_url = item.get("file_url")
160
+
161
+ if not task_id:
162
+ print(f"Skipping item with missing task_id: {item}")
163
  continue
164
+
165
+ # Prepare the input for the agent's __call__ method
166
+ agent_input_data = {"task_id": task_id, "question": question_text, "file_url": file_url}
167
+
168
  try:
169
+ submitted_answer = agent(agent_input_data)
170
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
171
+ results_log.append({
172
+ "Task ID": task_id,
173
+ "Question": question_text if question_text else "N/A (File-based question)",
174
+ "File URL": file_url if file_url else "N/A",
175
+ "Submitted Answer": submitted_answer
176
+ })
177
  except Exception as e:
178
+ print(f"Error running agent on task {task_id}: {e}")
179
+ results_log.append({
180
+ "Task ID": task_id,
181
+ "Question": question_text if question_text else "N/A (File-based question)",
182
+ "File URL": file_url if file_url else "N/A",
183
+ "Submitted Answer": f"AGENT ERROR: {e}"
184
+ })
185
 
186
  if not answers_payload:
187
  print("Agent did not produce any answers to submit.")
188
+ # Still return results_log if it has entries (e.g. all agent errors)
189
+ results_df = pd.DataFrame(results_log) if results_log else None
190
+ return "Agent did not produce any answers to submit.", results_df
191
 
 
192
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
193
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
194
  print(status_update)
195
 
 
196
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
197
  try:
198
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
214
  error_json = e.response.json()
215
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
216
  except requests.exceptions.JSONDecodeError:
217
+ error_detail += f" Response (first 500 chars): {e.response.text[:500]}"
218
  status_message = f"Submission Failed: {error_detail}"
219
  print(status_message)
220
  results_df = pd.DataFrame(results_log)
 
238
 
239
  # --- Build Gradio Interface using Blocks ---
240
  with gr.Blocks() as demo:
241
+ gr.Markdown("# GAIA Benchmark Agent Runner")
242
  gr.Markdown(
243
  """
244
  **Instructions:**
245
 
246
+ 1. Clone this space, then modify `src/` files (especially `BasicAgent` in `app.py`, and tool implementations) to define your agent's logic.
247
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
248
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
249
 
250
  ---
251
+ **Notes:**
252
+ - The agent's processing can take time, especially with file downloads and model inferences.
253
+ - This is a basic framework. For more complex agents, consider asynchronous operations, caching, and more robust error handling.
254
  """
255
  )
256
 
 
259
  run_button = gr.Button("Run Evaluation & Submit All Answers")
260
 
261
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
262
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, interactive=False) # Set interactive=False for display
 
263
 
264
  run_button.click(
265
  fn=run_and_submit_all,
266
+ inputs=None, # LoginButton provides profile implicitly if used as input, but here it's handled by checking profile in the function
267
  outputs=[status_output, results_table]
268
  )
269
 
270
  if __name__ == "__main__":
271
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
272
  space_host_startup = os.getenv("SPACE_HOST")
273
+ space_id_startup = os.getenv("SPACE_ID")
274
 
275
  if space_host_startup:
276
  print(f"✅ SPACE_HOST found: {space_host_startup}")
277
  print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
278
  else:
279
+ print("ℹ️ SPACE_HOST environment variable not found (likely running locally).")
280
 
281
+ if space_id_startup:
282
  print(f"✅ SPACE_ID found: {space_id_startup}")
283
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
284
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
285
  else:
286
+ print("ℹ️ SPACE_ID environment variable not found (likely running locally). Repo URL cannot be determined.")
287
 
288
  print("-"*(60 + len(" App Starting ")) + "\n")
289
 
290
+ print("Launching Gradio Interface for GAIA Agent Evaluation...")
291
+ # Set server_name and server_port for local development if needed, e.g. demo.launch(server_name="0.0.0.0", server_port=7860)
292
+ # For Hugging Face Spaces, share=True is often handled by the platform.
293
+ # debug=True is useful for development.
294
+ demo.launch(debug=True)