Asapyams commited on
Commit
bd124fe
·
verified ·
1 Parent(s): e0eab54

Update agents/tools.py

Browse files
Files changed (1) hide show
  1. agents/tools.py +121 -94
agents/tools.py CHANGED
@@ -1,147 +1,174 @@
1
  import os
2
- import uuid
3
  import tempfile
4
- from urllib.parse import urlparse
5
  from typing import Optional
6
 
7
- import requests
8
- from smolagents import tool
9
-
 
 
 
 
 
 
 
10
 
11
  @tool
12
- def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
 
 
 
 
 
 
13
  """
14
- Save content to a temporary file and return the path.
15
 
16
  Args:
17
- content (str): The text content to write into the file.
18
- filename (Optional[str]): Optional filename. If None, a random temp filename is generated.
 
 
 
19
 
20
  Returns:
21
- str: Message indicating where the file was saved.
22
  """
23
- temp_dir = tempfile.gettempdir()
24
- if filename is None:
25
- temp_file = tempfile.NamedTemporaryFile(delete=False)
26
- filepath = temp_file.name
27
  else:
28
- filepath = os.path.join(temp_dir, filename)
 
 
 
29
 
30
- with open(filepath, 'w') as f:
31
- f.write(content)
 
 
 
 
 
32
 
33
- return f"File saved to {filepath}. You can read this file to process its contents."
 
 
34
 
 
 
 
 
 
 
35
 
36
  @tool
37
- def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
 
 
38
  """
39
- Download a file from a URL and save it to a temporary location.
40
 
41
  Args:
42
- url (str): The URL to download the file from.
43
- filename (Optional[str]): Optional filename. If None, it's derived from the URL or randomized.
44
 
45
  Returns:
46
- str: Message indicating where the file was downloaded, or an error message.
47
  """
48
- try:
49
- # Derive or generate filename
50
- if not filename:
51
- path = urlparse(url).path
52
- basename = os.path.basename(path)
53
- filename = basename or f"downloaded_{uuid.uuid4().hex[:8]}"
54
-
55
- temp_dir = tempfile.gettempdir()
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
- with open(filepath, 'wb') as f:
63
- for chunk in response.iter_content(chunk_size=8192):
64
- if chunk:
65
- f.write(chunk)
 
 
66
 
67
- return f"File downloaded to {filepath}. You can now process this file."
68
- except Exception as e:
69
- return f"Error downloading file: {str(e)}"
70
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  @tool
73
- def extract_text_from_image(image_path: str) -> str:
 
 
 
74
  """
75
- Extract text from an image using pytesseract.
76
 
77
  Args:
78
- image_path (str): Path to the image file to process.
 
79
 
80
  Returns:
81
- str: Extracted text, or an error message if extraction fails.
82
  """
83
- try:
84
- import pytesseract
85
- from PIL import Image
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 analyze_csv_file(file_path: str, query: str) -> str:
 
 
 
98
  """
99
- Analyze a CSV file using pandas and answer a question about it.
100
 
101
  Args:
102
- file_path (str): Path to the CSV file to analyze.
103
- query (str): The question or analysis request for the CSV data.
104
 
105
  Returns:
106
- str: Analysis results or an error message.
107
  """
108
- try:
109
- import pandas as pd
110
-
111
- df = pd.read_csv(file_path)
112
- result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
113
- result += f"Columns: {', '.join(df.columns)}\n\n"
114
- result += "Summary statistics:\n" + df.describe().to_string()
115
- return result
116
- except ImportError:
117
- return "Error: pandas not installed. Please install pandas with 'pip install pandas'."
118
- except Exception as e:
119
- return f"Error analyzing CSV file: {str(e)}"
120
-
121
 
122
  @tool
123
- def analyze_excel_file(file_path: str, query: str) -> str:
 
 
124
  """
125
- Analyze an Excel file using pandas and answer a question about it.
126
 
127
  Args:
128
- file_path (str): Path to the Excel file to analyze.
129
- query (str): The question or analysis request for the Excel data.
130
 
131
  Returns:
132
- str: Analysis results or an error message.
133
  """
134
- try:
135
- import pandas as pd
136
-
137
- df = pd.read_excel(file_path)
138
- result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
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