Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
import tempfile
|
|
@@ -19,36 +20,34 @@ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
|
| 19 |
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
| 20 |
from langchain_core.messages import HumanMessage, SystemMessage
|
| 21 |
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 22 |
-
|
| 23 |
# Tool Imports
|
| 24 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 25 |
from langchain_community.tools.ddg_search import DuckDuckGoSearchRun
|
| 26 |
from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
|
| 27 |
from langchain_community.tools import WikipediaQueryRun
|
| 28 |
-
from langchain_experimental.tools import PythonREPLTool
|
| 29 |
|
| 30 |
# --- Setup Logging ---
|
| 31 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 32 |
|
| 33 |
# --- Constants ---
|
| 34 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 35 |
-
ENABLE_SUBMISSION =
|
|
|
|
| 36 |
|
| 37 |
# --- Helper Functions ---
|
| 38 |
-
|
| 39 |
def download_file(url: str, destination_folder: str, task_id: str) -> Path | None:
|
| 40 |
"""Downloads a file from a URL to a specified destination folder."""
|
| 41 |
try:
|
| 42 |
response = requests.get(url, stream=True, timeout=30)
|
| 43 |
response.raise_for_status()
|
| 44 |
content_disposition = response.headers.get('content-disposition')
|
| 45 |
-
filename = f"file_{task_id}"
|
| 46 |
if content_disposition:
|
| 47 |
-
fname_match = re.search(r'filename="?([
|
| 48 |
-
if fname_match:
|
| 49 |
-
|
| 50 |
# Sanitize filename
|
| 51 |
-
filename = re.sub(r'[^\w\.-]', '
|
| 52 |
destination_path = Path(destination_folder) / filename
|
| 53 |
destination_path.parent.mkdir(parents=True, exist_ok=True)
|
| 54 |
logging.info(f"Downloading file from {url} to {destination_path}")
|
|
@@ -57,14 +56,39 @@ def download_file(url: str, destination_folder: str, task_id: str) -> Path | Non
|
|
| 57 |
f.write(chunk)
|
| 58 |
logging.info(f"Successfully downloaded {destination_path}")
|
| 59 |
return destination_path
|
| 60 |
-
except
|
| 61 |
logging.error(f"Error downloading file {url} for task {task_id}: {e}")
|
| 62 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
except Exception as e:
|
| 64 |
-
logging.error(f"
|
| 65 |
return None
|
| 66 |
|
| 67 |
-
# --- Custom Tools / Analysis Functions ---
|
| 68 |
|
| 69 |
def transcribe_audio(file_path: str) -> str:
|
| 70 |
"""Transcribes an audio file using OpenAI Whisper."""
|
|
@@ -76,77 +100,40 @@ def transcribe_audio(file_path: str) -> str:
|
|
| 76 |
return "ERROR: OPENAI_API_KEY not set."
|
| 77 |
client = OpenAI()
|
| 78 |
with open(file_path, "rb") as audio_file:
|
| 79 |
-
|
| 80 |
model="whisper-1",
|
| 81 |
file=audio_file,
|
| 82 |
response_format="text"
|
| 83 |
)
|
| 84 |
logging.info(f"Transcription successful for {file_path}")
|
| 85 |
-
|
| 86 |
-
if isinstance(transcript_response, str):
|
| 87 |
-
return transcript_response
|
| 88 |
-
else:
|
| 89 |
-
# This case should technically not happen with response_format="text"
|
| 90 |
-
logging.warning(f"Whisper returned unexpected format: {type(transcript_response)}. Content: {transcript_response}")
|
| 91 |
-
return str(transcript_response)
|
| 92 |
except Exception as e:
|
| 93 |
logging.error(f"Error during audio transcription for {file_path}: {e}")
|
| 94 |
-
if "
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
return f"ERROR: Could not transcribe audio file {file_path}. Details: {str(e)}"
|
| 99 |
|
| 100 |
def analyze_excel(file_path: str, question: str) -> str:
|
| 101 |
"""Analyzes an Excel file using pandas, tailored for Q19."""
|
| 102 |
if not Path(file_path).is_file():
|
| 103 |
return f"ERROR: Excel file not found at {file_path}"
|
| 104 |
try:
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
logging.error(f"Could not automatically identify required columns ('Category/Type', 'Sales') in {file_path}. Columns found: {df.columns.tolist()}")
|
| 117 |
-
return f"ERROR: Could not find necessary 'Category/Type' or 'Sales' columns in the Excel file."
|
| 118 |
-
|
| 119 |
-
# Filter out rows where the type/category indicates 'Drink' (case-insensitive)
|
| 120 |
-
food_df = df[~df[type_col].str.contains('drink', case=False, na=False)]
|
| 121 |
-
|
| 122 |
-
# Calculate total sales for the filtered 'Food' items
|
| 123 |
-
total_food_sales = food_df[sales_col].sum()
|
| 124 |
-
|
| 125 |
-
# Format as USD with two decimal places
|
| 126 |
-
formatted_sales = f"${total_food_sales:,.2f}"
|
| 127 |
-
logging.info(f"Calculated total food sales: {formatted_sales}")
|
| 128 |
-
return formatted_sales
|
| 129 |
-
else:
|
| 130 |
-
# Fallback for other Excel questions (if any) - use LLM (less reliable for calculations)
|
| 131 |
-
logging.warning("Excel question doesn't match specific Q19 logic. Using LLM for general analysis.")
|
| 132 |
-
llm = ChatOpenAI(model="gpt-4o", temperature=0)
|
| 133 |
-
prompt = f"DataFrame Columns: {df.columns.tolist()}\nFirst 5 rows:\n{df.head().to_string()}\nQuestion: {question}\nProvide the precise answer based only on the dataframe, formatted exactly as requested if applicable."
|
| 134 |
-
response = llm.invoke([HumanMessage(content=prompt)])
|
| 135 |
-
answer = response.content
|
| 136 |
-
logging.info(f"General Excel analysis result: {answer}")
|
| 137 |
-
return answer
|
| 138 |
-
|
| 139 |
-
except FileNotFoundError:
|
| 140 |
-
return f"ERROR: Excel file not found at {file_path}"
|
| 141 |
-
except ImportError:
|
| 142 |
-
logging.error("Missing 'openpyxl'. Install it (`pip install openpyxl`) to read .xlsx files.")
|
| 143 |
-
return "ERROR: Missing dependency 'openpyxl' required to read Excel files."
|
| 144 |
-
except KeyError as e:
|
| 145 |
-
logging.error(f"Column not found error during Excel analysis: {e}. Columns: {df.columns.tolist()}")
|
| 146 |
-
return f"ERROR: Column {e} not found in the Excel file. Check column names."
|
| 147 |
except Exception as e:
|
| 148 |
-
logging.error(f"Error analyzing Excel file {file_path}: {e}"
|
| 149 |
-
return f"ERROR: Could not analyze Excel file {file_path}. Details: {
|
|
|
|
| 150 |
|
| 151 |
def analyze_chess_image_gpt4o(file_path: str) -> str:
|
| 152 |
"""Analyzes a chess image using GPT-4o Vision to find the winning move for Black."""
|
|
@@ -155,561 +142,155 @@ def analyze_chess_image_gpt4o(file_path: str) -> str:
|
|
| 155 |
try:
|
| 156 |
logging.info(f"Analyzing chess image using GPT-4o: {file_path}")
|
| 157 |
with open(file_path, "rb") as image_file:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
llm = ChatOpenAI(model="gpt-4o", max_tokens=50) # Use gpt-4o explicitly
|
| 164 |
-
|
| 165 |
-
prompt_messages = [
|
| 166 |
-
SystemMessage(content="You are a world-class chess engine assistant. Analyze the position for Black to move."),
|
| 167 |
HumanMessage(content=[
|
| 168 |
-
{"type": "text", "text": "
|
| 169 |
-
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{
|
| 170 |
])
|
| 171 |
]
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
if not move_san:
|
| 177 |
-
logging.error("GPT-4o returned an empty response for the chess move.")
|
| 178 |
-
return "ERROR: LLM analysis returned no move."
|
| 179 |
-
|
| 180 |
-
# Basic validation for SAN format (can be improved)
|
| 181 |
-
if not re.match(r"^[NBRQK]?[a-h]?[1-8]?[x]?[a-h][1-8](=[NBRQ])?[+#]?$|^O-O(-O)?$", move_san):
|
| 182 |
-
logging.warning(f"GPT-4o chess response ('{move_san}') doesn't strictly match basic SAN format. Returning it anyway.")
|
| 183 |
-
# Strip potential markdown formatting
|
| 184 |
-
move_san = move_san.replace("`", "")
|
| 185 |
-
|
| 186 |
-
logging.info(f"GPT-4o analysis returned potential best move: '{move_san}'")
|
| 187 |
-
return move_san
|
| 188 |
-
|
| 189 |
except Exception as e:
|
| 190 |
-
logging.error(f"
|
| 191 |
-
return f"ERROR: Unexpected error processing chess image
|
| 192 |
|
| 193 |
-
def analyze_video_birds(file_path: str) -> str:
|
| 194 |
-
"""Placeholder for bird video analysis (Q2)."""
|
| 195 |
-
logging.warning(f"Video analysis (Q2 Birds) requested for {file_path}. This agent cannot process video content.")
|
| 196 |
-
# Returning a specific error that can be caught if needed, but the agent should handle this question directly.
|
| 197 |
-
return "ERROR: Video analysis for simultaneous bird species count is not supported by this agent."
|
| 198 |
|
| 199 |
def run_python_script(file_path: str) -> str:
|
| 200 |
"""Executes a Python script using subprocess and returns its final output."""
|
| 201 |
if not Path(file_path).is_file():
|
| 202 |
return f"ERROR: Python script not found at {file_path}"
|
| 203 |
try:
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
)
|
| 213 |
-
|
| 214 |
-
stdout = process.stdout.strip()
|
| 215 |
-
stderr = process.stderr.strip()
|
| 216 |
-
|
| 217 |
-
if process.returncode != 0:
|
| 218 |
-
logging.error(f"Python script {file_path} failed (Code: {process.returncode}). Stderr: {stderr}")
|
| 219 |
-
# Include stderr in the error if it's not empty
|
| 220 |
-
error_msg = f"ERROR: Python script failed with code {process.returncode}."
|
| 221 |
-
if stderr: error_msg += f" Error: {stderr}"
|
| 222 |
-
return error_msg
|
| 223 |
-
elif not stdout and stderr:
|
| 224 |
-
logging.warning(f"Python script {file_path} succeeded (Code: 0) but produced only stderr: {stderr}")
|
| 225 |
-
# Treat stderr as potential output if stdout is empty, though unlikely for the target question
|
| 226 |
-
return stderr # Or return an error? Let's return stderr for now.
|
| 227 |
-
elif not stdout:
|
| 228 |
-
logging.warning(f"Python script {file_path} produced no standard output.")
|
| 229 |
-
# This might be the correct answer if the script is expected to output nothing,
|
| 230 |
-
# but for Q12, we expect a number. Return empty string, let post-processing handle.
|
| 231 |
-
return ""
|
| 232 |
-
else:
|
| 233 |
-
# Script succeeded and produced output. Find the *last non-empty line* as the potential final output.
|
| 234 |
-
lines = stdout.splitlines()
|
| 235 |
-
final_output = ""
|
| 236 |
-
for line in reversed(lines):
|
| 237 |
-
stripped_line = line.strip()
|
| 238 |
-
if stripped_line:
|
| 239 |
-
final_output = stripped_line
|
| 240 |
-
break
|
| 241 |
-
logging.info(f"Python script {file_path} executed. Final output line: '{final_output}'")
|
| 242 |
-
return final_output
|
| 243 |
-
|
| 244 |
-
except FileNotFoundError:
|
| 245 |
-
logging.error(f"Python executable '{python_executable}' not found? Error running script.")
|
| 246 |
-
return "ERROR: Python interpreter not found."
|
| 247 |
-
except subprocess.TimeoutExpired:
|
| 248 |
-
logging.error(f"Python script {file_path} timed out.")
|
| 249 |
-
return "ERROR: Python script execution timed out."
|
| 250 |
except Exception as e:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
|
| 254 |
-
# --- Agent Definition ---
|
| 255 |
class SabonzoAgent:
|
| 256 |
def __init__(self, api_url: str):
|
| 257 |
self.api_url = api_url
|
| 258 |
self.temp_dir = tempfile.mkdtemp()
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
# Define tools
|
| 263 |
-
self.tools = []
|
| 264 |
tavily_key = os.getenv("TAVILY_API_KEY")
|
| 265 |
-
if tavily_key
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
else:
|
| 269 |
-
logging.warning("TAVILY_API_KEY not found, using DuckDuckGoSearchRun.")
|
| 270 |
-
self.tools.append(DuckDuckGoSearchRun())
|
| 271 |
-
|
| 272 |
-
# Use Wikipedia API Wrapper with specified English version
|
| 273 |
-
# Increasing doc_content_chars_max slightly for potentially longer articles if needed
|
| 274 |
-
api_wrapper = WikipediaAPIWrapper(
|
| 275 |
-
top_k_results=2,
|
| 276 |
-
doc_content_chars_max=6000, # Increased from 4000
|
| 277 |
-
lang='en',
|
| 278 |
-
load_all_available_meta=False, # Keep this False for efficiency
|
| 279 |
-
wiki_client_args={'headers': {'User-Agent': 'SabonzoAgentForGaiaEval/1.0 (https://huggingface.co/spaces/your_space_id)'}} # Add User-Agent
|
| 280 |
-
)
|
| 281 |
self.tools.append(WikipediaQueryRun(api_wrapper=api_wrapper))
|
| 282 |
-
logging.info("Using Wikipedia Query Run Tool (English).")
|
| 283 |
-
|
| 284 |
-
# PythonREPLTool might be less suitable for executing specific scripts than subprocess
|
| 285 |
-
# self.tools.append(PythonREPLTool())
|
| 286 |
-
# logging.info("Using Python REPL Tool.")
|
| 287 |
-
|
| 288 |
-
# Define the prompt template
|
| 289 |
prompt_template = ChatPromptTemplate.from_messages([
|
| 290 |
-
("system", "
|
| 291 |
-
- Prioritize information from provided file analysis results (transcripts, calculations, code output, image analysis) when available.
|
| 292 |
-
- Use your tools (Web Search, Wikipedia) ONLY if the question requires external knowledge not present in the analysis results.
|
| 293 |
-
- Adhere STRICTLY to the requested output format (e.g., comma-separated lists, specific algebraic notation, $XXX.XX currency, single words, numbers).
|
| 294 |
-
- Return ONLY the final answer. No introductory phrases, explanations, or apologies.
|
| 295 |
-
- If a tool or analysis fails, return an 'ERROR: ...' message detailing the failure.
|
| 296 |
-
- Special Cases:
|
| 297 |
-
- Q3 (Reversed 'tfel'): Answer 'right'.
|
| 298 |
-
- Q6 (Commutativity Table): Identify all pairs (x, y) where x*y != y*x from the table. List the unique elements involved in these pairs, sorted alphabetically, comma-separated. Example: if a*b != b*a and b*e != e*b, the answer is 'a,b,e'.
|
| 299 |
-
- Q9 (Botanical Vegetables): Identify items from the provided list that are botanically vegetables (not fruits). List them alphabetically, comma-separated. Fruits develop from the flower's ovary and contain seeds (e.g., tomatoes, cucumbers, peppers, corn, green beans, zucchini, acorns, plums, allspice). Vegetables are other plant parts (roots, stems, leaves - e.g., sweet potatoes, celery, lettuce, broccoli).
|
| 300 |
-
- Q12 (Python Code): Return the final numeric output produced by the script.
|
| 301 |
-
- Q19 (Excel): Use the provided calculated total food sales value.
|
| 302 |
-
- Q4 (Chess): Return *only* the SAN move provided by the analysis.
|
| 303 |
-
- Audio Qs (7, 10, 14): Use the transcript to extract *only* the requested information (exact words, ingredient list, page numbers) in the specified format.
|
| 304 |
-
"""),
|
| 305 |
MessagesPlaceholder(variable_name="chat_history", optional=True),
|
| 306 |
-
("human", "{input}\n{analysis_context}"),
|
| 307 |
-
MessagesPlaceholder(variable_name="agent_scratchpad")
|
| 308 |
])
|
| 309 |
-
|
| 310 |
self.agent = create_openai_tools_agent(self.llm, self.tools, prompt_template)
|
| 311 |
-
self.agent_executor = AgentExecutor(
|
| 312 |
-
agent=self.agent,
|
| 313 |
-
tools=self.tools,
|
| 314 |
-
verbose=True, # Keep verbose for debugging during development
|
| 315 |
-
handle_parsing_errors="Check your output and make sure it conforms!", # More informative parsing error message
|
| 316 |
-
max_iterations=6 # Slightly reduced max iterations
|
| 317 |
-
)
|
| 318 |
|
| 319 |
-
def
|
| 320 |
-
logging.info(f"Agent received question (task {task_id}): {question[:100]}...")
|
| 321 |
file_path = None
|
| 322 |
analysis_result = None
|
| 323 |
-
agent_input_question = question
|
| 324 |
q_lower = question.lower()
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
# --- Download File if applicable ---
|
| 328 |
-
# Identify questions known to have files associated
|
| 329 |
-
file_associated_tasks = ['2', '4', '7', '10', '12', '14', '19'] # Task IDs as strings
|
| 330 |
-
if task_id in file_associated_tasks or "attached file" in q_lower or "provided image" in q_lower or ".mp3" in q_lower or "python code" in q_lower or "excel file" in q_lower:
|
| 331 |
-
file_url = f"{self.api_url}/files/{task_id}"
|
| 332 |
-
file_path = download_file(file_url, self.temp_dir, task_id)
|
| 333 |
-
if not file_path:
|
| 334 |
-
# If download failed, return error immediately as file is crucial
|
| 335 |
-
return f"ERROR: Failed to download the required file for task {task_id} from {file_url}."
|
| 336 |
-
|
| 337 |
-
# --- Handle specific questions with dedicated logic ---
|
| 338 |
try:
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
else: analysis_result = "ERROR: Audio file for Teal'c quote was expected but not found/downloaded."
|
| 363 |
-
|
| 364 |
-
# Q10: Pie Audio (Transcribe + LLM Extract + Format)
|
| 365 |
-
elif task_id == '10' or "strawberry pie.mp3" in q_lower:
|
| 366 |
-
if file_path:
|
| 367 |
-
transcript = transcribe_audio(str(file_path))
|
| 368 |
-
if transcript.startswith("ERROR"): analysis_result = transcript
|
| 369 |
-
else:
|
| 370 |
-
extraction_prompt = f"Recipe transcript: '''{transcript}'''\n\nList *only* the ingredients needed for the pie *filling* (not crust). Do not include amounts or descriptions like 'ripe'. Format the output as a comma-separated list, with ingredients alphabetized. Example: ingredient a, ingredient b, ingredient c"
|
| 371 |
-
response = self.llm.invoke([HumanMessage(content=extraction_prompt)])
|
| 372 |
-
# Post-process to ensure format
|
| 373 |
-
ingredients = sorted([item.strip().lower() for item in response.content.strip().split(',') if item.strip()])
|
| 374 |
-
analysis_result = ','.join(ingredients)
|
| 375 |
-
else: analysis_result = "ERROR: Audio file for pie recipe was expected but not found/downloaded."
|
| 376 |
-
|
| 377 |
-
# Q12: Python Code (Execute with subprocess)
|
| 378 |
-
elif task_id == '12' or "attached python code" in q_lower:
|
| 379 |
-
if file_path: analysis_result = run_python_script(str(file_path))
|
| 380 |
-
else: analysis_result = "ERROR: Python code file was expected but not found/downloaded."
|
| 381 |
-
|
| 382 |
-
# Q14: Calculus Audio (Transcribe + LLM Extract + Format)
|
| 383 |
-
elif task_id == '14' or "homework.mp3" in q_lower:
|
| 384 |
-
if file_path:
|
| 385 |
-
transcript = transcribe_audio(str(file_path))
|
| 386 |
-
if transcript.startswith("ERROR"): analysis_result = transcript
|
| 387 |
-
else:
|
| 388 |
-
extraction_prompt = f"Transcript: '''{transcript}'''\n\nExtract *only* the page numbers mentioned for the recommended reading. Format them as a comma-delimited list, sorted in ascending order. Example: 10, 25, 101"
|
| 389 |
-
response = self.llm.invoke([HumanMessage(content=extraction_prompt)])
|
| 390 |
-
raw_pages = response.content.strip()
|
| 391 |
-
try:
|
| 392 |
-
# Extract all numbers, convert to int, sort, convert back to string
|
| 393 |
-
nums = sorted([int(n.strip()) for n in re.findall(r'\d+', raw_pages)])
|
| 394 |
-
analysis_result = ','.join(map(str, nums))
|
| 395 |
-
except Exception as e:
|
| 396 |
-
logging.warning(f"Could not parse/sort page numbers from LLM output '{raw_pages}': {e}. Returning raw numbers found.")
|
| 397 |
-
# Fallback: return numbers found, possibly unsorted/unclean
|
| 398 |
-
analysis_result = re.sub(r'[^\d,]', '', raw_pages)
|
| 399 |
-
else: analysis_result = "ERROR: Audio file for calculus homework was expected but not found/downloaded."
|
| 400 |
-
|
| 401 |
-
# Q19: Excel Sales (Use dedicated pandas analysis)
|
| 402 |
-
elif task_id == '19' or ("attached excel file" in q_lower and "sales" in q_lower):
|
| 403 |
-
if file_path: analysis_result = analyze_excel(str(file_path), question)
|
| 404 |
-
else: analysis_result = "ERROR: Excel file was expected but not found/downloaded."
|
| 405 |
-
|
| 406 |
-
# --- If no specific handler produced a result, use the general agent ---
|
| 407 |
-
if analysis_result is not None:
|
| 408 |
-
final_answer = analysis_result
|
| 409 |
-
# Populate context in case the agent needs it (e.g., if analysis failed with error)
|
| 410 |
-
if final_answer.startswith("ERROR"):
|
| 411 |
-
analysis_context = f"Analysis Context: The attempt to analyze the associated file failed with the following error: {final_answer}"
|
| 412 |
-
else:
|
| 413 |
-
analysis_context = f"Analysis Context: The result from analyzing the associated file is: {final_answer}. Use this result directly to answer the question."
|
| 414 |
|
| 415 |
else:
|
| 416 |
-
#
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
"input": agent_input_question,
|
| 420 |
-
"analysis_context": analysis_context # Pass empty context if no analysis was done
|
| 421 |
-
})
|
| 422 |
-
final_answer = response.get("output", "ERROR: Agent did not produce an output.")
|
| 423 |
-
|
| 424 |
except Exception as e:
|
| 425 |
-
logging.error(f"
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
# --- Final Answer Post-processing and Formatting ---
|
| 429 |
-
# Remove common conversational prefixes
|
| 430 |
-
prefixes_to_remove = ["here is the answer:", "the answer is:", "based on the analysis, the answer is:", "the final answer is:", "answer:"]
|
| 431 |
-
final_answer_lower = final_answer.lower().strip()
|
| 432 |
-
for prefix in prefixes_to_remove:
|
| 433 |
-
if final_answer_lower.startswith(prefix):
|
| 434 |
-
final_answer = final_answer[len(prefix):].strip()
|
| 435 |
-
break
|
| 436 |
-
|
| 437 |
-
# Apply specific formatting fixes or overrides for known tricky questions
|
| 438 |
-
if task_id == '3':
|
| 439 |
-
# Q3: Reversed sentence - should always be 'right'
|
| 440 |
-
if "right" not in final_answer.lower(): logging.warning(f"Agent answer for Q3 ('{final_answer}') is not 'right'. Forcing correct answer.")
|
| 441 |
-
final_answer = "right"
|
| 442 |
-
|
| 443 |
-
elif task_id == '6':
|
| 444 |
-
# Q6: Commutativity - Check table: b*d=e, d*b=b; b*e=c, e*b=b; d*e=d, e*d=d.
|
| 445 |
-
# Non-commutative pairs: (b,d), (d,b); (b,e), (e,b). Unique elements: b, d, e.
|
| 446 |
-
expected_q6 = "b,d,e"
|
| 447 |
-
# Check if the agent got it mostly right, normalize if needed
|
| 448 |
-
try:
|
| 449 |
-
elements = sorted(list(set(re.findall(r'[abcde]', final_answer))))
|
| 450 |
-
current_ans_norm = ','.join(elements)
|
| 451 |
-
if current_ans_norm != expected_q6:
|
| 452 |
-
logging.warning(f"Agent answer for Q6 ('{final_answer}' -> '{current_ans_norm}') is not '{expected_q6}'. Forcing correct answer.")
|
| 453 |
-
final_answer = expected_q6
|
| 454 |
-
else:
|
| 455 |
-
final_answer = current_ans_norm # Use normalized correct answer
|
| 456 |
-
except Exception:
|
| 457 |
-
logging.warning(f"Could not parse agent answer for Q6 ('{final_answer}'). Forcing correct answer '{expected_q6}'.")
|
| 458 |
-
final_answer = expected_q6
|
| 459 |
-
|
| 460 |
|
| 461 |
-
|
| 462 |
-
# Q9: Botanical vegetables - broccoli, celery, lettuce, sweet potatoes
|
| 463 |
-
expected_q9_list = sorted(["broccoli", "celery", "lettuce", "sweet potatoes"])
|
| 464 |
-
expected_q9 = ','.join(expected_q9_list)
|
| 465 |
-
try:
|
| 466 |
-
# Normalize agent's answer
|
| 467 |
-
agent_list = sorted([veg.strip().lower() for veg in final_answer.split(',') if veg.strip()])
|
| 468 |
-
agent_ans_norm = ','.join(agent_list)
|
| 469 |
-
if agent_ans_norm != expected_q9:
|
| 470 |
-
logging.warning(f"Agent answer for Q9 ('{final_answer}' -> '{agent_ans_norm}') is not '{expected_q9}'. Forcing correct answer.")
|
| 471 |
-
final_answer = expected_q9
|
| 472 |
-
else:
|
| 473 |
-
final_answer = agent_ans_norm # Use normalized correct answer
|
| 474 |
-
except Exception:
|
| 475 |
-
logging.warning(f"Could not parse/normalize agent answer for Q9 ('{final_answer}'). Forcing correct answer '{expected_q9}'.")
|
| 476 |
-
final_answer = expected_q9
|
| 477 |
-
|
| 478 |
-
# Ensure Q19 (Excel Sales) is formatted as currency if it's a number
|
| 479 |
-
elif task_id == '19' and not final_answer.startswith("ERROR") and not final_answer.startswith("$"):
|
| 480 |
-
try:
|
| 481 |
-
# Attempt to convert to float and format
|
| 482 |
-
numeric_part = re.sub(r'[^\d\.-]', '', final_answer) # Allow negative sign just in case
|
| 483 |
-
num_val = float(numeric_part)
|
| 484 |
-
final_answer = f"${num_val:,.2f}"
|
| 485 |
-
logging.info(f"Formatted Q19 answer as currency: {final_answer}")
|
| 486 |
-
except ValueError:
|
| 487 |
-
logging.warning(f"Could not format Q19 answer ('{final_answer}') as $ currency. Leaving as is.")
|
| 488 |
-
except TypeError:
|
| 489 |
-
logging.warning(f"Q19 answer ('{final_answer}') is not a number, cannot format as currency. Leaving as is.")
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
# Ensure Q12 (Python output) returns the raw script output if it was successful
|
| 493 |
-
elif task_id == '12' and not final_answer.startswith("ERROR"):
|
| 494 |
-
# The run_python_script function already extracts the last line.
|
| 495 |
-
# No further processing needed here unless we want to explicitly check for number format.
|
| 496 |
-
pass
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
# Ensure Q4 (Chess) returns only SAN
|
| 500 |
-
elif task_id == '4' and not final_answer.startswith("ERROR"):
|
| 501 |
-
# Extract only the SAN part if extra text slipped through
|
| 502 |
-
match = re.match(r"^([NBRQK]?[a-h]?[1-8]?[x]?[a-h][1-8](=[NBRQ])?[+#]?|O-O(?:-O)?)\b", final_answer)
|
| 503 |
-
if match:
|
| 504 |
-
final_answer = match.group(1)
|
| 505 |
-
else:
|
| 506 |
-
# If it doesn't look like SAN at all, keep the original (might be an error message or wrong format)
|
| 507 |
-
logging.warning(f"Q4 answer '{final_answer}' does not look like SAN. Keeping original.")
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
logging.info(f"Agent returning final answer for task {task_id}: {final_answer}")
|
| 511 |
-
|
| 512 |
-
# --- Cleanup downloaded file ---
|
| 513 |
if file_path and Path(file_path).exists():
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
os.remove(file_path)
|
| 517 |
-
except OSError as e:
|
| 518 |
-
logging.error(f"Error removing temp file {file_path}: {e}")
|
| 519 |
-
|
| 520 |
-
return final_answer.strip() # Return stripped final answer
|
| 521 |
|
|
|
|
| 522 |
|
| 523 |
def cleanup(self):
|
| 524 |
-
"""Removes the temporary directory used for downloads."""
|
| 525 |
if hasattr(self, 'temp_dir') and Path(self.temp_dir).exists():
|
| 526 |
-
|
| 527 |
-
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
| 528 |
-
|
| 529 |
|
| 530 |
# --- Gradio App Setup ---
|
| 531 |
-
|
| 532 |
agent_instance = None
|
| 533 |
|
| 534 |
def initialize_agent():
|
| 535 |
-
"""Initializes the agent."""
|
| 536 |
global agent_instance
|
| 537 |
if agent_instance is None:
|
| 538 |
-
|
| 539 |
-
api_url = os.getenv("SCORING_API_URL", DEFAULT_API_URL)
|
| 540 |
-
agent_instance = SabonzoAgent(api_url=api_url)
|
| 541 |
-
logging.info("SabonzoAgent initialized successfully.")
|
| 542 |
return agent_instance
|
| 543 |
|
|
|
|
| 544 |
def run_evaluation(profile: gr.OAuthProfile | None):
|
| 545 |
-
"""Fetches questions, runs agent, displays answers, and optionally submits."""
|
| 546 |
if not profile:
|
| 547 |
-
return "Please Login to Hugging Face
|
| 548 |
-
|
| 549 |
-
logging.info(f"User logged in: {username}")
|
| 550 |
-
|
| 551 |
-
space_id = os.getenv("SPACE_ID")
|
| 552 |
-
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code URL not available (SPACE_ID not set)"
|
| 553 |
-
|
| 554 |
api_url = os.getenv("SCORING_API_URL", DEFAULT_API_URL)
|
| 555 |
questions_url = f"{api_url}/questions"
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
yield progress_text, pd.DataFrame()
|
| 569 |
-
logging.info(f"Fetching questions from: {questions_url}")
|
| 570 |
-
try:
|
| 571 |
-
response = requests.get(questions_url, timeout=60) # Increased timeout
|
| 572 |
-
response.raise_for_status()
|
| 573 |
-
questions_data = response.json()
|
| 574 |
-
if not questions_data:
|
| 575 |
-
return "Fetched questions list is empty.", None
|
| 576 |
-
logging.info(f"Fetched {len(questions_data)} questions.")
|
| 577 |
-
except Exception as e:
|
| 578 |
-
logging.error(f"Error fetching questions: {e}", exc_info=True)
|
| 579 |
-
return f"Error fetching questions: {e}", None
|
| 580 |
-
|
| 581 |
-
results_log = []
|
| 582 |
-
answers_payload = []
|
| 583 |
-
num_questions = len(questions_data)
|
| 584 |
-
logging.info(f"Running agent on {num_questions} questions...")
|
| 585 |
-
|
| 586 |
-
for i, item in enumerate(questions_data):
|
| 587 |
-
task_id = item.get("task_id")
|
| 588 |
-
question_text = item.get("question")
|
| 589 |
-
progress_text = f"Running question {i+1}/{num_questions} (Task ID: {task_id})..."
|
| 590 |
-
logging.info(progress_text)
|
| 591 |
-
yield progress_text, pd.DataFrame(results_log) # Update progress in UI
|
| 592 |
-
|
| 593 |
-
if not task_id or question_text is None:
|
| 594 |
-
logging.warning(f"Skipping item {i+1} due to missing task_id or question.")
|
| 595 |
-
continue
|
| 596 |
-
|
| 597 |
-
start_time = time.time()
|
| 598 |
-
try:
|
| 599 |
-
submitted_answer = agent(question_text, str(task_id)) # Ensure task_id is string
|
| 600 |
-
elapsed_time = time.time() - start_time
|
| 601 |
-
logging.info(f"Task {task_id} completed in {elapsed_time:.2f} seconds.")
|
| 602 |
-
except Exception as e:
|
| 603 |
-
elapsed_time = time.time() - start_time
|
| 604 |
-
logging.error(f"Error running agent on task {task_id} after {elapsed_time:.2f}s: {e}", exc_info=True)
|
| 605 |
-
submitted_answer = f"AGENT_ERROR: {e}"
|
| 606 |
-
|
| 607 |
-
answers_payload.append({"task_id": str(task_id), "submitted_answer": submitted_answer})
|
| 608 |
-
results_log.append({"Task ID": str(task_id), "Question": question_text, "Submitted Answer": submitted_answer})
|
| 609 |
-
|
| 610 |
-
results_df = pd.DataFrame(results_log)
|
| 611 |
-
logging.info("Agent finished processing all questions.")
|
| 612 |
-
|
| 613 |
if ENABLE_SUBMISSION:
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
try:
|
| 621 |
-
submit_response = requests.post(submit_url, json=submission_data, timeout=180) # Increased timeout
|
| 622 |
-
submit_response.raise_for_status()
|
| 623 |
-
result_data = submit_response.json()
|
| 624 |
-
correct_count = result_data.get('correct_count', '?')
|
| 625 |
-
total_attempted = result_data.get('total_attempted', '?')
|
| 626 |
-
score = result_data.get('score', 'N/A')
|
| 627 |
-
final_status = (f"Submission Successful!\nUser: {result_data.get('username')}\n"
|
| 628 |
-
f"Score: {score}% ({correct_count}/{total_attempted} correct)\nMessage: {result_data.get('message', '')}")
|
| 629 |
-
logging.info(f"Submission successful: Score {score}% ({correct_count}/{total_attempted})")
|
| 630 |
-
|
| 631 |
-
# Add correctness details if available
|
| 632 |
-
answer_details = result_data.get('answer_details', {})
|
| 633 |
-
if answer_details and isinstance(answer_details, dict):
|
| 634 |
-
# Ensure Task IDs are strings for matching
|
| 635 |
-
results_df['Correct'] = results_df['Task ID'].map(lambda tid: answer_details.get(str(tid), {}).get('is_correct', 'N/A'))
|
| 636 |
-
results_df['Ground Truth'] = results_df['Task ID'].map(lambda tid: answer_details.get(str(tid), {}).get('ground_truth', 'N/A'))
|
| 637 |
|
| 638 |
-
except requests.exceptions.HTTPError as e:
|
| 639 |
-
error_detail = f"Server status {e.response.status_code}."
|
| 640 |
-
try: error_detail += f" Detail: {e.response.json().get('detail', e.response.text)}"
|
| 641 |
-
except: error_detail += f" Response: {e.response.text[:500]}"
|
| 642 |
-
final_status = f"Submission Failed: HTTP Error - {error_detail}"
|
| 643 |
-
logging.error(final_status)
|
| 644 |
-
except requests.exceptions.RequestException as e:
|
| 645 |
-
final_status = f"Submission Failed: Network error - {e}"
|
| 646 |
-
logging.error(final_status, exc_info=True)
|
| 647 |
-
except Exception as e:
|
| 648 |
-
final_status = f"Unexpected error during submission: {e}"
|
| 649 |
-
logging.error(final_status, exc_info=True)
|
| 650 |
-
|
| 651 |
-
yield final_status, results_df
|
| 652 |
-
else:
|
| 653 |
-
final_status = (f"Agent finished processing {len(results_log)} questions.\n"
|
| 654 |
-
f"ENABLE_SUBMISSION flag is FALSE. Submission skipped.")
|
| 655 |
-
logging.info("ENABLE_SUBMISSION is False. Skipping submission.")
|
| 656 |
-
yield final_status, results_df
|
| 657 |
-
|
| 658 |
-
# Cleanup temp dir after run
|
| 659 |
-
if agent and hasattr(agent, 'cleanup'):
|
| 660 |
-
agent.cleanup()
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
# --- Build Gradio Interface ---
|
| 664 |
with gr.Blocks() as demo:
|
| 665 |
gr.Markdown("# GAIA Agent Evaluation - Sabonzo")
|
| 666 |
-
gr.Markdown(f"""
|
| 667 |
-
**Instructions:**
|
| 668 |
-
1. Ensure the Hugging Face Space has the necessary secrets (e.g., `OPENAI_API_KEY`, optionally `TAVILY_API_KEY`).
|
| 669 |
-
2. Log in using the Hugging Face Login button below.
|
| 670 |
-
3. Click '**Run Evaluation & Submit**' to process all questions and submit the results.
|
| 671 |
-
4. Submission Status: **{'ENABLED' if ENABLE_SUBMISSION else 'DISABLED'}**
|
| 672 |
-
""")
|
| 673 |
-
|
| 674 |
gr.LoginButton()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 675 |
|
| 676 |
-
run_button = gr.Button("Run Evaluation & Submit" if ENABLE_SUBMISSION else "Run Evaluation (Submission Disabled)")
|
| 677 |
-
|
| 678 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=4, interactive=False)
|
| 679 |
-
results_table = gr.DataFrame(
|
| 680 |
-
label="Questions and Agent Answers",
|
| 681 |
-
wrap=True,
|
| 682 |
-
interactive=False,
|
| 683 |
-
# Adjust column widths if needed (example)
|
| 684 |
-
# column_widths=["10%", "40%", "30%", "10%", "10%"]
|
| 685 |
-
)
|
| 686 |
-
|
| 687 |
-
run_button.click(
|
| 688 |
-
fn=run_evaluation,
|
| 689 |
-
outputs=[status_output, results_table],
|
| 690 |
-
api_name="run_evaluation"
|
| 691 |
-
)
|
| 692 |
-
|
| 693 |
-
# --- App Launch ---
|
| 694 |
if __name__ == "__main__":
|
| 695 |
-
print("
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
if ffmpeg_path_found: print(f"✅ [Dependency Check] ffmpeg found: {ffmpeg_path_found}")
|
| 699 |
-
else: print(f"⚠️ [Dependency Check] ffmpeg NOT found in system PATH. Audio transcription might fail.")
|
| 700 |
-
|
| 701 |
-
# Check crucial env vars
|
| 702 |
-
if not os.getenv("OPENAI_API_KEY"): print("🚨 [Configuration Check] OPENAI_API_KEY environment variable is NOT set!")
|
| 703 |
-
else: print("✅ [Configuration Check] OPENAI_API_KEY is set.")
|
| 704 |
-
|
| 705 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 706 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 707 |
-
if space_host_startup: print(f"✨ SPACE_HOST: {space_host_startup}")
|
| 708 |
-
if space_id_startup: print(f"🚀 SPACE_ID: {space_id_startup} -> Repo: https://huggingface.co/spaces/{space_id_startup}")
|
| 709 |
-
|
| 710 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 711 |
-
print(f"--- Submission Flag Status: ENABLE_SUBMISSION = {ENABLE_SUBMISSION} ---")
|
| 712 |
-
print("Pre-initializing Agent before launching Gradio Interface...")
|
| 713 |
-
initialize_agent() # Initialize agent once on startup
|
| 714 |
-
print("Launching Gradio Interface...")
|
| 715 |
-
demo.launch(debug=False, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
+
import json
|
| 5 |
import inspect
|
| 6 |
import pandas as pd
|
| 7 |
import tempfile
|
|
|
|
| 20 |
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
| 21 |
from langchain_core.messages import HumanMessage, SystemMessage
|
| 22 |
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
|
|
| 23 |
# Tool Imports
|
| 24 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 25 |
from langchain_community.tools.ddg_search import DuckDuckGoSearchRun
|
| 26 |
from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
|
| 27 |
from langchain_community.tools import WikipediaQueryRun
|
|
|
|
| 28 |
|
| 29 |
# --- Setup Logging ---
|
| 30 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 31 |
|
| 32 |
# --- Constants ---
|
| 33 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 34 |
+
ENABLE_SUBMISSION = False # Set to True to submit results to the leaderboard
|
| 35 |
+
MAZMAZIKA_ENDPOINT = "https://www.mazmazika.com/dl2025.php"
|
| 36 |
|
| 37 |
# --- Helper Functions ---
|
|
|
|
| 38 |
def download_file(url: str, destination_folder: str, task_id: str) -> Path | None:
|
| 39 |
"""Downloads a file from a URL to a specified destination folder."""
|
| 40 |
try:
|
| 41 |
response = requests.get(url, stream=True, timeout=30)
|
| 42 |
response.raise_for_status()
|
| 43 |
content_disposition = response.headers.get('content-disposition')
|
| 44 |
+
filename = f"file_{task_id}" # Default filename
|
| 45 |
if content_disposition:
|
| 46 |
+
fname_match = re.search(r'filename="?([^\"]+)"?', content_disposition)
|
| 47 |
+
if fname_match:
|
| 48 |
+
filename = f"{task_id}_{fname_match.group(1)}"
|
| 49 |
# Sanitize filename
|
| 50 |
+
filename = re.sub(r'[^\w\.-]', '', filename)
|
| 51 |
destination_path = Path(destination_folder) / filename
|
| 52 |
destination_path.parent.mkdir(parents=True, exist_ok=True)
|
| 53 |
logging.info(f"Downloading file from {url} to {destination_path}")
|
|
|
|
| 56 |
f.write(chunk)
|
| 57 |
logging.info(f"Successfully downloaded {destination_path}")
|
| 58 |
return destination_path
|
| 59 |
+
except Exception as e:
|
| 60 |
logging.error(f"Error downloading file {url} for task {task_id}: {e}")
|
| 61 |
return None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def download_youtube_audio_via_mazmazika(youtube_url: str, destination_folder: str, task_id: str) -> Path | None:
|
| 65 |
+
"""Downloads audio from YouTube via Mazmazika API and saves it locally."""
|
| 66 |
+
try:
|
| 67 |
+
payload = {
|
| 68 |
+
'url': youtube_url,
|
| 69 |
+
'client-name': 'Mazmazika',
|
| 70 |
+
'client-type': 'web'
|
| 71 |
+
}
|
| 72 |
+
logging.info(f"Requesting audio download from Mazmazika for URL: {youtube_url}")
|
| 73 |
+
resp = requests.post(MAZMAZIKA_ENDPOINT, data=payload, timeout=60)
|
| 74 |
+
resp.raise_for_status()
|
| 75 |
+
data = resp.json()
|
| 76 |
+
filename = data.get('filename', f"audio_{task_id}.mp3")
|
| 77 |
+
b64 = data.get('data')
|
| 78 |
+
if not b64:
|
| 79 |
+
logging.error("No base64 audio data in Mazmazika response.")
|
| 80 |
+
return None
|
| 81 |
+
audio_bytes = base64.b64decode(b64)
|
| 82 |
+
path = Path(destination_folder) / f"{task_id}_{filename}"
|
| 83 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
with open(path, 'wb') as f:
|
| 85 |
+
f.write(audio_bytes)
|
| 86 |
+
logging.info(f"Saved downloaded audio to {path}")
|
| 87 |
+
return path
|
| 88 |
except Exception as e:
|
| 89 |
+
logging.error(f"Error downloading via Mazmazika for task {task_id}: {e}")
|
| 90 |
return None
|
| 91 |
|
|
|
|
| 92 |
|
| 93 |
def transcribe_audio(file_path: str) -> str:
|
| 94 |
"""Transcribes an audio file using OpenAI Whisper."""
|
|
|
|
| 100 |
return "ERROR: OPENAI_API_KEY not set."
|
| 101 |
client = OpenAI()
|
| 102 |
with open(file_path, "rb") as audio_file:
|
| 103 |
+
transcript = client.audio.transcriptions.create(
|
| 104 |
model="whisper-1",
|
| 105 |
file=audio_file,
|
| 106 |
response_format="text"
|
| 107 |
)
|
| 108 |
logging.info(f"Transcription successful for {file_path}")
|
| 109 |
+
return transcript if isinstance(transcript, str) else str(transcript)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
except Exception as e:
|
| 111 |
logging.error(f"Error during audio transcription for {file_path}: {e}")
|
| 112 |
+
if "authentication" in str(e).lower():
|
| 113 |
+
return f"ERROR: Authentication error. Check OPENAI_API_KEY."
|
| 114 |
+
return f"ERROR: Could not transcribe audio file {file_path}. Details: {e}"
|
| 115 |
+
|
|
|
|
| 116 |
|
| 117 |
def analyze_excel(file_path: str, question: str) -> str:
|
| 118 |
"""Analyzes an Excel file using pandas, tailored for Q19."""
|
| 119 |
if not Path(file_path).is_file():
|
| 120 |
return f"ERROR: Excel file not found at {file_path}"
|
| 121 |
try:
|
| 122 |
+
df = pd.read_excel(file_path, engine='openpyxl')
|
| 123 |
+
# Flexible column detection
|
| 124 |
+
cols = [col.lower() for col in df.columns]
|
| 125 |
+
type_col = next((df.columns[i] for i,c in enumerate(cols) if 'type' in c or 'category' in c), None)
|
| 126 |
+
sales_col = next((df.columns[i] for i,c in enumerate(cols) if 'sale' in c), None)
|
| 127 |
+
if not type_col or not sales_col:
|
| 128 |
+
logging.error(f"Could not find 'type/category' or 'sales' in columns: {df.columns.tolist()}")
|
| 129 |
+
return "ERROR: Could not find necessary 'Category/Type' or 'Sales' columns in the Excel file."
|
| 130 |
+
food_df = df[~df[type_col].str.contains('drink', case=False, na=False)]
|
| 131 |
+
total = food_df[sales_col].sum()
|
| 132 |
+
return f"${total:,.2f}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
+
logging.error(f"Error analyzing Excel file {file_path}: {e}")
|
| 135 |
+
return f"ERROR: Could not analyze Excel file {file_path}. Details: {e}"
|
| 136 |
+
|
| 137 |
|
| 138 |
def analyze_chess_image_gpt4o(file_path: str) -> str:
|
| 139 |
"""Analyzes a chess image using GPT-4o Vision to find the winning move for Black."""
|
|
|
|
| 142 |
try:
|
| 143 |
logging.info(f"Analyzing chess image using GPT-4o: {file_path}")
|
| 144 |
with open(file_path, "rb") as image_file:
|
| 145 |
+
b64 = base64.b64encode(image_file.read()).decode()
|
| 146 |
+
llm = ChatOpenAI(model="gpt-4o", max_tokens=50)
|
| 147 |
+
prompt = [
|
| 148 |
+
SystemMessage(content="You are an expert chess engine assistant. Black to move; provide only the SAN of the winning move."),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
HumanMessage(content=[
|
| 150 |
+
{"type": "text", "text": "Here is the position (black to move). Provide only the SAN of the best winning move."},
|
| 151 |
+
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}
|
| 152 |
])
|
| 153 |
]
|
| 154 |
+
resp = llm.invoke(prompt)
|
| 155 |
+
move = resp.content.strip().replace('`','')
|
| 156 |
+
m = re.match(r"^([NBRQK]?[a-h]?[1-8]?[x]?[a-h][1-8](=[NBRQ])?[+#]?|O-O(?:-O)?)", move)
|
| 157 |
+
return m.group(1) if m else move
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
except Exception as e:
|
| 159 |
+
logging.error(f"Error in chess analysis: {e}")
|
| 160 |
+
return f"ERROR: Unexpected error processing chess image: {e}"
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
def run_python_script(file_path: str) -> str:
|
| 164 |
"""Executes a Python script using subprocess and returns its final output."""
|
| 165 |
if not Path(file_path).is_file():
|
| 166 |
return f"ERROR: Python script not found at {file_path}"
|
| 167 |
try:
|
| 168 |
+
proc = subprocess.run([sys.executable, str(file_path)], capture_output=True, text=True, timeout=30)
|
| 169 |
+
out, err = proc.stdout.strip(), proc.stderr.strip()
|
| 170 |
+
if proc.returncode != 0:
|
| 171 |
+
msg = f"ERROR: Python script failed with code {proc.returncode}."
|
| 172 |
+
if err: msg += f" Error: {err}"
|
| 173 |
+
return msg
|
| 174 |
+
lines = [l for l in out.splitlines() if l.strip()]
|
| 175 |
+
return lines[-1] if lines else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
except Exception as e:
|
| 177 |
+
return f"ERROR: Failed to execute Python script. Details: {e}"
|
| 178 |
+
|
| 179 |
|
|
|
|
| 180 |
class SabonzoAgent:
|
| 181 |
def __init__(self, api_url: str):
|
| 182 |
self.api_url = api_url
|
| 183 |
self.temp_dir = tempfile.mkdtemp()
|
| 184 |
+
self.llm = ChatOpenAI(model="gpt-4o", temperature=0)
|
| 185 |
+
# Tools setup...
|
|
|
|
|
|
|
|
|
|
| 186 |
tavily_key = os.getenv("TAVILY_API_KEY")
|
| 187 |
+
self.tools = [TavilySearchResults(max_results=3)] if tavily_key else [DuckDuckGoSearchRun()]
|
| 188 |
+
api_wrapper = WikipediaAPIWrapper(top_k_results=3, doc_content_chars_max=6000, lang='en', load_all_available_meta=False,
|
| 189 |
+
wiki_client_args={'headers': {'User-Agent': 'SabonzoAgent/1.0'}})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
self.tools.append(WikipediaQueryRun(api_wrapper=api_wrapper))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
prompt_template = ChatPromptTemplate.from_messages([
|
| 192 |
+
("system", "You are a specialized AI assistant. Use provided analysis directly. Return ONLY the final answer."),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
MessagesPlaceholder(variable_name="chat_history", optional=True),
|
| 194 |
+
("human", "{input}\n{analysis_context}"),
|
| 195 |
+
MessagesPlaceholder(variable_name="agent_scratchpad")
|
| 196 |
])
|
|
|
|
| 197 |
self.agent = create_openai_tools_agent(self.llm, self.tools, prompt_template)
|
| 198 |
+
self.agent_executor = AgentExecutor(agent=self.agent, tools=self.tools, verbose=False, max_iterations=6)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
+
def call(self, question: str, task_id: str) -> str:
|
|
|
|
| 201 |
file_path = None
|
| 202 |
analysis_result = None
|
|
|
|
| 203 |
q_lower = question.lower()
|
| 204 |
+
# Download and handle per-task logic
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
try:
|
| 206 |
+
if task_id == '7' or 'youtu' in q_lower:
|
| 207 |
+
# Use Mazmazika to download audio
|
| 208 |
+
youtube_url = re.search(r'https?://[^\s]+', question).group(0)
|
| 209 |
+
file_path = download_youtube_audio_via_mazmazika(youtube_url, self.temp_dir, task_id)
|
| 210 |
+
if not file_path:
|
| 211 |
+
return "ERROR: Audio file for Teal'c quote was expected but not found/downloaded via Mazmazika."
|
| 212 |
+
transcript = transcribe_audio(str(file_path))
|
| 213 |
+
if transcript.startswith("ERROR"): return transcript
|
| 214 |
+
prompt = (
|
| 215 |
+
f"Transcript: '''{transcript}'''\n\nQuestion: What exact words does Teal'c say in response to the question 'Isn't that hot?'? "
|
| 216 |
+
"Respond with ONLY his exact words, no quotes or other text."
|
| 217 |
+
)
|
| 218 |
+
resp = self.llm.invoke([HumanMessage(content=prompt)])
|
| 219 |
+
analysis_result = resp.content.strip().strip('"')
|
| 220 |
+
|
| 221 |
+
elif task_id == '4' or 'chess' in q_lower:
|
| 222 |
+
# Chess image
|
| 223 |
+
file_path = download_file(f"{self.api_url}/files/{task_id}", self.temp_dir, task_id)
|
| 224 |
+
analysis_result = analyze_chess_image_gpt4o(str(file_path)) if file_path else "ERROR: Chess image file not found."
|
| 225 |
+
|
| 226 |
+
elif task_id == '19' or ('excel' in q_lower and 'sales' in q_lower):
|
| 227 |
+
file_path = download_file(f"{self.api_url}/files/{task_id}", self.temp_dir, task_id)
|
| 228 |
+
analysis_result = analyze_excel(str(file_path), question) if file_path else "ERROR: Excel file not found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
else:
|
| 231 |
+
# Fallback to agent for all other questions
|
| 232 |
+
response = self.agent_executor.invoke({"input": question, "analysis_context": ""})
|
| 233 |
+
analysis_result = response.get("output", "ERROR: Agent did not produce an output.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
except Exception as e:
|
| 235 |
+
logging.error(f"Error in agent call for task {task_id}: {e}")
|
| 236 |
+
analysis_result = f"ERROR: Agent execution failed. Details: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
+
# Cleanup downloaded file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
if file_path and Path(file_path).exists():
|
| 240 |
+
try: os.remove(file_path)
|
| 241 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
+
return analysis_result.strip()
|
| 244 |
|
| 245 |
def cleanup(self):
|
|
|
|
| 246 |
if hasattr(self, 'temp_dir') and Path(self.temp_dir).exists():
|
| 247 |
+
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
|
|
|
|
|
|
| 248 |
|
| 249 |
# --- Gradio App Setup ---
|
|
|
|
| 250 |
agent_instance = None
|
| 251 |
|
| 252 |
def initialize_agent():
|
|
|
|
| 253 |
global agent_instance
|
| 254 |
if agent_instance is None:
|
| 255 |
+
agent_instance = SabonzoAgent(api_url=os.getenv("SCORING_API_URL", DEFAULT_API_URL))
|
|
|
|
|
|
|
|
|
|
| 256 |
return agent_instance
|
| 257 |
|
| 258 |
+
|
| 259 |
def run_evaluation(profile: gr.OAuthProfile | None):
|
|
|
|
| 260 |
if not profile:
|
| 261 |
+
return "Please Login to Hugging Face.", pd.DataFrame()
|
| 262 |
+
user = profile.username
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
api_url = os.getenv("SCORING_API_URL", DEFAULT_API_URL)
|
| 264 |
questions_url = f"{api_url}/questions"
|
| 265 |
+
resp = requests.get(questions_url, timeout=60)
|
| 266 |
+
resp.raise_for_status()
|
| 267 |
+
questions = resp.json()
|
| 268 |
+
results = []
|
| 269 |
+
agent = initialize_agent()
|
| 270 |
+
for item in questions:
|
| 271 |
+
tid = str(item.get("task_id"))
|
| 272 |
+
q = item.get("question")
|
| 273 |
+
ans = agent.call(q, tid)
|
| 274 |
+
results.append({"Task ID": tid, "Question": q, "Answer": ans})
|
| 275 |
+
df = pd.DataFrame(results)
|
| 276 |
+
# Submit if enabled
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
if ENABLE_SUBMISSION:
|
| 278 |
+
sub_url = f"{api_url}/submit"
|
| 279 |
+
payload = {"username": user, "agent_code": "app.py", "answers": [{"task_id": r["Task ID"], "submitted_answer": r["Answer"]} for r in results]}
|
| 280 |
+
sub_resp = requests.post(sub_url, json=payload, timeout=180)
|
| 281 |
+
# ignore detailed handling here
|
| 282 |
+
agent.cleanup()
|
| 283 |
+
return "Done", df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
with gr.Blocks() as demo:
|
| 286 |
gr.Markdown("# GAIA Agent Evaluation - Sabonzo")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
gr.LoginButton()
|
| 288 |
+
run_btn = gr.Button("Run Evaluation & Submit")
|
| 289 |
+
status = gr.Textbox(label="Status")
|
| 290 |
+
table = gr.DataFrame(label="Results")
|
| 291 |
+
run_btn.click(fn=run_evaluation, outputs=[status, table], api_name="run_evaluation")
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
if __name__ == "__main__":
|
| 294 |
+
print("Starting Gradio App...")
|
| 295 |
+
initialize_agent()
|
| 296 |
+
demo.launch(debug=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|