Spaces:
Build error
Build error
Update agents/tools.py
Browse files- agents/tools.py +121 -94
agents/tools.py
CHANGED
|
@@ -1,147 +1,174 @@
|
|
| 1 |
import os
|
| 2 |
-
import uuid
|
| 3 |
import tempfile
|
| 4 |
-
|
| 5 |
from typing import Optional
|
| 6 |
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
@tool
|
| 12 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
-
|
| 15 |
|
| 16 |
Args:
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
Returns:
|
| 21 |
-
|
| 22 |
"""
|
| 23 |
-
|
| 24 |
-
if
|
| 25 |
-
|
| 26 |
-
filepath = temp_file.name
|
| 27 |
else:
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
@tool
|
| 37 |
-
def
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
-
|
| 40 |
|
| 41 |
Args:
|
| 42 |
-
|
| 43 |
-
filename (Optional[str]): Optional filename. If None, it's derived from the URL or randomized.
|
| 44 |
|
| 45 |
Returns:
|
| 46 |
-
|
| 47 |
"""
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
filepath = os.path.join(temp_dir, filename)
|
| 57 |
-
|
| 58 |
-
# Stream download
|
| 59 |
-
response = requests.get(url, stream=True, timeout=15)
|
| 60 |
-
response.raise_for_status()
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
return f"Error downloading file: {str(e)}"
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
@tool
|
| 73 |
-
def
|
|
|
|
|
|
|
|
|
|
| 74 |
"""
|
| 75 |
-
|
| 76 |
|
| 77 |
Args:
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
Returns:
|
| 81 |
-
|
| 82 |
"""
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
image = Image.open(image_path)
|
| 88 |
-
text = pytesseract.image_to_string(image)
|
| 89 |
-
return f"Extracted text from image:\n\n{text}"
|
| 90 |
-
except ImportError:
|
| 91 |
-
return "Error: pytesseract or Pillow not installed. Please install them with 'pip install pytesseract pillow'."
|
| 92 |
-
except Exception as e:
|
| 93 |
-
return f"Error extracting text from image: {str(e)}"
|
| 94 |
-
|
| 95 |
|
| 96 |
@tool
|
| 97 |
-
def
|
|
|
|
|
|
|
|
|
|
| 98 |
"""
|
| 99 |
-
|
| 100 |
|
| 101 |
Args:
|
| 102 |
-
file_path
|
| 103 |
-
query
|
| 104 |
|
| 105 |
Returns:
|
| 106 |
-
|
| 107 |
"""
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
except Exception as e:
|
| 119 |
-
return f"Error analyzing CSV file: {str(e)}"
|
| 120 |
-
|
| 121 |
|
| 122 |
@tool
|
| 123 |
-
def
|
|
|
|
|
|
|
| 124 |
"""
|
| 125 |
-
|
| 126 |
|
| 127 |
Args:
|
| 128 |
-
|
| 129 |
-
query (str): The question or analysis request for the Excel data.
|
| 130 |
|
| 131 |
Returns:
|
| 132 |
-
|
| 133 |
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 140 |
-
result += "Summary statistics:\n" + df.describe().to_string()
|
| 141 |
-
return result
|
| 142 |
-
except ImportError:
|
| 143 |
-
return "Error: pandas or openpyxl not installed. Please install them with 'pip install pandas openpyxl'."
|
| 144 |
-
except Exception as e:
|
| 145 |
-
return f"Error analyzing Excel file: {str(e)}"
|
| 146 |
|
| 147 |
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import tempfile
|
| 3 |
+
import io
|
| 4 |
from typing import Optional
|
| 5 |
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import whisper
|
| 8 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 9 |
+
import pytesseract
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import chess
|
| 12 |
+
import chess.engine
|
| 13 |
+
import fitz # PyMuPDF
|
| 14 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 15 |
+
from smolagents import tool, PythonInterpreterTool
|
| 16 |
|
| 17 |
@tool
|
| 18 |
+
def sum_sales_by_category(
|
| 19 |
+
file_path: str,
|
| 20 |
+
sheet_name: Optional[str] = None,
|
| 21 |
+
category_column: str = "Category",
|
| 22 |
+
exclude_category: str = "Drinks",
|
| 23 |
+
sales_column: str = "Sales"
|
| 24 |
+
) -> str:
|
| 25 |
"""
|
| 26 |
+
Load a CSV or Excel file and sum the sales for items not in exclude_category.
|
| 27 |
|
| 28 |
Args:
|
| 29 |
+
file_path: Path to the CSV (.csv) or Excel (.xlsx) file.
|
| 30 |
+
sheet_name: Name of the sheet to load (only for Excel files). Defaults to None.
|
| 31 |
+
category_column: Column name that holds the item categories.
|
| 32 |
+
exclude_category: Category value to exclude (e.g. "Drinks").
|
| 33 |
+
sales_column: Column name that holds the sales figures.
|
| 34 |
|
| 35 |
Returns:
|
| 36 |
+
The total sales (excluding the specified category), formatted as a decimal string to two places.
|
| 37 |
"""
|
| 38 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 39 |
+
if ext == ".csv":
|
| 40 |
+
df = pd.read_csv(file_path)
|
|
|
|
| 41 |
else:
|
| 42 |
+
df = pd.read_excel(file_path, sheet_name=sheet_name)
|
| 43 |
+
filtered = df[df[category_column] != exclude_category]
|
| 44 |
+
total = float(filtered[sales_column].sum())
|
| 45 |
+
return f"{total:.2f}"
|
| 46 |
|
| 47 |
+
@tool
|
| 48 |
+
def transcribe_audio(
|
| 49 |
+
file_path: str,
|
| 50 |
+
model_size: str = "base"
|
| 51 |
+
) -> str:
|
| 52 |
+
"""
|
| 53 |
+
Transcribe an audio file to text using OpenAI Whisper.
|
| 54 |
|
| 55 |
+
Args:
|
| 56 |
+
file_path: Path to the audio file (.mp3, .wav, etc.).
|
| 57 |
+
model_size: Whisper model size ("tiny", "base", "small", "medium", or "large"). Defaults to "base".
|
| 58 |
|
| 59 |
+
Returns:
|
| 60 |
+
The full transcript as plain text.
|
| 61 |
+
"""
|
| 62 |
+
model = whisper.load_model(model_size)
|
| 63 |
+
result = model.transcribe(file_path)
|
| 64 |
+
return result["text"]
|
| 65 |
|
| 66 |
@tool
|
| 67 |
+
def fetch_youtube_transcript(
|
| 68 |
+
video_url: str
|
| 69 |
+
) -> str:
|
| 70 |
"""
|
| 71 |
+
Fetch a YouTube video's captions via the YouTube Transcript API.
|
| 72 |
|
| 73 |
Args:
|
| 74 |
+
video_url: Full YouTube URL or just the video ID.
|
|
|
|
| 75 |
|
| 76 |
Returns:
|
| 77 |
+
A time-stamped transcript, one line per caption block.
|
| 78 |
"""
|
| 79 |
+
# extract ID
|
| 80 |
+
if "v=" in video_url:
|
| 81 |
+
video_id = video_url.split("v=")[-1].split("&")[0]
|
| 82 |
+
else:
|
| 83 |
+
video_id = video_url
|
| 84 |
+
entries = YouTubeTranscriptApi.get_transcript(video_id)
|
| 85 |
+
lines = [f"{item['start']:.2f}s: {item['text']}" for item in entries]
|
| 86 |
+
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
@tool
|
| 89 |
+
def ocr_chess_fen(
|
| 90 |
+
image_path: str
|
| 91 |
+
) -> str:
|
| 92 |
+
"""
|
| 93 |
+
OCR a chessboard image and extract a FEN string.
|
| 94 |
|
| 95 |
+
Args:
|
| 96 |
+
image_path: Path to the image of a chessboard position.
|
|
|
|
| 97 |
|
| 98 |
+
Returns:
|
| 99 |
+
A FEN string representing the position detected via OCR.
|
| 100 |
+
"""
|
| 101 |
+
img = Image.open(image_path)
|
| 102 |
+
text = pytesseract.image_to_string(img)
|
| 103 |
+
# crude scan for FEN-like substring
|
| 104 |
+
for token in text.split():
|
| 105 |
+
if token.count("/") == 7:
|
| 106 |
+
return token
|
| 107 |
+
raise ValueError("No FEN string detected in OCR output")
|
| 108 |
|
| 109 |
@tool
|
| 110 |
+
def best_chess_move(
|
| 111 |
+
fen: str,
|
| 112 |
+
engine_path: str = "stockfish"
|
| 113 |
+
) -> str:
|
| 114 |
"""
|
| 115 |
+
Compute the best move in a given position using Stockfish.
|
| 116 |
|
| 117 |
Args:
|
| 118 |
+
fen: A FEN string for the position.
|
| 119 |
+
engine_path: Path to the Stockfish binary. Defaults to "stockfish".
|
| 120 |
|
| 121 |
Returns:
|
| 122 |
+
The best move in algebraic notation, according to Stockfish.
|
| 123 |
"""
|
| 124 |
+
board = chess.Board(fen)
|
| 125 |
+
with chess.engine.SimpleEngine.popen_uci(engine_path) as engine:
|
| 126 |
+
result = engine.play(board, limit=chess.engine.Limit(time=0.5))
|
| 127 |
+
return board.san(result.move)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
@tool
|
| 130 |
+
def search_pdf(
|
| 131 |
+
file_path: str,
|
| 132 |
+
query: str
|
| 133 |
+
) -> str:
|
| 134 |
"""
|
| 135 |
+
Full-text search inside a PDF and return the first matching snippet.
|
| 136 |
|
| 137 |
Args:
|
| 138 |
+
file_path: Path to the PDF file.
|
| 139 |
+
query: The text string to search for.
|
| 140 |
|
| 141 |
Returns:
|
| 142 |
+
A snippet of text where the query appears, or "No match found."
|
| 143 |
"""
|
| 144 |
+
doc = fitz.open(file_path)
|
| 145 |
+
full = ""
|
| 146 |
+
for page in doc:
|
| 147 |
+
full += page.get_text()
|
| 148 |
+
splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 149 |
+
chunks = splitter.split_text(full)
|
| 150 |
+
for c in chunks:
|
| 151 |
+
if query.lower() in c.lower():
|
| 152 |
+
return c.strip()
|
| 153 |
+
return "No match found."
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
@tool
|
| 156 |
+
def decode_reversed_text(
|
| 157 |
+
text: str
|
| 158 |
+
) -> str:
|
| 159 |
"""
|
| 160 |
+
Detect and decode text that’s been reversed backwards.
|
| 161 |
|
| 162 |
Args:
|
| 163 |
+
text: Input text which may be backwards.
|
|
|
|
| 164 |
|
| 165 |
Returns:
|
| 166 |
+
The decoded text if reversed, otherwise returns original.
|
| 167 |
"""
|
| 168 |
+
rev = text[::-1]
|
| 169 |
+
# simple heuristic: more vowels in reversed?
|
| 170 |
+
if sum(c.lower() in "aeiou" for c in rev) > sum(c.lower() in "aeiou" for c in text):
|
| 171 |
+
return rev
|
| 172 |
+
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
|