FD900 commited on
Commit
de0f4f4
·
verified ·
1 Parent(s): 4adf070

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -238
app.py DELETED
@@ -1,238 +0,0 @@
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")