MickyWin22 commited on
Commit
31645f4
·
verified ·
1 Parent(s): 71251fa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +326 -0
app.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ import traceback
6
+ import time
7
+ import mimetypes
8
+ from tempfile import NamedTemporaryFile
9
+
10
+ # Import smol-agent and tool components
11
+ from smolagents import CodeAgent, LiteLLMModel, tool
12
+ from smolagents import DuckDuckGoSearchTool
13
+ from unstructured.partition.auto import partition
14
+
15
+ # Imports for advanced file processing
16
+ import speech_recognition as sr
17
+ from pydub import AudioSegment
18
+
19
+ # --- Constants ---
20
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
+
22
+ # --- Constants ---
23
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
+
25
+ # --- Tool Definition (Upgraded for Full Multimodality with pydub) ---
26
+ @tool
27
+ def file_reader(file_path: str) -> str:
28
+ """
29
+ Reads and analyzes the content of a file and returns relevant text-based information.
30
+ Supports:
31
+ - Text files (PDF, TXT, CSV)
32
+ - Images (PNG, JPG) with OCR
33
+ - Audio (MP3, WAV) via speech recognition
34
+ - Video (MP4, MOV) via speech recognition on audio track
35
+ Can be used with a local file path or a web URL.
36
+
37
+ Args:
38
+ file_path (str): The local path or web URL of the file to be read.
39
+ Returns:
40
+ str: Extracted or transcribed content as text.
41
+ """
42
+ temp_file_path = None
43
+ audio_temp_path = None
44
+ try:
45
+ # Download the file if it's a URL
46
+ if file_path.startswith("http://") or file_path.startswith("https://"):
47
+ temp_file_path = NamedTemporaryFile(delete=False).name
48
+ response = requests.get(file_path, timeout=20)
49
+ response.raise_for_status()
50
+ with open(temp_file_path, "wb") as f:
51
+ f.write(response.content)
52
+ local_path = temp_file_path
53
+ else:
54
+ local_path = file_path
55
+
56
+ mime_type, _ = mimetypes.guess_type(local_path)
57
+ recognizer = sr.Recognizer()
58
+
59
+ if mime_type:
60
+ # Handle audio files
61
+ if mime_type.startswith("audio/"):
62
+ with sr.AudioFile(local_path) as source:
63
+ audio = recognizer.record(source)
64
+ return recognizer.recognize_whisper(audio)
65
+
66
+ # Handle video files by extracting audio with pydub
67
+ elif mime_type.startswith("video/"):
68
+ with NamedTemporaryFile(suffix=".wav", delete=False) as audio_temp:
69
+ audio_temp_path = audio_temp.name
70
+
71
+ # Extract audio using pydub
72
+ video_audio = AudioSegment.from_file(local_path, format=mime_type.split('/')[1])
73
+ video_audio.export(audio_temp_path, format="wav")
74
+
75
+ with sr.AudioFile(audio_temp_path) as source:
76
+ audio = recognizer.record(source)
77
+
78
+ return recognizer.recognize_whisper(audio)
79
+
80
+ # Default to handling text and images with OCR if not audio/video
81
+ elements = partition(local_path)
82
+ return "\n\n".join([str(el) for el in elements])
83
+
84
+ except Exception as e:
85
+ return f"Error reading or processing file '{file_path}': {e}"
86
+ finally:
87
+ # Clean up the downloaded file if it exists
88
+ if temp_file_path and os.path.exists(temp_file_path):
89
+ os.remove(temp_file_path)
90
+ # Clean up the temporary audio file
91
+ if audio_temp_path and os.path.exists(audio_temp_path):
92
+ os.remove(audio_temp_path)
93
+
94
+
95
+
96
+ # --- Agent Class (Updated with More Powerful Model and Tools) ---
97
+ class GaiaSmolAgent:
98
+ def __init__(self):
99
+ """
100
+ Initializes the optimized agent.
101
+ Now uses a more powerful model and the agent's native conversation memory.
102
+ """
103
+ print("Initializing Optimized GaiaSmolAgent...")
104
+ api_key = os.getenv("GEMINI_API_KEY")
105
+ if not api_key:
106
+ raise ValueError("API key 'GEMINI_API_KEY' not found in environment secrets.")
107
+
108
+ # Use a more powerful, "clever" model for better reasoning.
109
+ model = LiteLLMModel(
110
+ model_id="gemini/gemini-1.5-pro-latest",
111
+ api_key=api_key,
112
+ temperature=0.0,
113
+ timeout=120.0, # Add a timeout to prevent hanging
114
+ )
115
+
116
+ # --- CHANGE 1: ENHANCED SYSTEM PROMPT ---
117
+ # A more detailed prompt that guides the agent on how to handle GAIA-specific challenges,
118
+ # such as precise data extraction, calculations, and structured reasoning.
119
+ self.system_prompt = """
120
+ You are an expert-level research assistant AI, specifically designed to solve challenging questions from the GAIA benchmark. Your goal is to provide a precise and accurate final answer by meticulously following a step-by-step plan.
121
+
122
+ **Available Tools:**
123
+ - `duck_duck_go_search(query: str) -> str`: Use this for web searches to find information, URLs, facts, etc.
124
+ - `file_reader(file_path: str) -> str`: Use this to read content from local files or web URLs. It handles text, PDFs, images (OCR), audio, and video.
125
+
126
+ **Your Thought Process & Execution Strategy:**
127
+ 1. **Analyze the Question:** First, break down the user's question to fully understand all its components, constraints, and the exact type of information required for the answer (e.g., a number, a date, a name).
128
+ 2. **Formulate a Step-by-Step Plan:** Before using any tools, you MUST outline your plan in your thoughts. For example: "Step 1: Search for the document URL. Step 2: Use the file_reader to read the document. Step 3: Extract the specific data point. Step 4: Perform calculation if needed. Step 5: Provide the final answer."
129
+ 3. **Execute and Verify:** Execute your plan one step at a time. After each tool call, review the output. Verify if the information obtained is sufficient and accurate. If a step fails or the result is not what you expected, REVISE your plan.
130
+ 4. **Synthesize the Answer:** Once you have gathered and verified all necessary information, formulate the final answer. Use the Python interpreter for any calculations, data sorting, or text processing to ensure accuracy.
131
+
132
+ **CRITICAL INSTRUCTIONS:**
133
+ - **Precision is Key:** Pay close attention to the requested format of the final answer. If a question asks for a number, your final answer must be only that number.
134
+ - **Code for Calculations:** ALWAYS use the Python interpreter for any calculations, date comparisons, or data manipulation. Do not perform calculations in your head.
135
+ - **Autonomous Operation:** You must work autonomously. Make the most logical deduction based on the information you gather. Do not ask for clarification.
136
+ - **Final Answer:** Your final output MUST be a single call to the `final_answer(answer: str)` function with the precise answer.
137
+ """
138
+
139
+ # Initialize the agent with the updated file_reader tool and memory settings.
140
+ self.agent = CodeAgent(
141
+ model=model,
142
+ tools=[file_reader, DuckDuckGoSearchTool()],
143
+ add_base_tools=True, # Provides python interpreter and final_answer
144
+
145
+ # --- CHANGE 2: MORE REACTIVE PLANNING ---
146
+ # By setting planning_interval=1, the agent re-evaluates its plan
147
+ # after every single tool execution. This allows it to immediately course-correct
148
+ # based on new information, which is vital for complex, multi-step tasks.
149
+ planning_interval=1
150
+ )
151
+
152
+ print("Optimized GaiaSmolAgent initialized successfully with enhanced prompt and reactive planning.")
153
+
154
+ def __call__(self, question: str, reset_memory: bool = False) -> str:
155
+ """
156
+ Directly runs the agent to generate and execute a plan to answer the question.
157
+ It leverages the agent's built-in memory, controlled by the `reset` parameter.
158
+
159
+ Args:
160
+ question (str): The user's question.
161
+ reset_memory (bool): If True, the agent's conversation memory will be cleared
162
+ before running. Maps to the agent's `reset` parameter.
163
+ """
164
+ print(f"Optimized Agent received question: {question[:100]}...")
165
+
166
+ try:
167
+ # Combine the system prompt with the current question. The agent will handle the history.
168
+ full_prompt = f"{self.system_prompt}\n\nCURRENT TASK:\nUser Question: \"{question}\""
169
+
170
+ # Use the agent's `reset` parameter to control conversation memory.
171
+ # `reset=False` keeps the memory from previous calls.
172
+ final_answer = self.agent.run(full_prompt, reset=reset_memory)
173
+ except Exception as e:
174
+ print(f"FATAL AGENT ERROR: An exception occurred during agent execution: {e}")
175
+ print(traceback.format_exc()) # Print full traceback for easier debugging
176
+ return f"FATAL AGENT ERROR: {e}"
177
+
178
+ print(f"Optimized Agent returning final answer: {final_answer}")
179
+ return str(final_answer)
180
+
181
+ # --- Main Application Logic (Unchanged) ---
182
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
183
+ """
184
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
185
+ and displays the results.
186
+ """
187
+ # --- Determine HF Space Runtime URL and Repo URL ---
188
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
189
+
190
+ if profile:
191
+ username= f"{profile.username}"
192
+ print(f"User logged in: {username}")
193
+ else:
194
+ print("User not logged in.")
195
+ return "Please Login to Hugging Face with the button.", None
196
+
197
+ api_url = DEFAULT_API_URL
198
+ questions_url = f"{api_url}/questions"
199
+ submit_url = f"{api_url}/submit"
200
+
201
+ # 1. Instantiate Agent ( modify this part to create your agent)
202
+ try:
203
+ agent = GaiaSmolAgent()
204
+ except Exception as e:
205
+ print(f"Error instantiating agent: {e}")
206
+ return f"Error initializing agent: {e}", None
207
+ # 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)
208
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
209
+ print(agent_code)
210
+
211
+ # 2. Fetch Questions
212
+ print(f"Fetching questions from: {questions_url}")
213
+ try:
214
+ response = requests.get(questions_url, timeout=15)
215
+ response.raise_for_status()
216
+ questions_data = response.json()
217
+ if not questions_data:
218
+ print("Fetched questions list is empty.")
219
+ return "Fetched questions list is empty or invalid format.", None
220
+ print(f"Fetched {len(questions_data)} questions.")
221
+ except requests.exceptions.RequestException as e:
222
+ print(f"Error fetching questions: {e}")
223
+ return f"Error fetching questions: {e}", None
224
+ except requests.exceptions.JSONDecodeError as e:
225
+ print(f"Error decoding JSON response from questions endpoint: {e}")
226
+ print(f"Response text: {response.text[:500]}")
227
+ return f"Error decoding server response for questions: {e}", None
228
+ except Exception as e:
229
+ print(f"An unexpected error occurred fetching questions: {e}")
230
+ return f"An unexpected error occurred fetching questions: {e}", None
231
+
232
+ # 3. Run your Agent
233
+ results_log = []
234
+ answers_payload = []
235
+ print(f"Running agent on {len(questions_data)} questions...")
236
+ for item in questions_data:
237
+ task_id = item.get("task_id")
238
+ question_text = item.get("question")
239
+ if not task_id or question_text is None:
240
+ print(f"Skipping item with missing task_id or question: {item}")
241
+ continue
242
+ try:
243
+ submitted_answer = agent(question_text)
244
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
245
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
246
+ except Exception as e:
247
+ print(f"Error running agent on task {task_id}: {e}")
248
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
249
+
250
+ if not answers_payload:
251
+ print("Agent did not produce any answers to submit.")
252
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
253
+
254
+ # 4. Prepare Submission
255
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
256
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
257
+ print(status_update)
258
+
259
+ # 5. Submit
260
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
261
+ try:
262
+ response = requests.post(submit_url, json=submission_data, timeout=60)
263
+ response.raise_for_status()
264
+ result_data = response.json()
265
+ final_status = (
266
+ f"Submission Successful!\n"
267
+ f"User: {result_data.get('username')}\n"
268
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
269
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
270
+ f"Message: {result_data.get('message', 'No message received.')}"
271
+ )
272
+ print("Submission successful.")
273
+ results_df = pd.DataFrame(results_log)
274
+ return final_status, results_df
275
+ except requests.exceptions.HTTPError as e:
276
+ error_detail = f"Server responded with status {e.response.status_code}."
277
+ try:
278
+ error_json = e.response.json()
279
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
280
+ except requests.exceptions.JSONDecodeError:
281
+ error_detail += f" Response: {e.response.text[:500]}"
282
+ status_message = f"Submission Failed: {error_detail}"
283
+ print(status_message)
284
+ results_df = pd.DataFrame(results_log)
285
+ return status_message, results_df
286
+ except requests.exceptions.Timeout:
287
+ status_message = "Submission Failed: The request timed out."
288
+ print(status_message)
289
+ results_df = pd.DataFrame(results_log)
290
+ return status_message, results_df
291
+ except requests.exceptions.RequestException as e:
292
+ status_message = f"Submission Failed: Network error - {e}"
293
+ print(status_message)
294
+ results_df = pd.DataFrame(results_log)
295
+ return status_message, results_df
296
+ except Exception as e:
297
+ status_message = f"An unexpected error occurred during submission: {e}"
298
+ print(status_message)
299
+ results_df = pd.DataFrame(results_log)
300
+ return status_message, results_df
301
+
302
+
303
+ # --- Gradio Interface (Updated Instructions) ---
304
+ with gr.Blocks() as demo:
305
+ gr.Markdown("# GAIA Agent Evaluation Runner (smol-agent)")
306
+ gr.Markdown(
307
+ """
308
+ **Instructions:**
309
+ 1. Ensure you have added your **GEMINI API key** (as `GEMINI_API_KEY`) in the Space's secrets.
310
+ 2. Log in to your Hugging Face account using the button below.
311
+ 3. Click 'Run Evaluation & Submit All Answers' to run your agent and see the score.
312
+ """
313
+ )
314
+ gr.LoginButton()
315
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
316
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
317
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
318
+
319
+ run_button.click(
320
+ fn=run_and_submit_all,
321
+ outputs=[status_output, results_table]
322
+ )
323
+
324
+ if __name__ == "__main__":
325
+ print("Launching Gradio Interface for GAIA Agent Evaluation...")
326
+ demo.launch(debug=True, share=False)