unit-40-sa / tools.py
sabler
Remove the URL for now
f60d19b unverified
import io
import openpyxl
import os
from smolagents import tool
import requests
from PIL import Image
@tool
def tool_reverse_string(text: str) -> str:
"""
Use this tool only if you encounter text that seems to be written backwards
Args:
text: The string to reverse.
"""
return text[::-1]
@tool
def tool_read_files(filepath: str) -> str:
"""
Downloads a .py or .xlsx file from a remote URL and returns its contents as plain text.
Raises a recoverable exception if the file does not end with .py or .xlsx.
Args:
filepath: The path to the Python (.py) or Excel (.xlsx) file.
"""
root_url = "https://agents-course-unit4-scoring.hf.space/files/"
# Strip the file extension from the url before downloading
import os
base, ext = os.path.splitext(filepath)
url = root_url + base
if filepath.endswith('.py'):
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Recoverable: Failed to download file from {url}")
return response.text
elif filepath.endswith('.xlsx'):
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Recoverable: Failed to download file from {url}")
wb = openpyxl.load_workbook(io.BytesIO(response.content), data_only=True)
result = []
for sheet in wb.worksheets:
result.append(f"# Sheet: {sheet.title}")
for row in sheet.iter_rows(values_only=True):
result.append(','.join([str(cell) if cell is not None else '' for cell in row]))
return '\n'.join(result)
else:
raise Exception("Recoverable: Only .py and .xlsx files can be read with this tool.")
@tool
def tool_download_image(filepath: str) -> str:
"""
Downloads an image file (.png, .jpg, .jpeg) from a remote URL and returns useful information about the image.
This includes the image URL and basic metadata like dimensions and format.
Raises a recoverable exception if the file is not a supported image type.
Args:
filepath: The path to the image file.
"""
root_url = "https://agents-course-unit4-scoring.hf.space/files/"
base, ext = os.path.splitext(filepath)
url = root_url + base
if ext.lower() in ['.png', '.jpg', '.jpeg']:
response = requests.get(url)
if response.status_code != 200:
raise Exception(f"Recoverable: Failed to download image from {url}")
# Get image metadata using Pillow
try:
img = Image.open(io.BytesIO(response.content))
width, height = img.size
format = img.format
mode = img.mode
# Return useful information about the image
return f"Image URL: {url}\nFormat: {format}\nDimensions: {width}x{height}\nMode: {mode}"
except ImportError:
# Fallback if PIL is not available
content_type = response.headers.get('Content-Type', 'unknown')
content_length = response.headers.get('Content-Length', 'unknown')
return f"Content-Type: {content_type}\nSize: {content_length} bytes"
else:
raise Exception("Recoverable: Only .png, .jpg, and .jpeg files can be processed with this tool.")