File size: 12,935 Bytes
d03c5e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# tools.py

import os
import tempfile
import requests
import pandas as pd
from pathlib import Path
from typing import Optional
import openai
from bs4 import BeautifulSoup
from smolagents import tool
from smolagents.tools import Tool, PipelineTool
import tempfile, os, cv2, pytesseract
from pytube import YouTube


# ─────────────────────────────────────────────────────────────
# 🧾 EXCEL β†’ MARKDOWN TABLE TOOL (Class-based)
# ─────────────────────────────────────────────────────────────

class ExcelToTextTool(Tool):
    name = "excel_to_markdown"
    description = "Convert an Excel worksheet to a Markdown table."

    inputs = {
        "excel_path": {"type": "string", "description": "Path to the Excel file"},
        "sheet_name": {"type": "string", "description": "Sheet name or index (optional)", "nullable": True},
    }
    output_type = "string"

    def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
        path = Path(excel_path).expanduser().resolve()
        if not path.exists():
            return f"❌ File not found: {path}"
        try:
            sheet = int(sheet_name) if sheet_name and sheet_name.isdigit() else sheet_name or 0
            df = pd.read_excel(path, sheet_name=sheet)
            if hasattr(df, "to_markdown"):
                return df.to_markdown(index=False)
            return df.to_string(index=False)
        except Exception as e:
            return f"❌ Excel read error: {e}"


# ─────────────────────────────────────────────────────────────
# πŸ”Š AUDIO β†’ TEXT TOOL (Whisper via OpenAI)
# ─────────────────────────────────────────────────────────────

class SpeechToTextTool(PipelineTool):
    default_checkpoint = "openai/whisper-1"

    name = "whisper_transcribe"
    description = "Transcribe local audio file to text using OpenAI Whisper."

    inputs = {
        "audio": {"type": "string", "description": "Path to an audio file"},
    }
    output_type = "string"

    def __init__(self):
        # now you can just call super with no args
        super().__init__()

    def __call__(self, audio: str) -> str:
        return self._transcribe(audio)
    @staticmethod
    def _transcribe(audio_path: str) -> str:
        path = Path(audio_path).expanduser().resolve()
        if not path.is_file():
            return f"❌ Audio file not found: {audio_path}"
        try:
            with path.open("rb") as fp:
                transcript = openai.audio.transcriptions.create(
                    file=fp,
                    model="whisper-1",
                    response_format="text"
                )
            return transcript
        except Exception as e:
            return f"❌ Whisper error: {e}"


# ─────────────────────────────────────────────────────────────
# πŸ“ DOWNLOAD FILE TOOL (Decorator)
# ─────────────────────────────────────────────────────────────

@tool
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
    """

    Download a file from a URL and save it locally.



    Args:

        url: URL to fetch.

        filename: Optional desired filename; if omitted, extracted from URL.



    Returns:

        Local file path or error message.

    """
    try:
        from urllib.parse import urlparse

        if not filename:
            parsed = urlparse(url).path
            filename = os.path.basename(parsed) or f"file_{os.urandom(4).hex()}"

        dest = os.path.join(tempfile.gettempdir(), filename)
        r = requests.get(url, stream=True, timeout=15)
        r.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in r.iter_content(8192):
                f.write(chunk)
        return dest
    except Exception as e:
        return f"❌ Download error: {e}"


@tool
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
    """

    Save content to a temporary file and return the path.

    Useful for processing files from the GAIA API.

    

    Args:

        content: The content to save to the file

        filename: Optional filename, will generate a random name if not provided

        

    Returns:

        Path to the saved file

    """
    temp_dir = tempfile.gettempdir()
    if filename is None:
        temp_file = tempfile.NamedTemporaryFile(delete=False)
        filepath = temp_file.name
    else:
        filepath = os.path.join(temp_dir, filename)
    
    # Write content to the file
    with open(filepath, 'w') as f:
        f.write(content)
    
    return f"File saved to {filepath}. You can read this file to process its contents."
# ─────────────────────────────────────────────────────────────
# πŸ“Š CSV ANALYZER TOOL (Decorator)
# ─────────────────────────────────────────────────────────────

@tool
def analyze_csv_file(file_path: str, query: str) -> str:
    """

    Load a CSV and return row/column counts, column names, and summary stats.



    Args:

        file_path: Path to CSV.

        query: Question context (unused, for agent reference).



    Returns:

        Text summary of the CSV.

    """
    try:
        df = pd.read_csv(file_path)
        summary = [
            f"Rows: {len(df)}, Columns: {len(df.columns)}",
            "Columns: " + ", ".join(df.columns),
            "Stats:\n" + df.describe(include="all").to_string()
        ]
        return "\n".join(summary)
    except Exception as e:
        return f"❌ CSV analyze error: {e}"


# ─────────────────────────────────────────────────────────────
# πŸ“ˆ EXCEL ANALYZER TOOL (Decorator)
# ─────────────────────────────────────────────────────────────

@tool
def analyze_excel_file(file_path: str, query: str) -> str:
    """

    Load an Excel file and return row/column counts, column names, and summary stats.



    Args:

        file_path: Path to Excel.

        query: Question context (unused).



    Returns:

        Text summary of the sheet.

    """
    try:
        df = pd.read_excel(file_path)
        summary = [
            f"Rows: {len(df)}, Columns: {len(df.columns)}",
            "Columns: " + ", ".join(df.columns),
            "Stats:\n" + df.describe(include="all").to_string()
        ]
        return "\n".join(summary)
    except Exception as e:
        return f"❌ Excel analyze error: {e}"


# ─────────────────────────────────────────────────────────────
# πŸ“š WIKIPEDIA FULL PAGE FETCH TOOL (Decorator)
# ─────────────────────────────────────────────────────────────

@tool
def wikipedia_page_fetch(title: str) -> str:
    """

    Fetch the full HTML content of an English Wikipedia page.



    Args:

        title: Article title (spaces OK).



    Returns:

        Raw HTML or error message.

    """
    try:
        slug = title.replace(" ", "_")
        url = f"https://en.wikipedia.org/api/rest_v1/page/html/{slug}"
        resp = requests.get(url, timeout=15)
        resp.raise_for_status()
        return resp.text
    except Exception as e:
        return f"❌ Wiki fetch error: {e}"

@tool
def reverse_text(s: str) -> str:
    """

    Reverse a string and return it for further reasoning.



    Args:

        s: The text to reverse (e.g. a backward-written sentence).



    Returns:

        The reversed string, so it reads forward.

    """
    return s[::-1]

@tool
def extract_wiki_list(html: str, section_id: str) -> list[str]:
    """

    Given Wikipedia HTML and a section anchor (e.g. 'Studio_albums'),

    return the list items under that heading.

    

    Args:

        html: Full page HTML from wikipedia_page_fetch(...)

        section_id: The <span id="…"> anchor to look for.

    Returns:

        A Python list of the <li> texts in that section.

    """
    soup = BeautifulSoup(html, "html.parser")
    header = soup.find("span", {"id": section_id})
    if not header:
        return []
    ul = header.find_next_sibling("ul")
    return [li.get_text(strip=True) for li in ul.find_all("li")]



@tool
def highest_ocr_number_in_video(video_path: str) -> int:
    """

    Extract all integer tokens from every frame of a video and return the highest one found.



    Args:

        video_path: Path to the local video file.



    Returns:

        The largest integer recognized via OCR in the video, or 0 if no digits are found.

    """
    cap = cv2.VideoCapture(video_path)
    max_num = 0
    while True:
        ret, frame = cap.read()
        if not ret: break
        text = pytesseract.image_to_string(frame, config="--psm 6 digits")
        for token in text.split():
            if token.isdigit():
                max_num = max(max_num, int(token))
    cap.release()
    return max_num

    
@tool
def extract_text_from_image(image_path: str) -> str:
    """

    Extract text from an image using pytesseract (if available).

    

    Args:

        image_path: Path to the image file

        

    Returns:

        Extracted text or error message

    """
    try:
        # Try to import pytesseract
        import pytesseract
        from PIL import Image
        
        # Open the image
        image = Image.open(image_path)
        
        # Extract text
        text = pytesseract.image_to_string(image)
        
        return f"Extracted text from image:\n\n{text}"
    except ImportError:
        return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
    except Exception as e:
        return f"Error extracting text from image: {str(e)}"
    
@tool
def download_youtube_audio(url: str) -> str:
    """

    Download the audio from a YouTube video and save it locally as an MP4 file.



    Args:

        url: YouTube video URL.



    Returns:

        Path to the downloaded audio file.

    """
    try:
        from pytube import YouTube
        
        yt = YouTube(url)
        audio_stream = yt.streams.filter(only_audio=True).first()
        if not audio_stream:
            return "❌ No audio stream found."
        
        temp_dir = tempfile.gettempdir()
        safe_title = yt.title.replace(" ", "_").replace("/", "_")[:50]  # Avoid long names
        audio_path = os.path.join(temp_dir, f"{safe_title}.mp4")
        
        audio_stream.download(filename=audio_path)
        return audio_path
    except Exception as e:
        return f"❌ Error downloading YouTube audio: {e}"

@tool
def extract_audio_from_video(video_path: str) -> str:
    """

    Extract audio from a video file and save it as a WAV file.



    Args:

        video_path: Path to the input video file.



    Returns:

        Path to the extracted WAV audio file.

    """
    try:
        from moviepy import VideoFileClip

        clip = VideoFileClip(video_path)
        audio_path = video_path.rsplit(".", 1)[0] + ".wav"
        clip.audio.write_audiofile(audio_path, codec='pcm_s16le')
        return audio_path
    except Exception as e:
        return f"❌ Error extracting audio: {e}"
    
@tool
def final_answer(input_text: str) -> str:
    """

    Return the final answer to conclude the task.



    Args:

        input_text: The final answer text to submit.



    Returns:

        The final answer as a plain string.

    """
    return input_text