Abbasid commited on
Commit
f97d9bf
·
verified ·
1 Parent(s): 6cdf45e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -83
app.py CHANGED
@@ -1,7 +1,9 @@
1
  """
2
  app.py
3
  This script provides the Gradio web interface to run the evaluation.
4
- This version properly handles multimodal inputs including images, videos, and audio.
 
 
5
  """
6
 
7
  import os
@@ -16,7 +18,7 @@ from agent import create_agent_executor
16
  # --- Constants ---
17
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
 
19
- # --- Helper function to parse the agent's output ---
20
  def parse_final_answer(agent_response: str) -> str:
21
  match = re.search(r"FINAL ANSWER:\s*(.*)", agent_response, re.IGNORECASE | re.DOTALL)
22
  if match: return match.group(1).strip()
@@ -24,74 +26,12 @@ def parse_final_answer(agent_response: str) -> str:
24
  if lines: return lines[-1].strip()
25
  return "Could not parse a final answer."
26
 
27
- def detect_file_type(url: str) -> str:
28
- """Detect the type of file from URL."""
29
- if not url:
30
- return "unknown"
31
-
32
- url_lower = url.lower()
33
-
34
- # Image extensions
35
- if any(ext in url_lower for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']):
36
- return "image"
37
-
38
- # Video extensions and YouTube
39
- if any(domain in url_lower for domain in ['youtube.com', 'youtu.be', 'vimeo.com']):
40
- return "youtube"
41
- if any(ext in url_lower for ext in ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm']):
42
- return "video"
43
-
44
- # Audio extensions
45
- if any(ext in url_lower for ext in ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a']):
46
- return "audio"
47
-
48
- # Try to detect from headers if possible
49
- try:
50
- response = requests.head(url, timeout=5)
51
- content_type = response.headers.get('content-type', '').lower()
52
-
53
- if 'image' in content_type:
54
- return "image"
55
- elif 'audio' in content_type:
56
- return "audio"
57
- elif 'video' in content_type:
58
- return "video"
59
- except:
60
- pass
61
-
62
- return "unknown"
63
 
64
- def create_enhanced_prompt(question_text: str, file_url: str = None) -> str:
65
- """Create an enhanced prompt that guides the agent to use appropriate tools."""
66
-
67
- if not file_url:
68
- return question_text
69
-
70
- file_type = detect_file_type(file_url)
71
-
72
- if file_type == "image":
73
- return f"""{question_text}
74
-
75
- [IMAGE ATTACHMENT]: {file_url}
76
- INSTRUCTION: There is an image attached to this question. You MUST use the 'describe_image' tool to analyze this image before answering the question."""
77
-
78
- elif file_type == "youtube":
79
- return f"""{question_text}
80
-
81
- [YOUTUBE VIDEO]: {file_url}
82
- INSTRUCTION: There is a YouTube video attached to this question. You MUST use the 'process_youtube_video' tool to analyze this video before answering the question."""
83
-
84
- elif file_type == "audio":
85
- return f"""{question_text}
86
-
87
- [AUDIO FILE]: {file_url}
88
- INSTRUCTION: There is an audio file attached to this question. You MUST use the 'process_audio_file' tool to analyze this audio before answering the question."""
89
-
90
- else:
91
- return f"""{question_text}
92
-
93
- [ATTACHMENT]: {file_url}
94
- INSTRUCTION: There is a file attachment. Analyze the URL and use the appropriate tool to process this content before answering the question."""
95
 
96
  def run_and_submit_all(profile: gr.OAuthProfile | None):
97
  """
@@ -138,20 +78,21 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
138
 
139
  print(f"\n--- Running Task {i+1}/{len(questions_data)} (ID: {task_id}) ---")
140
 
141
- # Get file URL if it exists
142
  file_url = item.get("file_url")
143
 
144
- # Create enhanced prompt that instructs the agent to use appropriate tools
145
- full_question_text = create_enhanced_prompt(question_text, file_url)
146
-
147
  if file_url:
148
- file_type = detect_file_type(file_url)
149
- print(f"File detected: {file_url} (Type: {file_type})")
 
 
150
 
151
- print(f"Enhanced Prompt for Agent:\n{full_question_text}")
152
 
153
  try:
154
- # Pass the enhanced question to the agent
155
  result = agent_executor.invoke({"messages": [("user", full_question_text)]})
156
 
157
  raw_answer = result['messages'][-1].content
@@ -165,7 +106,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
165
  "Task ID": task_id,
166
  "Question": question_text,
167
  "File URL": file_url or "None",
168
- "File Type": detect_file_type(file_url) if file_url else "None",
169
  "Submitted Answer": submitted_answer
170
  })
171
 
@@ -177,14 +117,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
177
  "Task ID": task_id,
178
  "Question": question_text,
179
  "File URL": file_url or "None",
180
- "File Type": detect_file_type(file_url) if file_url else "None",
181
  "Submitted Answer": error_msg
182
  })
183
 
184
  if not answers_payload:
185
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
186
 
187
- # 4. Prepare and 5. Submit
188
  submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
189
  print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")
190
  try:
@@ -200,7 +139,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
200
  print(status_message)
201
  return status_message, pd.DataFrame(results_log)
202
 
203
- # --- Gradio UI ---
204
  with gr.Blocks(title="Multimodal Agent Evaluation") as demo:
205
  gr.Markdown("# Multimodal Agent Evaluation Runner")
206
  gr.Markdown("This agent can process images, YouTube videos, audio files, and perform web searches.")
@@ -212,10 +151,18 @@ with gr.Blocks(title="Multimodal Agent Evaluation") as demo:
212
  label="Questions and Agent Answers",
213
  wrap=True,
214
  row_count=10,
215
- column_widths=[80, 200, 150, 80, 200]
 
216
  )
217
 
218
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
 
 
 
 
219
 
220
  if __name__ == "__main__":
221
  print("\n" + "-"*30 + " Multimodal App Starting " + "-"*30)
 
1
  """
2
  app.py
3
  This script provides the Gradio web interface to run the evaluation.
4
+ ## MODIFICATION: This version is simplified to work with the new agent architecture.
5
+ It no longer performs file-type detection or prompt enhancement, as that responsibility
6
+ has been moved into the agent's 'multimodal_router'.
7
  """
8
 
9
  import os
 
18
  # --- Constants ---
19
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
 
21
+ # --- Helper function to parse the agent's output (remains the same) ---
22
  def parse_final_answer(agent_response: str) -> str:
23
  match = re.search(r"FINAL ANSWER:\s*(.*)", agent_response, re.IGNORECASE | re.DOTALL)
24
  if match: return match.group(1).strip()
 
26
  if lines: return lines[-1].strip()
27
  return "Could not parse a final answer."
28
 
29
+ ## MODIFICATION: The `detect_file_type` function has been removed.
30
+ ## It is now redundant as this logic is handled inside the agent.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ ## MODIFICATION: The `create_enhanced_prompt` function has been removed.
33
+ ## It was causing errors by trying to instruct the agent to use tools that no longer exist.
34
+ ## The agent is now responsible for handling the raw input itself.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  def run_and_submit_all(profile: gr.OAuthProfile | None):
37
  """
 
78
 
79
  print(f"\n--- Running Task {i+1}/{len(questions_data)} (ID: {task_id}) ---")
80
 
 
81
  file_url = item.get("file_url")
82
 
83
+ ## MODIFICATION: Prompt creation is now much simpler.
84
+ # We just combine the question and the URL into one string.
85
+ # The agent's multimodal_router will handle the rest.
86
  if file_url:
87
+ full_question_text = f"{question_text}\n\nHere is the relevant file: {file_url}"
88
+ print(f"File provided: {file_url}")
89
+ else:
90
+ full_question_text = question_text
91
 
92
+ print(f"Raw Prompt for Agent:\n{full_question_text}")
93
 
94
  try:
95
+ # Pass the simple, raw question to the agent
96
  result = agent_executor.invoke({"messages": [("user", full_question_text)]})
97
 
98
  raw_answer = result['messages'][-1].content
 
106
  "Task ID": task_id,
107
  "Question": question_text,
108
  "File URL": file_url or "None",
 
109
  "Submitted Answer": submitted_answer
110
  })
111
 
 
117
  "Task ID": task_id,
118
  "Question": question_text,
119
  "File URL": file_url or "None",
 
120
  "Submitted Answer": error_msg
121
  })
122
 
123
  if not answers_payload:
124
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
125
 
126
+ # 4. Prepare and 5. Submit (remains the same)
127
  submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
128
  print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")
129
  try:
 
139
  print(status_message)
140
  return status_message, pd.DataFrame(results_log)
141
 
142
+ # --- Gradio UI (remains the same) ---
143
  with gr.Blocks(title="Multimodal Agent Evaluation") as demo:
144
  gr.Markdown("# Multimodal Agent Evaluation Runner")
145
  gr.Markdown("This agent can process images, YouTube videos, audio files, and perform web searches.")
 
151
  label="Questions and Agent Answers",
152
  wrap=True,
153
  row_count=10,
154
+ # MODIFICATION: Removed the 'File Type' column as it's no longer detected here.
155
+ column_widths=[80, 250, 200, 250]
156
  )
157
 
158
+ # We also remove "File Type" from the results_log being displayed
159
+ def display_wrapper(profile):
160
+ status, df = run_and_submit_all(profile)
161
+ if df is not None and "File Type" in df.columns:
162
+ df = df.drop(columns=["File Type"])
163
+ return status, df
164
+
165
+ run_button.click(fn=display_wrapper, outputs=[status_output, results_table])
166
 
167
  if __name__ == "__main__":
168
  print("\n" + "-"*30 + " Multimodal App Starting " + "-"*30)