Karim0111 commited on
Commit
bc6fadc
·
verified ·
1 Parent(s): eca273b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -12
app.py CHANGED
@@ -1,23 +1,163 @@
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
  """
@@ -45,7 +185,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
@@ -76,11 +216,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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:
@@ -146,11 +291,9 @@ with gr.Blocks() as demo:
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).
@@ -171,7 +314,38 @@ with gr.Blocks() as demo:
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")
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import os
6
+ from agents import manager_agent
7
+ from datetime import datetime
8
+ from typing import Optional
9
+ import time
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
 
 
15
  class BasicAgent:
16
  def __init__(self):
17
  print("BasicAgent initialized.")
18
+ self.agent = manager_agent
19
+ self.verbose = True
20
+
21
+ def __call__(self, question: str, files: list[str] = None) -> str:
22
+ print(f"Agent received question: {question[:50]}... with files: {files}")
23
+ result = self.answer_question(question, files)
24
+ print(f"Agent returning answer: {result}")
25
+ #time.sleep(60)
26
+ return result
27
+ def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str:
28
+ """
29
+ Process a GAIA benchmark question and return the answer
30
+
31
+ Args:
32
+ question: The question to answer
33
+ task_file_path: Optional path to a file associated with the question
34
+
35
+ Returns:
36
+ The answer to the question
37
+ """
38
+ try:
39
+ if self.verbose:
40
+ print(f"Processing question: {question}")
41
+ if task_file_path:
42
+ print(f"With associated file: {task_file_path}")
43
+
44
+ # Create a context with file information if available
45
+ context = question
46
+
47
+ # If there's a file, read it and include its content in the context
48
+ if task_file_path:
49
+ try:
50
+ context = f"""
51
+ Question: {question}
52
+
53
+ This question has an associated file. You can download the file from
54
+ {DEFAULT_API_URL}/files/{task_file_path}
55
+ using the download_file_from_url tool.
56
+
57
+ Analyze the file content above to answer the question.
58
+ """
59
+ except Exception as file_e:
60
+ context = f"""
61
+ Question: {question}
62
+
63
+ This question has an associated file at path: {task_file_path}
64
+ However, there was an error reading the file: {file_e}
65
+ You can still try to answer the question based on the information provided.
66
+ """
67
+
68
+ # Check for special cases that need specific formatting
69
+ # Reversed text questions
70
+ if question.startswith(".") or ".rewsna eht sa" in question:
71
+ context = f"""
72
+ This question appears to be in reversed text. Here's the reversed version:
73
+ {question[::-1]}
74
+
75
+ Now answer the question above. Remember to format your answer exactly as requested.
76
+ """
77
+
78
+ # Add a prompt to ensure precise answers
79
+ full_prompt = f"""{context}
80
+
81
+ When answering, provide ONLY the precise answer requested.
82
+ Do not include explanations, steps, reasoning, or additional text.
83
+ Be direct and specific. GAIA benchmark requires exact matching answers.
84
+ For example, if asked "What is the capital of France?", respond simply with "Paris".
85
+ """
86
+
87
+ # Run the agent with the question
88
+ answer = self.agent.run(full_prompt)
89
+
90
+ # Clean up the answer to ensure it's in the expected format
91
+ # Remove common prefixes that models often add
92
+ answer = self._clean_answer(answer)
93
+
94
+ if self.verbose:
95
+ print(f"Generated answer: {answer}")
96
+
97
+ return answer
98
+ except Exception as e:
99
+ error_msg = f"Error answering question: {e}"
100
+ if self.verbose:
101
+ print(error_msg)
102
+ return error_msg
103
+
104
+ def _clean_answer(self, answer: any) -> str:
105
+ """
106
+ Clean up the answer to remove common prefixes and formatting
107
+ that models often add but that can cause exact match failures.
108
+
109
+ Args:
110
+ answer: The raw answer from the model
111
+
112
+ Returns:
113
+ The cleaned answer as a string
114
+ """
115
+ # Convert non-string types to strings
116
+ if not isinstance(answer, str):
117
+ # Handle numeric types (float, int)
118
+ if isinstance(answer, float):
119
+ # Format floating point numbers properly
120
+ # Check if it's an integer value in float form (e.g., 12.0)
121
+ if answer.is_integer():
122
+ formatted_answer = str(int(answer))
123
+ else:
124
+ # For currency values that might need formatting
125
+ if abs(answer) >= 1000:
126
+ formatted_answer = f"${answer:,.2f}"
127
+ else:
128
+ formatted_answer = str(answer)
129
+ return formatted_answer
130
+ elif isinstance(answer, int):
131
+ return str(answer)
132
+ else:
133
+ # For any other type
134
+ return str(answer)
135
+
136
+ # Now we know answer is a string, so we can safely use string methods
137
+ # Normalize whitespace
138
+ answer = answer.strip()
139
+
140
+ # Remove common prefixes and formatting that models add
141
+ prefixes_to_remove = [
142
+ "The answer is ",
143
+ "Answer: ",
144
+ "Final answer: ",
145
+ "The result is ",
146
+ "To answer this question: ",
147
+ "Based on the information provided, ",
148
+ "According to the information: ",
149
+ ]
150
+
151
+ for prefix in prefixes_to_remove:
152
+ if answer.startswith(prefix):
153
+ answer = answer[len(prefix):].strip()
154
+
155
+ # Remove quotes if they wrap the entire answer
156
+ if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
157
+ answer = answer[1:-1].strip()
158
+
159
+ return answer
160
+
161
 
162
  def run_and_submit_all( profile: gr.OAuthProfile | None):
163
  """
 
185
  print(f"Error instantiating agent: {e}")
186
  return f"Error initializing agent: {e}", None
187
  # 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)
188
+ agent_code = f"https://github.com/ssgrummons/huggingface_final_assignment"
189
  print(agent_code)
190
 
191
  # 2. Fetch Questions
 
216
  for item in questions_data:
217
  task_id = item.get("task_id")
218
  question_text = item.get("question")
219
+ files = item.get("file_name")
220
  if not task_id or question_text is None:
221
  print(f"Skipping item with missing task_id or question: {item}")
222
  continue
223
  try:
224
+ if files is None or files == '':
225
+ print(files)
226
+ submitted_answer = agent(question_text)
227
+ else:
228
+ submitted_answer = agent(question_text, task_id)
229
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
230
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
231
  except Exception as e:
 
291
  gr.Markdown(
292
  """
293
  **Instructions:**
 
294
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
295
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
296
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
297
  ---
298
  **Disclaimers:**
299
  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).
 
314
  outputs=[status_output, results_table]
315
  )
316
 
317
+ import sys
318
+ from pathlib import Path
319
+
320
+ class Tee:
321
+ def __init__(self, file_path):
322
+ log_path = Path(file_path)
323
+ log_path.parent.mkdir(parents=True, exist_ok=True)
324
+ self.terminal_stdout = sys.__stdout__
325
+ self.terminal_stderr = sys.__stderr__
326
+ self.log = open(log_path, "a")
327
+
328
+ def write(self, message):
329
+ self.terminal_stdout.write(message)
330
+ self.log.write(message)
331
+
332
+ def flush(self):
333
+ self.terminal_stdout.flush()
334
+ self.log.flush()
335
+
336
+ def isatty(self):
337
+ return self.terminal_stdout.isatty()
338
+
339
+
340
  if __name__ == "__main__":
341
+
342
+ # Redirect stdout and stderr
343
+ log_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
344
+ log_file = f"./logs/output_{log_timestamp}.log"
345
+ tee = Tee(log_file)
346
+ sys.stdout = tee
347
+ sys.stderr = tee
348
+
349
  print("\n" + "-"*30 + " App Starting " + "-"*30)
350
  # Check for SPACE_HOST and SPACE_ID at startup for information
351
  space_host_startup = os.getenv("SPACE_HOST")