Mauricio Mercado
changes to agent, add memory and proper download of files
f96a4ce unverified
Raw History Blame Contribute Delete
27.5 kB
import os
import traceback
import pandas as pd
import gradio as gr
import requests
from typing import Dict, List, Optional, Tuple
from pathlib import Path
import dotenv
dotenv.load_dotenv()
# Import smolagents correctly
from smolagents import CodeAgent, Tool, OpenAIServerModel, DuckDuckGoSearchTool, PythonInterpreterTool
# --- Configuration ---
API_ENDPOINT = "https://agents-course-unit4-scoring.hf.space"
DEFAULT_MODEL = "gpt-4o-mini-2024-07-18"
# --- Custom Tool Implementations ---
class VideoTranscriptTool(Tool):
"""Extract transcripts from YouTube videos"""
name = "video_transcript"
description = "Extract text transcript from YouTube videos with optional timestamps"
inputs = {
"video_url": {"type": "string", "description": "YouTube video URL or ID"},
"include_timestamps": {"type": "boolean", "description": "Whether to include timestamps in output", "nullable": True}
}
output_type = "string"
def forward(self, video_url: str, include_timestamps: bool = False) -> str:
"""Extract transcript from YouTube video"""
from youtube_transcript_api import YouTubeTranscriptApi
# Extract video ID from different URL formats
if "youtube.com/watch" in video_url:
video_id = video_url.split("v=")[1].split("&")[0]
elif "youtu.be/" in video_url:
video_id = video_url.split("youtu.be/")[1].split("?")[0]
elif len(video_url.strip()) == 11: # Direct ID
video_id = video_url.strip()
else:
return f"Invalid YouTube URL or ID: {video_url}"
try:
transcript_data = YouTubeTranscriptApi.get_transcript(video_id)
if include_timestamps:
formatted_transcript = []
for entry in transcript_data:
time_str = f"{int(entry['start']//60)}:{int(entry['start']%60):02d}"
formatted_transcript.append(f"[{time_str}] {entry['text']}")
return "\n".join(formatted_transcript)
else:
return " ".join([entry['text'] for entry in transcript_data])
except Exception as e:
return f"Failed to retrieve YouTube transcript: {str(e)}"
class AudioTranscriptionTool(Tool):
"""Convert audio files to text using Whisper"""
name = "audio_transcription"
description = "Transcribe audio files (.mp3, .wav) to text using Whisper"
inputs = {
"audio_path": {"type": "string", "description": "Path to the audio file"}
}
output_type = "string"
def __init__(self):
super().__init__()
self._whisper_model = None
def _load_model(self):
"""Load the Whisper model if not already loaded"""
if self._whisper_model is None:
import whisper
self._whisper_model = whisper.load_model("base")
return self._whisper_model
def forward(self, audio_path: str) -> str:
"""Transcribe audio file to text"""
if not os.path.exists(audio_path):
return f"Error: Audio file not found at {audio_path}"
try:
model = self._load_model()
result = model.transcribe(audio_path)
return result.get("text", "No transcription produced")
except Exception as e:
return f"Audio transcription failed: {str(e)}"
class SemanticQueryTool(Tool):
"""Query semantic knowledge bases using SPARQL"""
name = "semantic_query"
description = "Execute SPARQL queries against Wikidata knowledge graph"
inputs = {
"sparql_query": {"type": "string", "description": "SPARQL query to execute"}
}
output_type = "string"
def forward(self, sparql_query: str) -> str:
"""Execute SPARQL query and return results"""
from SPARQLWrapper import SPARQLWrapper, JSON
import json
try:
endpoint = SPARQLWrapper("https://query.wikidata.org/sparql")
endpoint.setQuery(sparql_query)
endpoint.setReturnFormat(JSON)
results = endpoint.query().convert()
return json.dumps(results, indent=2)
except Exception as e:
return f"Error executing SPARQL query: {str(e)}"
class ChessAnalysisTool(Tool):
"""Analyze chess positions using Stockfish"""
name = "chess_analysis"
description = "Analyze chess positions and find the best move using Stockfish"
inputs = {
"position": {"type": "string", "description": "Chess position in FEN notation"},
"analysis_depth": {"type": "number", "description": "Analysis time in seconds", "nullable": True}
}
output_type = "string"
def forward(self, position: str, analysis_depth: float = 0.5) -> str:
"""Analyze chess position and return best move"""
import chess
import chess.engine
import shutil
# Find Stockfish binary
stockfish_path = shutil.which("stockfish")
if not stockfish_path:
stockfish_path = "/usr/games/stockfish" # Common location in Linux
if not os.path.exists(stockfish_path):
return "Stockfish chess engine not found. Please install it first."
try:
# Set up board and engine
board = chess.Board(position)
engine = chess.engine.SimpleEngine.popen_uci(stockfish_path)
# Analyze position
result = engine.play(board, chess.engine.Limit(time=analysis_depth))
move = board.san(result.move)
# Get position evaluation
info = engine.analyse(board, chess.engine.Limit(time=analysis_depth/2))
score = info.get("score", "")
# Clean up
engine.quit()
return f"Best move: {move}\nEvaluation: {score}"
except Exception as e:
return f"Chess analysis failed: {str(e)}"
class TextProcessingTool(Tool):
"""Process text using regular expressions"""
name = "text_processor"
description = "Process text using regular expressions for pattern matching and replacement"
inputs = {
"input_text": {"type": "string", "description": "Text to process"},
"regex_pattern": {"type": "string", "description": "Regular expression pattern"},
"replacement": {"type": "string", "description": "Replacement text", "nullable": True}
}
output_type = "string"
def forward(self, input_text: str, regex_pattern: str, replacement: str = "") -> str:
"""Apply regex pattern to text"""
import re
try:
result = re.sub(regex_pattern, replacement, input_text)
return result
except Exception as e:
return f"Regex operation failed: {str(e)}"
class DataTableTool(Tool):
"""Parse and process tabular data"""
name = "data_table"
description = "Parse and analyze tables from text (markdown, ASCII) into structured data"
inputs = {
"table_text": {"type": "string", "description": "Table text in markdown or ASCII format"}
}
output_type = "string"
def forward(self, table_text: str) -> str:
"""Parse table text into DataFrame"""
import re
from io import StringIO
try:
# Clean up table format (remove pipes at beginning/end of lines)
cleaned_text = re.sub(r"^\s*\||\|\s*$", "", table_text, flags=re.MULTILINE)
# Parse with pandas
df = pd.read_csv(StringIO(cleaned_text), sep=r"\s*\|\s*", engine="python")
return df.to_string()
except Exception as e:
# Return empty DataFrame with error message as column
return f"Failed to parse table: {str(e)}"
class MathematicalTool(Tool):
"""Solve mathematical expressions and equations"""
name = "math_solver"
description = "Solve mathematical expressions and equations using sympy or numeric evaluation"
inputs = {
"expression": {"type": "string", "description": "Mathematical expression or equation to solve"}
}
output_type = "string"
def forward(self, expression: str) -> str:
"""Evaluate mathematical expressions"""
try:
# Try sympy for symbolic math
import sympy as sp
# Check if it's an equation to solve
if "=" in expression:
parts = expression.split("=")
if len(parts) == 2:
lhs = sp.sympify(parts[0])
rhs = sp.sympify(parts[1])
eq = sp.Eq(lhs, rhs)
# Get unknown variable
symbols = list(eq.free_symbols)
if symbols:
var = symbols[0] # Take first symbol as variable to solve for
solution = sp.solve(eq, var)
return f"Solution: {var} = {solution}"
# Try as direct expression
result = sp.sympify(expression)
if hasattr(result, "evalf"):
return f"Result: {result.evalf()}"
return f"Result: {result}"
except Exception as e:
# Fall back to numeric evaluation
try:
# Create a safe environment for eval
safe_globals = {"__builtins__": {}}
safe_locals = {
"abs": abs, "max": max, "min": min, "sum": sum,
"pow": pow, "round": round
}
result = eval(expression, safe_globals, safe_locals)
return f"Numeric result: {result}"
except Exception as e2:
return f"Failed to evaluate expression: {str(e2)}"
class FileContentTool(Tool):
"""Read and process different file types"""
name = "file_content"
description = "Read and process content from various file types (text, PDF, Excel)"
inputs = {
"file_path": {"type": "string", "description": "Path to the file"},
"file_type": {"type": "string", "description": "Type of file (auto, text, pdf, excel)", "nullable": True}
}
output_type = "string"
def forward(self, file_path: str, file_type: str = "auto") -> str:
"""Read and process file content"""
if not os.path.exists(file_path):
return f"Error: File not found at {file_path}"
# Auto-detect file type if needed
if file_type == "auto":
extension = os.path.splitext(file_path)[1].lower()
if extension in [".txt", ".md", ".json", ".csv", ".py", ".js", ".html", ".css"]:
file_type = "text"
elif extension == ".pdf":
file_type = "pdf"
elif extension in [".xlsx", ".xls"]:
file_type = "excel"
else:
return f"Unsupported file extension: {extension}"
# Process based on file type
if file_type == "text":
return self._process_text(file_path)
elif file_type == "pdf":
return self._process_pdf(file_path)
elif file_type == "excel":
return self._process_excel(file_path)
else:
return f"Unsupported file type: {file_type}"
def _process_text(self, file_path: str) -> str:
"""Read text file content"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Truncate if too long
if len(content) > 10000:
content = content[:10000] + "\n...\n[Content truncated]"
return content
except Exception as e:
return f"Error reading text file: {str(e)}"
def _process_pdf(self, file_path: str) -> str:
"""Extract text from PDF"""
try:
import PyPDF2
with open(file_path, 'rb') as f:
reader = PyPDF2.PdfReader(f)
# Get page count
page_count = len(reader.pages)
# Extract text from all pages
text = []
for i in range(page_count):
page = reader.pages[i]
text.append(page.extract_text())
result = "\n\n".join(text)
# Truncate if too long
if len(result) > 10000:
result = result[:10000] + "\n...\n[Content truncated]"
return result or "No text content extracted from PDF"
except Exception as e:
return f"Error processing PDF: {str(e)}"
def _process_excel(self, file_path: str) -> str:
"""Process Excel file"""
try:
df = pd.read_excel(file_path)
# Create summary
summary = f"Excel file: {os.path.basename(file_path)}\n"
summary += f"Dimensions: {df.shape[0]} rows Γ— {df.shape[1]} columns\n\n"
summary += "Columns:\n" + "\n".join(f"- {col}" for col in df.columns) + "\n\n"
summary += "Preview (first 5 rows):\n"
summary += df.head(5).to_string()
return summary
except Exception as e:
return f"Error processing Excel file: {str(e)}"
class ImageAnalysisTool(Tool):
"""Analyze images using OpenAI's vision models"""
name = "image_analyzer"
description = "Analyze image content and extract information using AI"
inputs = {
"image_path": {"type": "string", "description": "Path to the image file"}
}
output_type = "string"
def forward(self, image_path: str) -> str:
"""Analyze image content"""
if not os.path.exists(image_path):
return f"Error: Image file not found at {image_path}"
try:
import base64
# Get API key
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
return "OpenAI API key not found in environment variables"
# Read and encode image
with open(image_path, "rb") as img_file:
encoded_img = base64.b64encode(img_file.read()).decode('utf-8')
# Set up API request
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": DEFAULT_MODEL,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this image in detail. Describe what you see, including objects, people, text, and other relevant elements."},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded_img}"}}
]
}
],
"max_tokens": 500
}
# Send request
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=payload
)
# Process response
if response.status_code == 200:
result = response.json()
analysis = result["choices"][0]["message"]["content"]
return analysis
else:
return f"API request failed: {response.status_code} - {response.text}"
except Exception as e:
return f"Image analysis failed: {str(e)}"
class DownloadTaskAttachmentTool(Tool):
"""Download files attached to tasks"""
name = "download_file"
description = "Downloads the file attached to the task ID. Use this when the task requires accessing a file."
inputs = {
'task_id': {'type': 'string', 'description': 'The task id to download attachment from.'}
}
output_type = "string"
def forward(self, task_id: str) -> str:
"""Download file attached to a task"""
from pathlib import Path
# Create downloads directory if it doesn't exist
downloads_dir = Path("downloads")
downloads_dir.mkdir(exist_ok=True)
try:
# Construct the file download URL
file_url = f"{API_ENDPOINT}/files/{task_id}"
print(f"Downloading file from: {file_url}")
# Send the request to download the file
response = requests.get(file_url, stream=True, timeout=30)
response.raise_for_status()
# Try to get the filename from the Content-Disposition header
content_disposition = response.headers.get('Content-Disposition', '')
if 'filename=' in content_disposition:
filename = content_disposition.split('filename=')[1].strip('"\'')
else:
# Use task_id as filename with appropriate extension based on content type
content_type = response.headers.get('Content-Type', '')
if 'image/png' in content_type:
filename = f"{task_id}.png"
elif 'image/jpeg' in content_type:
filename = f"{task_id}.jpg"
elif 'audio/mpeg' in content_type:
filename = f"{task_id}.mp3"
elif 'application/pdf' in content_type:
filename = f"{task_id}.pdf"
elif 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' in content_type:
filename = f"{task_id}.xlsx"
elif 'text/plain' in content_type:
filename = f"{task_id}.txt"
else:
filename = f"{task_id}.bin"
# Save the file to the downloads directory
file_path = downloads_dir / filename
with open(file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
return str(file_path)
except requests.exceptions.RequestException as e:
return f"Error downloading file: {str(e)}"
except Exception as e:
return f"Unexpected error downloading file: {str(e)}"
# --- Main Assistant Class ---
class SmartAssistant:
"""Advanced agent with multiple tool capabilities"""
def __init__(self):
"""Initialize the assistant with all tools"""
print("Initializing SmartAssistant...")
# Set up model
self.model = OpenAIServerModel(model_id=DEFAULT_MODEL)
# Initialize custom tools
self.tools = [
VideoTranscriptTool(),
AudioTranscriptionTool(),
SemanticQueryTool(),
ChessAnalysisTool(),
TextProcessingTool(),
DataTableTool(),
MathematicalTool(),
FileContentTool(),
ImageAnalysisTool(),
DownloadTaskAttachmentTool(),
DuckDuckGoSearchTool(),
PythonInterpreterTool(),
]
# Create agent
self.agent = CodeAgent(
model=self.model,
tools=self.tools,
add_base_tools=True
)
print("SmartAssistant initialized successfully")
def answer_question(self, question: str) -> str:
"""Process a question and return the answer"""
print(f"Processing question: {question[:50]}..." if len(question) > 50 else question)
try:
result = self.agent.run(question)
# Ensure result is always a string
if not isinstance(result, str):
result = str(result)
return result
except Exception as e:
print(traceback.format_exc())
error_msg = f"Error running agent: {str(e)}"
return f"I encountered an issue while processing your question: {str(e)}"
def download_file(self, task_id: str) -> str:
"""Download a file attached to a task"""
# Find the download_file tool
download_tool = next((tool for tool in self.tools if tool.name == "download_file"), None)
if not download_tool:
raise ValueError("File download tool not available")
# Download the file
file_path = download_tool.forward(task_id)
if "Error" in file_path:
raise ValueError(f"File download failed: {file_path}")
return file_path
# --- Evaluation Functions ---
def evaluate_and_submit(profile: Optional[gr.OAuthProfile] = None) -> Tuple[str, Optional[pd.DataFrame]]:
"""Run evaluation and submit results"""
# Check if user is logged in
if not profile:
return "Please log in with your Hugging Face account first.", None
username = profile.username.strip()
print(f"Starting evaluation for user: {username}")
# Get space ID for code URL
space_id = os.getenv("SPACE_ID")
if not space_id:
return "Environment error: SPACE_ID not found. Cannot determine code URL.", None
code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
try:
# Initialize assistant
assistant = SmartAssistant()
# Fetch questions
print(f"Fetching questions from {API_ENDPOINT}/questions")
response = requests.get(f"{API_ENDPOINT}/questions", timeout=15)
response.raise_for_status()
questions = response.json()
if not questions:
return "Error: Received empty questions list from server.", None
print(f"Successfully fetched {len(questions)} questions")
# Process all questions
results_log = []
answers_payload = []
for item in questions:
task_id = item.get("task_id")
question_text = item.get("question")
file_name = item.get("file_name")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
print(f"Processing task {task_id}: {question_text[:50]}...")
# Download file if required
if file_name:
try:
file_path = assistant.download_file(task_id)
print(f"File for task {task_id} saved at: {file_path}")
# Include file path in the question
submitted_answer = assistant.answer_question(f"{question_text} (File: {file_path})")
except Exception as file_error:
print(f"Error downloading file for task {task_id}: {file_error}")
submitted_answer = assistant.answer_question(f"{question_text} (Note: There was an error downloading the associated file: {str(file_error)})")
else:
submitted_answer = assistant.answer_question(question_text)
# Store results
answers_payload.append({
"task_id": task_id,
"submitted_answer": submitted_answer
})
results_log.append({
"Task ID": task_id,
"Question": question_text,
"Answer": submitted_answer
})
print(f"Task {task_id} processed successfully")
except Exception as e:
error_msg = f"Error on task {task_id}: {str(e)}"
print(error_msg)
results_log.append({
"Task ID": task_id,
"Question": question_text,
"Answer": f"ERROR: {str(e)}"
})
# Submit answers
if not answers_payload:
return "No answers were generated to submit.", pd.DataFrame(results_log)
# Prepare submission
submission_data = {
"username": username,
"agent_code": code_url,
"answers": answers_payload
}
# Submit answers
print(f"Submitting {len(answers_payload)} answers to {API_ENDPOINT}/submit")
response = requests.post(
f"{API_ENDPOINT}/submit",
json=submission_data,
timeout=60
)
response.raise_for_status()
# Process results
result = response.json()
status_message = (
f"βœ… Evaluation Complete!\n"
f"User: {result.get('username')}\n"
f"Overall Score: {result.get('score', 'N/A')}% "
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
f"Feedback: {result.get('message', 'No feedback provided.')}"
)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"HTTP Error: {e.response.status_code}"
try:
error_json = e.response.json()
error_detail += f" - {error_json.get('detail', '')}"
except:
error_detail += f" - {e.response.text[:200]}"
return f"Submission failed: {error_detail}", None
except Exception as e:
error_message = f"Evaluation failed: {str(e)}"
print(error_message)
print(traceback.format_exc())
# Return partial results if available
results_df = pd.DataFrame(results_log) if 'results_log' in locals() else None
return error_message, results_df
# --- Gradio Interface ---
with gr.Blocks(title="AI Assistant Evaluation") as interface:
gr.Markdown("# AI Assistant Evaluation Platform")
gr.Markdown("""
**Instructions:**
1. Log in to your Hugging Face account
2. Click 'Run Evaluation' to process all questions and see your score
Note: Processing may take several minutes depending on the complexity of questions.
""")
# Login component
gr.LoginButton()
# Evaluation button
eval_button = gr.Button("Start Evaluation", variant="primary")
# Results display
status_display = gr.Textbox(
label="Evaluation Status",
placeholder="Results will appear here after evaluation",
lines=6
)
results_display = gr.DataFrame(
label="Question Results",
headers=["Task ID", "Question", "Answer"],
wrap=True
)
# Connect components
eval_button.click(
fn=evaluate_and_submit,
outputs=[status_display, results_display]
)
gr.Markdown("""
### About
This evaluation system uses an advanced AI assistant powered by the smolagents library with multiple capabilities:
- Web search and information retrieval
- Document analysis (text, PDF, Excel)
- Media processing (YouTube transcripts, audio)
- Mathematical problem solving
- Strategic game analysis (chess)
- Image analysis and interpretation
""")
# --- Main Execution ---
if __name__ == "__main__":
print("\n" + "-"*30 + " App Starting " + "-"*30)
# Check for SPACE_HOST and SPACE_ID at startup for information
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup:
print(f"βœ… SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
if space_id_startup:
print(f"βœ“ Space ID: {space_id_startup}")
print(f" Repository URL: https://huggingface.co/spaces/{space_id_startup}")
# Launch interface
print("\nLaunching evaluation interface...")
interface.launch(debug=True, share=False)