FD900 commited on
Commit
c8685d2
·
verified ·
1 Parent(s): f5eb447

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -76
app.py CHANGED
@@ -1,98 +1,238 @@
1
- from agent import BasicAgent
2
-
3
  import os
4
  import gradio as gr
5
  import requests
 
6
  import pandas as pd
 
 
 
 
 
7
 
 
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- def run_and_submit_all(profile: gr.OAuthProfile | None):
11
- space_id = os.getenv("SPACE_ID")
12
- if profile:
13
- username = f"{profile.username}"
14
- print(f"User logged in: {username}")
15
- else:
16
- print("User not logged in.")
17
- return "Please Login to Hugging Face with the button.", None
18
-
19
- api_url = DEFAULT_API_URL
20
- questions_url = f"{api_url}/questions"
21
- submit_url = f"{api_url}/submit"
22
-
23
- try:
24
- agent = BasicAgent()
25
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  print(f"Error instantiating agent: {e}")
27
  return f"Error initializing agent: {e}", None
28
-
29
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
30
  print(agent_code)
31
 
32
- try:
33
- response = requests.get(questions_url, timeout=15)
34
- response.raise_for_status()
35
- questions_data = response.json()
36
- if not questions_data:
37
- return "Fetched questions list is empty or invalid format.", None
38
- print(f"Fetched {len(questions_data)} questions.")
39
- except requests.exceptions.RequestException as e:
40
- return f"Error fetching questions: {e}", None
41
-
42
- results_log = []
43
- answers_payload = []
44
- print(f"Running agent on {len(questions_data)} questions...")
45
  for item in questions_data:
46
  task_id = item.get("task_id")
47
  question_text = item.get("question")
 
48
  if not task_id or question_text is None:
 
49
  continue
50
  try:
51
- submitted_answer = agent(question_text)
 
 
 
 
52
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
53
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
54
  except Exception as e:
55
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
56
-
57
- if not answers_payload:
58
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
59
-
60
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
61
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
62
- try:
63
- response = requests.post(submit_url, json=submission_data, timeout=60)
64
- response.raise_for_status()
65
- result_data = response.json()
66
- final_status = (
67
- f"Submission Successful!\n"
68
- f"User: {result_data.get('username')}\n"
69
- f"Overall Score: {result_data.get('score', 'N/A')}% "
70
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
71
- f"Message: {result_data.get('message', 'No message received.')}"
72
- )
73
- results_df = pd.DataFrame(results_log)
74
- return final_status, results_df
75
- except requests.exceptions.RequestException as e:
76
- status_message = f"Submission Failed: {e}"
77
- results_df = pd.DataFrame(results_log)
78
- return status_message, results_df
79
-
80
- with gr.Blocks() as demo:
81
- gr.Markdown("# GAIA Agent Evaluation")
82
- gr.Markdown("""
83
- **Instructions:**
84
- 1. Clone this Space and modify the agent logic in `agent.py`.
85
- 2. Log in to Hugging Face below.
86
- 3. Click "Run Evaluation & Submit All Answers" to evaluate.
87
- """)
88
-
89
- gr.LoginButton()
90
- run_button = gr.Button("Run Evaluation & Submit All Answers")
91
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
92
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
93
-
94
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
95
 
96
  if __name__ == "__main__":
97
- print("Launching Gradio Interface for Boosted GAIA Agent...")
98
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+
5
  import pandas as pd
6
+ import os
7
+ from agents import manager_agent
8
+ from datetime import datetime
9
+ from typing import Optional
10
+ import time
11
 
12
+ # (Keep Constants as is)
13
+ # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
+
17
+
18
+ class BasicAgent:
19
+ def __init__(self):
20
+ print("BasicAgent initialized.")
21
+ self.agent = manager_agent
22
+ self.verbose = True
23
+
24
+ def __call__(self, question: str, files: list[str] = None) -> str:
25
+ print(f"Agent received question: {question[:50]}... with files: {files}")
26
+ result = self.answer_question(question, files)
27
+ print(f"Agent returning answer: {result}")
28
+ #time.sleep(60)
29
+ return result
30
+ def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str:
31
+ """
32
+ Process a GAIA benchmark question and return the answer
33
+
34
+ Args:
35
+ question: The question to answer
36
+ task_file_path: Optional path to a file associated with the question
37
+
38
+ Returns:
39
+ The answer to the question
40
+ """
41
+ try:
42
+ if self.verbose:
43
+ print(f"Processing question: {question}")
44
+ if task_file_path:
45
+ print(f"With associated file: {task_file_path}")
46
+
47
+ # Create a context with file information if available
48
+ context = question
49
+
50
+ # If there's a file, read it and include its content in the context
51
+ if task_file_path:
52
+ try:
53
+ context = f"""
54
+ Question: {question}
55
+
56
+ This question has an associated file. You can download the file from
57
+ {DEFAULT_API_URL}/files/{task_file_path}
58
+ using the download_file_from_url tool.
59
+
60
+ Analyze the file content above to answer the question.
61
+ """
62
+ except Exception as file_e:
63
+ context = f"""
64
+ Question: {question}
65
+
66
+ This question has an associated file at path: {task_file_path}
67
+ However, there was an error reading the file: {file_e}
68
+ You can still try to answer the question based on the information provided.
69
+ """
70
+
71
+ # Check for special cases that need specific formatting
72
+ # Reversed text questions
73
+ if question.startswith(".") or ".rewsna eht sa" in question:
74
+ context = f"""
75
+ This question appears to be in reversed text. Here's the reversed version:
76
+ {question[::-1]}
77
+
78
+ Now answer the question above. Remember to format your answer exactly as requested.
79
+ """
80
+
81
+ # Add a prompt to ensure precise answers
82
+ full_prompt = f"""{context}
83
+
84
+ When answering, provide ONLY the precise answer requested.
85
+ Do not include explanations, steps, reasoning, or additional text.
86
+ Be direct and specific. GAIA benchmark requires exact matching answers.
87
+ For example, if asked "What is the capital of France?", respond simply with "Paris".
88
+ """
89
+
90
+ # Run the agent with the question
91
+ answer = self.agent.run(full_prompt)
92
+
93
+ # Clean up the answer to ensure it's in the expected format
94
+ # Remove common prefixes that models often add
95
+ answer = self._clean_answer(answer)
96
+
97
+ if self.verbose:
98
+ print(f"Generated answer: {answer}")
99
+
100
+ return answer
101
+ except Exception as e:
102
+ error_msg = f"Error answering question: {e}"
103
+ if self.verbose:
104
+ print(error_msg)
105
+ return error_msg
106
+
107
+ def _clean_answer(self, answer: any) -> str:
108
+ """
109
+ Clean up the answer to remove common prefixes and formatting
110
+ that models often add but that can cause exact match failures.
111
+
112
+ Args:
113
+ answer: The raw answer from the model
114
+
115
+ Returns:
116
+ The cleaned answer as a string
117
+ """
118
+ # Convert non-string types to strings
119
+ if not isinstance(answer, str):
120
+ # Handle numeric types (float, int)
121
+ if isinstance(answer, float):
122
+ # Format floating point numbers properly
123
+ # Check if it's an integer value in float form (e.g., 12.0)
124
+ if answer.is_integer():
125
+ formatted_answer = str(int(answer))
126
+ else:
127
+ # For currency values that might need formatting
128
+ if abs(answer) >= 1000:
129
+ formatted_answer = f"${answer:,.2f}"
130
+ else:
131
+ formatted_answer = str(answer)
132
+ return formatted_answer
133
+ elif isinstance(answer, int):
134
+ return str(answer)
135
+ else:
136
+ # For any other type
137
+ return str(answer)
138
+
139
+ # Now we know answer is a string, so we can safely use string methods
140
+ # Normalize whitespace
141
+ answer = answer.strip()
142
+
143
+ # Remove common prefixes and formatting that models add
144
+ prefixes_to_remove = [
145
+ "The answer is ",
146
+ "Answer: ",
147
+ "Final answer: ",
148
+ "The result is ",
149
+ "To answer this question: ",
150
+ "Based on the information provided, ",
151
+ "According to the information: ",
152
+ ]
153
+
154
+ for prefix in prefixes_to_remove:
155
+ if answer.startswith(prefix):
156
+ answer = answer[len(prefix):].strip()
157
+
158
+ # Remove quotes if they wrap the entire answer
159
+ if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
160
+ answer = answer[1:-1].strip()
161
+
162
+ return answer
163
+
164
+
165
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
166
+ """
167
  print(f"Error instantiating agent: {e}")
168
  return f"Error initializing agent: {e}", None
169
+ # 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)
170
+ agent_code = f"https://github.com/ssgrummons/huggingface_final_assignment"
171
  print(agent_code)
172
 
173
+ # 2. Fetch Questions
 
 
 
 
 
 
 
 
 
 
 
 
174
  for item in questions_data:
175
  task_id = item.get("task_id")
176
  question_text = item.get("question")
177
+ files = item.get("file_name")
178
  if not task_id or question_text is None:
179
+ print(f"Skipping item with missing task_id or question: {item}")
180
  continue
181
  try:
182
+ if files is None or files == '':
183
+ print(files)
184
+ submitted_answer = agent(question_text)
185
+ else:
186
+ submitted_answer = agent(question_text, task_id)
187
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
188
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
189
  except Exception as e:
190
+ gr.Markdown(
191
+ """
192
+ **Instructions:**
193
+
194
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
195
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
196
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
197
+
198
+ ---
199
+ **Disclaimers:**
200
+ 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).
201
+ outputs=[status_output, results_table]
202
+ )
203
+
204
+ import sys
205
+ from pathlib import Path
206
+
207
+ class Tee:
208
+ def __init__(self, file_path):
209
+ log_path = Path(file_path)
210
+ log_path.parent.mkdir(parents=True, exist_ok=True)
211
+ self.terminal_stdout = sys.__stdout__
212
+ self.terminal_stderr = sys.__stderr__
213
+ self.log = open(log_path, "a")
214
+
215
+ def write(self, message):
216
+ self.terminal_stdout.write(message)
217
+ self.log.write(message)
218
+
219
+ def flush(self):
220
+ self.terminal_stdout.flush()
221
+ self.log.flush()
222
+
223
+ def isatty(self):
224
+ return self.terminal_stdout.isatty()
225
+
 
 
 
 
226
 
227
  if __name__ == "__main__":
228
+
229
+ # Redirect stdout and stderr
230
+ log_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
231
+ log_file = f"./logs/output_{log_timestamp}.log"
232
+ tee = Tee(log_file)
233
+ sys.stdout = tee
234
+ sys.stderr = tee
235
+
236
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
237
+ # Check for SPACE_HOST and SPACE_ID at startup for information
238
+ space_host_startup = os.getenv("SPACE_HOST")