ghanemfaouri commited on
Commit
f9dd5ed
·
verified ·
1 Parent(s): ce2ebf0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -181
app.py CHANGED
@@ -5,6 +5,9 @@ import pandas as pd
5
  import re
6
  from openai import OpenAI
7
  from duckduckgo_search import DDGS
 
 
 
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -12,20 +15,23 @@ GAIA_SYSTEM_PROMPT = """
12
  You are an expert at solving GAIA benchmark questions. Follow these rules:
13
  1. Think step-by-step before answering
14
  2. Format answers EXACTLY as required:
15
- - Numbers: Plain digits without commas/units (e.g., 1500000)
16
  - Strings: Minimal words, no articles/abbreviations
17
  - Lists: Comma-separated values without spaces
18
- - Multiple choice: Single uppercase letter (e.g., A)
19
  3. For calculations, show your work then box the final answer
20
  4. When uncertain, search online for verification
21
  5. ALWAYS end with: FINAL ANSWER: [Your Answer]
22
  """
23
 
24
- # --- Enhanced Agent Definition ---
25
- class GaiaAgent:
26
  def __init__(self):
27
- print("GaiaAgent initialized")
28
  self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
 
29
  self.answer_patterns = [
30
  r"FINAL ANSWER:\s*(.+)",
31
  r"Final Answer:\s*(.+)",
@@ -34,7 +40,7 @@ class GaiaAgent:
34
  ]
35
 
36
  def web_search(self, query: str, max_results: int = 3) -> str:
37
- """Perform web search and return results as string"""
38
  try:
39
  with DDGS() as ddgs:
40
  results = [r for r in ddgs.text(query, max_results=max_results)]
@@ -43,33 +49,63 @@ class GaiaAgent:
43
  print(f"Search error: {str(e)}")
44
  return ""
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def __call__(self, question: str) -> str:
47
- """Process a question and return formatted answer"""
48
  print(f"Processing: {question[:60]}...")
49
 
50
- # Step 1: Perform web search if needed
 
 
 
 
 
 
 
 
 
 
 
 
51
  needs_search = any(word in question.lower() for word in
52
- ["current", "recent", "today", "latest", "who is", "what is"])
53
- search_results = ""
 
54
  if needs_search:
55
- search_query = f"{question} -site:reddit.com -site:quora.com"
56
- search_results = self.web_search(search_query)
57
- if search_results:
58
- print(f"Found {len(search_results.splitlines())} search results")
59
 
60
- # Step 2: Generate prompt
61
  messages = [
62
  {"role": "system", "content": GAIA_SYSTEM_PROMPT},
63
  {"role": "user", "content": question}
64
  ]
65
 
66
- if search_results:
67
- messages.insert(1, {
68
- "role": "system",
69
- "content": f"Search Results:\n{search_results}"
70
- })
71
 
72
- # Step 3: Get model response
73
  try:
74
  response = self.client.chat.completions.create(
75
  model="gpt-4-turbo",
@@ -77,174 +113,86 @@ class GaiaAgent:
77
  temperature=0.1,
78
  max_tokens=500
79
  )
80
- raw_answer = response.choices[0].message.content
81
-
82
- # Step 4: Extract final answer
83
- final_answer = self.extract_final_answer(raw_answer)
84
- print(f"Final answer: {final_answer}")
85
- return final_answer
86
  except Exception as e:
87
  print(f"GPT error: {str(e)}")
88
  return "Error: Could not generate answer"
89
-
90
- def extract_final_answer(self, response: str) -> str:
91
- """Robust extraction of final answer from response"""
92
- # Look for explicit answer markers
93
- for pattern in self.answer_patterns:
94
- match = re.search(pattern, response, re.IGNORECASE)
95
- if match:
96
- return match.group(1).strip()
97
-
98
- # Fallback: Last line extraction
99
- lines = response.strip().split('\n')
100
- if lines:
101
- return lines[-1].strip()
102
- return response.strip()
103
-
104
- # --- Updated Submission Function ---
105
- def run_and_submit_all(profile: gr.OAuthProfile | None):
106
- """
107
- Fetches all questions, runs the GaiaAgent on them, submits all answers,
108
- and displays the results.
109
- """
110
- # --- Determine HF Space Runtime URL and Repo URL ---
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.")
118
- return "Please Login to Hugging Face with the button.", None
119
 
120
- api_url = DEFAULT_API_URL
121
- questions_url = f"{api_url}/questions"
122
- submit_url = f"{api_url}/submit"
123
-
124
- # 1. Instantiate Agent
125
- try:
126
- agent = GaiaAgent()
127
- except Exception as e:
128
- print(f"Error instantiating agent: {e}")
129
- return f"Error initializing agent: {e}", None
130
-
131
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
132
- print(agent_code)
133
-
134
- # 2. Fetch Questions
135
- print(f"Fetching questions from: {questions_url}")
136
- try:
137
- response = requests.get(questions_url, timeout=15)
138
- response.raise_for_status()
139
- questions_data = response.json()
140
- if not questions_data:
141
- print("Fetched questions list is empty.")
142
- return "Fetched questions list is empty or invalid format.", None
143
- print(f"Fetched {len(questions_data)} questions.")
144
- except requests.exceptions.RequestException as e:
145
- print(f"Error fetching questions: {e}")
146
- return f"Error fetching questions: {e}", None
147
- except Exception as e:
148
- print(f"An unexpected error occurred fetching questions: {e}")
149
- return f"An unexpected error occurred fetching questions: {e}", None
150
-
151
- # 3. Run your Agent
152
- results_log = []
153
- answers_payload = []
154
- print(f"Running agent on {len(questions_data)} questions...")
155
- for item in questions_data:
156
- task_id = item.get("task_id")
157
- question_text = item.get("question")
158
- if not task_id or question_text is None:
159
- print(f"Skipping item with missing task_id or question: {item}")
160
- continue
161
  try:
162
- submitted_answer = agent(question_text)
163
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
164
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
165
- except Exception as e:
166
- print(f"Error running agent on task {task_id}: {e}")
167
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
168
-
169
- if not answers_payload:
170
- print("Agent did not produce any answers to submit.")
171
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
172
-
173
- # 4. Prepare Submission
174
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
175
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
176
- print(status_update)
177
 
178
- # 5. Submit
179
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
180
- try:
181
- response = requests.post(submit_url, json=submission_data, timeout=60)
182
- response.raise_for_status()
183
- result_data = response.json()
184
- final_status = (
185
- f"Submission Successful!\n"
186
- f"User: {result_data.get('username')}\n"
187
- f"Overall Score: {result_data.get('score', 'N/A')}% "
188
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
189
- f"Message: {result_data.get('message', 'No message received.')}"
190
- )
191
- print("Submission successful.")
192
- results_df = pd.DataFrame(results_log)
193
- return final_status, results_df
194
- except requests.exceptions.HTTPError as e:
195
- error_detail = f"Server responded with status {e.response.status_code}."
196
  try:
197
- error_json = e.response.json()
198
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
 
 
 
 
199
  except:
200
- error_detail += f" Response: {e.response.text[:500]}"
201
- status_message = f"Submission Failed: {error_detail}"
202
- print(status_message)
203
- results_df = pd.DataFrame(results_log)
204
- return status_message, results_df
205
- except Exception as e:
206
- status_message = f"An unexpected error occurred during submission: {e}"
207
- print(status_message)
208
- results_df = pd.DataFrame(results_log)
209
- return status_message, results_df
210
-
211
- # --- Build Gradio Interface using Blocks ---
212
- with gr.Blocks() as demo:
213
- gr.Markdown("# GAIA Benchmark Agent")
214
- gr.Markdown(
215
- "This agent is optimized for the GAIA benchmark. Log in with your Hugging Face account, "
216
- "then click 'Run Evaluation & Submit All Answers' to test against 20 questions."
217
- )
218
-
219
- gr.LoginButton()
220
-
221
- run_button = gr.Button("Run Evaluation & Submit All Answers")
222
-
223
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
224
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
225
-
226
- run_button.click(
227
- fn=run_and_submit_all,
228
- outputs=[status_output, results_table]
229
- )
230
-
231
- if __name__ == "__main__":
232
- print("\n" + "-"*30 + " GAIA Agent Starting " + "-"*30)
233
- space_host_startup = os.getenv("SPACE_HOST")
234
- space_id_startup = os.getenv("SPACE_ID")
235
 
236
- if space_host_startup:
237
- print(f"✅ SPACE_HOST found: {space_host_startup}")
238
- print(f" Runtime URL: https://{space_host_startup}.hf.space")
239
- else:
240
- print("ℹ️ SPACE_HOST environment variable not found (running locally?)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
- if space_id_startup:
243
- print(f"✅ SPACE_ID found: {space_id_startup}")
244
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
245
- else:
246
- print("ℹ️ SPACE_ID environment variable not found (running locally?)")
 
 
 
 
 
 
 
247
 
248
- print("-"*(60 + len(" GAIA Agent Starting ")) + "\n")
249
- print("Launching Gradio Interface...")
250
- demo.launch(debug=True, share=False)
 
5
  import re
6
  from openai import OpenAI
7
  from duckduckgo_search import DDGS
8
+ import wikipediaapi
9
+ from pytube import YouTube
10
+ import whisper
11
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
15
  You are an expert at solving GAIA benchmark questions. Follow these rules:
16
  1. Think step-by-step before answering
17
  2. Format answers EXACTLY as required:
18
+ - Numbers: Plain digits without commas/units
19
  - Strings: Minimal words, no articles/abbreviations
20
  - Lists: Comma-separated values without spaces
21
+ - Multiple choice: Single uppercase letter
22
  3. For calculations, show your work then box the final answer
23
  4. When uncertain, search online for verification
24
  5. ALWAYS end with: FINAL ANSWER: [Your Answer]
25
  """
26
 
27
+ class EnhancedGaiaAgent:
 
28
  def __init__(self):
29
+ print("Initializing Enhanced GAIA Agent")
30
  self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
31
+ self.wiki = wikipediaapi.Wikipedia('en')
32
+ self.model = whisper.load_model("base")
33
+
34
+ # Answer extraction patterns
35
  self.answer_patterns = [
36
  r"FINAL ANSWER:\s*(.+)",
37
  r"Final Answer:\s*(.+)",
 
40
  ]
41
 
42
  def web_search(self, query: str, max_results: int = 3) -> str:
43
+ """Perform web search with enhanced filtering"""
44
  try:
45
  with DDGS() as ddgs:
46
  results = [r for r in ddgs.text(query, max_results=max_results)]
 
49
  print(f"Search error: {str(e)}")
50
  return ""
51
 
52
+ def get_wikipedia(self, topic: str) -> str:
53
+ """Get clean Wikipedia content"""
54
+ try:
55
+ page = self.wiki.page(topic)
56
+ return page.summary[:2000] if page.exists() else ""
57
+ except:
58
+ return ""
59
+
60
+ def transcribe_audio(self, audio_path: str) -> str:
61
+ """Transcribe audio using Whisper"""
62
+ try:
63
+ result = self.model.transcribe(audio_path)
64
+ return result["text"]
65
+ except Exception as e:
66
+ print(f"Transcription error: {str(e)}")
67
+ return ""
68
+
69
+ def extract_youtube_info(self, url: str) -> str:
70
+ """Get video metadata"""
71
+ try:
72
+ yt = YouTube(url)
73
+ return f"Title: {yt.title}\nLength: {yt.length}s"
74
+ except:
75
+ return ""
76
+
77
  def __call__(self, question: str) -> str:
78
+ """Enhanced question answering pipeline"""
79
  print(f"Processing: {question[:60]}...")
80
 
81
+ # Specialized handlers
82
+ if "youtube.com/watch" in question.lower():
83
+ return self.handle_youtube_question(question)
84
+ if "mp3" in question.lower() or "audio" in question.lower():
85
+ return self.handle_audio_question(question)
86
+ if "wikipedia" in question.lower():
87
+ return self.handle_wikipedia_question(question)
88
+
89
+ # General question handling
90
+ return self.handle_general_question(question)
91
+
92
+ def handle_general_question(self, question: str) -> str:
93
+ """Process standard questions"""
94
  needs_search = any(word in question.lower() for word in
95
+ ["current", "recent", "today", "latest", "who is", "what is"])
96
+
97
+ context = ""
98
  if needs_search:
99
+ context = self.web_search(question)
 
 
 
100
 
 
101
  messages = [
102
  {"role": "system", "content": GAIA_SYSTEM_PROMPT},
103
  {"role": "user", "content": question}
104
  ]
105
 
106
+ if context:
107
+ messages.insert(1, {"role": "system", "content": f"Search Results:\n{context}"})
 
 
 
108
 
 
109
  try:
110
  response = self.client.chat.completions.create(
111
  model="gpt-4-turbo",
 
113
  temperature=0.1,
114
  max_tokens=500
115
  )
116
+ return self.extract_final_answer(response.choices[0].message.content)
 
 
 
 
 
117
  except Exception as e:
118
  print(f"GPT error: {str(e)}")
119
  return "Error: Could not generate answer"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
+ def handle_youtube_question(self, question: str) -> str:
122
+ """Process YouTube video questions"""
123
+ url = re.search(r"(https?://[^\s]+)", question).group(1)
124
+ video_info = self.extract_youtube_info(url)
125
+
126
+ messages = [
127
+ {"role": "system", "content": GAIA_SYSTEM_PROMPT},
128
+ {"role": "system", "content": f"Video Info:\n{video_info}"},
129
+ {"role": "user", "content": question}
130
+ ]
131
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  try:
133
+ response = self.client.chat.completions.create(
134
+ model="gpt-4-vision-preview",
135
+ messages=messages,
136
+ temperature=0.1
137
+ )
138
+ return self.extract_final_answer(response.choices[0].message.content)
139
+ except:
140
+ return "Error: Could not process video"
 
 
 
 
 
 
 
141
 
142
+ def handle_audio_question(self, question: str) -> str:
143
+ """Process audio questions"""
144
+ audio_path = "temp_audio.mp3" # Assume file is saved here
145
+ transcript = self.transcribe_audio(audio_path)
146
+
147
+ messages = [
148
+ {"role": "system", "content": GAIA_SYSTEM_PROMPT},
149
+ {"role": "system", "content": f"Transcript:\n{transcript}"},
150
+ {"role": "user", "content": question}
151
+ ]
152
+
 
 
 
 
 
 
 
153
  try:
154
+ response = self.client.chat.completions.create(
155
+ model="gpt-4-turbo",
156
+ messages=messages,
157
+ temperature=0.1
158
+ )
159
+ return self.extract_final_answer(response.choices[0].message.content)
160
  except:
161
+ return "Error: Could not process audio"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
+ def handle_wikipedia_question(self, question: str) -> str:
164
+ """Process Wikipedia-specific questions"""
165
+ topic = re.search(r"about (.*?)(?:that|which)", question, re.IGNORECASE)
166
+ wiki_content = self.get_wikipedia(topic.group(1) if topic else ""
167
+
168
+ messages = [
169
+ {"role": "system", "content": GAIA_SYSTEM_PROMPT},
170
+ {"role": "system", "content": f"Wikipedia Context:\n{wiki_content}"},
171
+ {"role": "user", "content": question}
172
+ ]
173
+
174
+ try:
175
+ response = self.client.chat.completions.create(
176
+ model="gpt-4-turbo",
177
+ messages=messages,
178
+ temperature=0.1
179
+ )
180
+ return self.extract_final_answer(response.choices[0].message.content)
181
+ except:
182
+ return "Error: Could not process Wikipedia query"
183
 
184
+ def extract_final_answer(self, response: str) -> str:
185
+ """Robust answer extraction"""
186
+ for pattern in self.answer_patterns:
187
+ match = re.search(pattern, response, re.IGNORECASE)
188
+ if match:
189
+ answer = match.group(1).strip()
190
+ # Clean formatting
191
+ answer = re.sub(r"[^a-zA-Z0-9,. ]", "", answer)
192
+ return answer[:200] # Limit length
193
+
194
+ lines = response.strip().split('\n')
195
+ return lines[-1].strip() if lines else "No answer found"
196
 
197
+ # [Rest of your existing Gradio and submission code remains unchanged]
198
+ # Just replace BasicAgent with EnhancedGaiaAgent in run_and_submit_all()