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c1f
8eabc3b
 
 
 
 
 
 
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""Tools for the GAIA evaluation agent."""

from __future__ import annotations

import os
import re
from pathlib import Path

import requests
from markdownify import markdownify
from requests.exceptions import RequestException
from smolagents import DuckDuckGoSearchTool, tool
from youtube_transcript_api import YouTubeTranscriptApi

BROWSER_USER_AGENT = (
    "Mozilla/5.0 (compatible; GAIAAgent/1.0; "
    "+https://huggingface.co/spaces/ken2ki/Final_Assignment_Template)"
)
WIKIPEDIA_HEADERS = {
    "User-Agent": os.getenv("WIKIPEDIA_USER_AGENT", BROWSER_USER_AGENT),
}
FETCH_HEADERS = {"User-Agent": BROWSER_USER_AGENT}


def build_search_tool() -> DuckDuckGoSearchTool:
    return DuckDuckGoSearchTool()


def _should_return_raw_response(url: str, content_type: str) -> bool:
    lowered = url.lower()
    if "format=json" in lowered or "/api.php" in lowered:
        return True
    if lowered.endswith(".json"):
        return True
    return "application/json" in content_type.lower()


def _fetch_wikipedia_wikitext(page_title: str) -> str:
    response = requests.get(
        "https://en.wikipedia.org/w/api.php",
        params={
            "action": "parse",
            "page": page_title.replace(" ", "_"),
            "prop": "wikitext",
            "format": "json",
        },
        timeout=20,
        headers=WIKIPEDIA_HEADERS,
    )
    response.raise_for_status()
    payload = response.json()
    return payload["parse"]["wikitext"]["*"]


def parse_studio_album_rows(wikitext: str) -> list[tuple[int, str]]:
    """Extract (year, album label) rows from a Wikipedia studio-albums section."""
    match = re.search(
        r"===\s*Studio albums\s*===\n(.*?)(?:\n===[^=]|\Z)",
        wikitext,
        re.DOTALL | re.IGNORECASE,
    )
    if not match:
        return []

    section = match.group(1)
    rows: list[tuple[int, str]] = []
    for year_text, album_cell in re.findall(
        r"^\|\s*(\d{4})\s*\n\|(.+?)(?=\n\|-|\n\|\s*\d{4}\s*\n|\Z)",
        section,
        re.MULTILINE | re.DOTALL,
    ):
        year = int(year_text)
        album = re.sub(r"\[\[([^|\]]+\|)?([^\]]+)\]\]", r"\2", album_cell)
        album = re.sub(r"''+", "", album)
        album = re.sub(r"<[^>]+>", "", album)
        album = " ".join(album.split())
        rows.append((year, album[:200]))
    return rows


@tool
def visit_webpage(url: str) -> str:
    """Fetch a web page and return readable markdown text.

    Args:
        url: Full URL to fetch.
    """
    return fetch_url_as_markdown(url)


@tool
def wikipedia_search(query: str) -> str:
    """Search English Wikipedia and return the opening text of the best matching article.

    Args:
        query: Search terms, ideally a person, place, or topic name.
    """
    try:
        search_url = "https://en.wikipedia.org/w/api.php"
        search_params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json",
            "srlimit": 3,
        }
        search_response = requests.get(
            search_url, params=search_params, timeout=20, headers=WIKIPEDIA_HEADERS
        )
        search_response.raise_for_status()
        results = search_response.json().get("query", {}).get("search", [])
        if not results:
            return f"No Wikipedia articles found for: {query}"

        snippets: list[str] = []
        for result in results[:3]:
            title = result["title"]
            extract_params = {
                "action": "query",
                "prop": "extracts",
                "explaintext": True,
                "exintro": False,
                "titles": title,
                "format": "json",
            }
            extract_response = requests.get(
                search_url, params=extract_params, timeout=20, headers=WIKIPEDIA_HEADERS
            )
            extract_response.raise_for_status()
            pages = extract_response.json().get("query", {}).get("pages", {})
            page = next(iter(pages.values()), {})
            extract = page.get("extract", "")
            snippets.append(f"Title: {title}\n{extract[:4000]}")
        return "\n\n---\n\n".join(snippets)
    except Exception as error:
        return f"Wikipedia search failed: {error}"


@tool
def wikipedia_studio_albums(page_title: str, start_year: int, end_year: int) -> str:
    """Count studio albums listed on English Wikipedia within an inclusive year range.

    Args:
        page_title: Wikipedia article title, e.g. "Mercedes Sosa".
        start_year: First release year to include.
        end_year: Last release year to include.
    """
    if start_year > end_year:
        return f"Invalid year range: {start_year} > {end_year}"

    try:
        wikitext = _fetch_wikipedia_wikitext(page_title)
        rows = parse_studio_album_rows(wikitext)
        if not rows:
            return f'No "Studio albums" section found on Wikipedia page: {page_title}'

        selected = [(year, album) for year, album in rows if start_year <= year <= end_year]
        lines = [f"- {year}: {album}" for year, album in selected]
        header = (
            f'Studio albums on "{page_title}" (English Wikipedia) '
            f"between {start_year} and {end_year} inclusive: {len(selected)}"
        )
        if not lines:
            return header + "\n(none listed in that range)"
        return header + "\n\n" + "\n".join(lines)
    except Exception as error:
        return f"Wikipedia discography lookup failed: {error}"


@tool
def fetch_url_as_markdown(url: str) -> str:
    """Fetch a web page and return readable markdown text.

    Args:
        url: Full URL to fetch.
    """
    try:
        response = requests.get(url, timeout=30, headers=FETCH_HEADERS)
        response.raise_for_status()
        content_type = response.headers.get("Content-Type", "")
        if _should_return_raw_response(url, content_type):
            return response.text[:12000]
        markdown_content = markdownify(response.text).strip()
        markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
        return markdown_content[:12000]
    except RequestException as error:
        return f"Error fetching URL: {error}"


@tool
def read_text_file(file_path: str) -> str:
    """Read a local text, Python, CSV, or JSON file and return its contents.

    Args:
        file_path: Absolute or relative path to the file.
    """
    path = Path(file_path)
    if not path.exists():
        return f"File not found: {file_path}"
    try:
        return path.read_text(encoding="utf-8", errors="replace")[:12000]
    except Exception as error:
        return f"Could not read file: {error}"


@tool
def read_excel_summary(file_path: str) -> str:
    """Read an Excel workbook and return all sheets as markdown tables.

    Args:
        file_path: Path to an .xlsx or .xls file.
    """
    try:
        import pandas as pd

        workbook = pd.read_excel(file_path, sheet_name=None)
        parts: list[str] = []
        for sheet_name, frame in workbook.items():
            parts.append(f"Sheet: {sheet_name}\n{frame.to_markdown(index=False)}")
        return "\n\n".join(parts)[:12000]
    except Exception as error:
        return f"Could not read Excel file: {error}"


@tool
def transcribe_audio(file_path: str) -> str:
    """Transcribe a local audio file such as mp3 or wav.

    Args:
        file_path: Path to the audio file.
    """
    path = Path(file_path)
    if not path.exists():
        return f"Audio file not found: {file_path}"

    try:
        from faster_whisper import WhisperModel

        model_size = os.getenv("WHISPER_MODEL", "base")
        whisper = WhisperModel(model_size, device="cpu", compute_type="int8")
        segments, _info = whisper.transcribe(str(path))
        text = " ".join(segment.text.strip() for segment in segments)
        if text:
            return text[:12000]
    except Exception as local_error:
        hf_error = None
        token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
        if token:
            try:
                from huggingface_hub import InferenceClient

                client = InferenceClient(token=token)
                with path.open("rb") as audio_file:
                    transcript = client.automatic_speech_recognition(
                        audio_file.read(),
                        model="openai/whisper-large-v3",
                    )
                if isinstance(transcript, dict):
                    return transcript.get("text", str(transcript))
                return str(transcript)
            except Exception as error:
                hf_error = error
        if hf_error:
            return (
                f"Local transcription failed: {local_error}. "
                f"HF fallback failed: {hf_error}"
            )
        return (
            f"Local transcription failed: {local_error}. "
            "Install faster-whisper or set HF_TOKEN for cloud fallback."
        )

    return "Audio transcription returned no text."


@tool
def describe_image(file_path: str, question: str = "Describe this image in detail.") -> str:
    """Analyze a local image file and answer a question about it.

    Args:
        file_path: Path to a png, jpg, jpeg, or webp image.
        question: What you want to know about the image.
    """
    path = Path(file_path)
    if not path.exists():
        return f"Image file not found: {file_path}"

    import base64

    image_b64 = base64.b64encode(path.read_bytes()).decode("ascii")
    vision_model = os.getenv("OLLAMA_VISION_MODEL", "").strip()
    if vision_model:
        try:
            api_base = os.getenv("OLLAMA_API_BASE", "http://127.0.0.1:11434")
            response = requests.post(
                f"{api_base.rstrip('/')}/api/chat",
                json={
                    "model": vision_model,
                    "messages": [
                        {
                            "role": "user",
                            "content": question,
                            "images": [image_b64],
                        }
                    ],
                    "stream": False,
                },
                timeout=180,
            )
            response.raise_for_status()
            return response.json()["message"]["content"]
        except Exception as error:
            return f"Ollama vision analysis failed: {error}"

    token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
    if not token:
        return (
            "No local vision model configured. Set OLLAMA_VISION_MODEL in .env "
            "(for example after running `ollama pull llava:7b`) or set HF_TOKEN."
        )

    try:
        from huggingface_hub import InferenceClient

        mime_type = {
            ".png": "image/png",
            ".jpg": "image/jpeg",
            ".jpeg": "image/jpeg",
            ".webp": "image/webp",
        }.get(path.suffix.lower(), "image/png")
        data_url = f"data:{mime_type};base64,{image_b64}"

        client = InferenceClient(token=token)
        vision_model = os.getenv("HF_VISION_MODEL", "Qwen/Qwen2.5-VL-72B-Instruct")
        response = client.chat.completions.create(
            model=vision_model,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": question},
                        {"type": "image_url", "image_url": {"url": data_url}},
                    ],
                }
            ],
            max_tokens=500,
        )
        return response.choices[0].message.content
    except Exception as error:
        return f"Image analysis failed: {error}"


@tool
def get_youtube_transcript(video_url: str) -> str:
    """Fetch the transcript/captions for a YouTube video URL.

    If captions are unavailable, returns the video title plus web search results
    about the video so you can still infer the answer.

    Args:
        video_url: A YouTube watch URL or youtu.be link.
    """
    match = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", video_url)
    if not match:
        return "Could not extract a YouTube video id from the URL."

    video_id = match.group(1)
    try:
        api = YouTubeTranscriptApi()
        transcript = api.fetch(video_id, languages=["en", "en-US", "en-GB"])
        text = " ".join(snippet.text for snippet in transcript)
        return text[:12000]
    except Exception as transcript_error:
        try:
            oembed = requests.get(
                "https://www.youtube.com/oembed",
                params={"url": video_url, "format": "json"},
                timeout=20,
            )
            oembed.raise_for_status()
            title = oembed.json().get("title", video_id)
        except Exception:
            title = video_id

        try:
            from ddgs import DDGS

            with DDGS() as ddgs:
                results = list(
                    ddgs.text(
                        f'"{title}" bird species video transcript summary',
                        max_results=5,
                    )
                )
            snippets = []
            for item in results:
                body = item.get("body") or item.get("title") or str(item)
                snippets.append(body)
            search_text = "\n\n".join(snippets)
        except Exception as search_error:
            search_text = f"Web search fallback failed: {search_error}"

        return (
            f"YouTube transcript unavailable ({transcript_error}).\n"
            f"Video title: {title}\n"
            f"Use the following web search results about the video instead:\n\n"
            f"{search_text[:10000]}"
        )


def build_tools() -> list:
    return [
        build_search_tool(),
        visit_webpage,
        wikipedia_search,
        wikipedia_studio_albums,
        fetch_url_as_markdown,
        read_text_file,
        read_excel_summary,
        transcribe_audio,
        describe_image,
        get_youtube_transcript,
    ]