File size: 6,488 Bytes
aed39aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a21cec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aed39aa
 
 
 
a21cec1
aed39aa
 
a21cec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aed39aa
a21cec1
 
 
 
 
 
 
 
 
aed39aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import re
import requests
import wikipedia
from bs4 import BeautifulSoup
from ddgs import DDGS
from langchain_core.tools import tool
from pypdf import PdfReader
from youtube_transcript_api import YouTubeTranscriptApi


@tool
def web_search(query: str) -> str:
    """Search the web using DuckDuckGo and return top results."""
    try:
        with DDGS() as ddgs:
            results = list(ddgs.text(query, max_results=5))
        if not results:
            return "No results found."
        formatted = []
        for r in results:
            formatted.append(
                f"Title: {r.get('title')}\nURL: {r.get('href')}\nSnippet: {r.get('body')}\n"
            )
        return "\n---\n".join(formatted)[:5500]
    except Exception as e:
        return f"Web search error: {e}"


_PAGE_CACHE: dict[str, str] = {}


def _fetch_raw_text(url: str) -> str:
    """Fetch full text from a URL (PDF, HTML, or Jina Reader fallback)."""
    if url in _PAGE_CACHE:
        return _PAGE_CACHE[url]

    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/124.0.0.0 Safari/537.36"
        )
    }

    text = ""
    try:
        response = requests.get(url, headers=headers, timeout=20)
        response.raise_for_status()

        # 1. Raw PDF bytes
        if response.content[:4] == b"%PDF":
            reader = PdfReader(io.BytesIO(response.content))
            text = "\n".join(page.extract_text() or "" for page in reader.pages)
        else:
            # 2. Standard HTML
            soup = BeautifulSoup(response.text, "html.parser")
            for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
                tag.decompose()
            text = " ".join(soup.get_text(separator=" ").split())
    except Exception:
        text = ""

    # 3. Fallback to Jina Reader if blocked, empty, or JS-walled
    if len(text) < 400 or "just a moment" in text[:300].lower() or "enable javascript" in text[:300].lower():
        try:
            jina_resp = requests.get(
                f"https://r.jina.ai/{url}",
                headers={"User-Agent": headers["User-Agent"]},
                timeout=25,
            )
            if jina_resp.status_code == 200 and len(jina_resp.text) > len(text):
                text = jina_resp.text
        except Exception:
            pass

    if not text:
        return ""

    _PAGE_CACHE[url] = text
    return text


@tool
def fetch_webpage(url: str, search_term: str = "", offset: int = 0) -> str:
    """Fetch a webpage or PDF URL.

    - Use `search_term` to jump directly to a keyword/section (e.g., 'Discography', '1977', 'NASA').

    - Use `offset` (character index) to read further down a long page.

    """
    try:
        full_text = _fetch_raw_text(url)
        if not full_text:
            return f"Error: Could not extract readable text from {url}."

        total_len = len(full_text)
        chunk_size = 5000

        # Mode A: Keyword search inside the page
        if search_term:
            matches = [
                m.start()
                for m in re.finditer(re.escape(search_term), full_text, re.IGNORECASE)
            ]
            if not matches:
                return (
                    f"[Term '{search_term}' not found in {total_len} chars. "
                    f"Showing start of page instead:]\n\n{full_text[:3500]}"
                )

            snippets = []
            used_ranges = []
            for pos in matches[:3]:
                start = max(0, pos - 700)
                end = min(total_len, pos + 1000)
                if any(start < u_end and end > u_start for u_start, u_end in used_ranges):
                    continue
                used_ranges.append((start, end))
                snippets.append(f"--- Match at char {pos} ---\n{full_text[start:end]}")

            header = f"[Found {len(matches)} match(es) for '{search_term}' in {total_len} chars]"
            return f"{header}\n\n" + "\n\n".join(snippets)[:5500]

        # Mode B: Sequential / offset reading
        offset = max(0, offset)
        chunk = full_text[offset : offset + chunk_size]
        end_pos = min(total_len, offset + chunk_size)
        header = (
            f"[Showing chars {offset}-{end_pos} of {total_len}. "
            f"Pass search_term='...' or offset={end_pos} to read more.]"
        )
        return f"{header}\n\n{chunk}"

    except Exception as e:
        return f"Error fetching webpage: {e}"


@tool
def wikipedia_search(query: str) -> str:
    """Search Wikipedia for matching article titles and a brief summary of the top match."""
    try:
        titles = wikipedia.search(query, results=5)
        if not titles:
            return "No Wikipedia articles found."
        summary = ""
        try:
            summary = wikipedia.summary(titles[0], sentences=5, auto_suggest=False)
        except Exception:
            pass
        return f"Matching titles: {', '.join(titles)}\n\nTop summary ({titles[0]}):\n{summary}"[:5500]
    except Exception as e:
        return f"Wikipedia search error: {e}"


@tool
def get_wikipedia_page(title: str) -> str:
    """Fetch the text content of a specific Wikipedia article by exact title."""
    try:
        page = wikipedia.page(title, auto_suggest=False)
        return f"Title: {page.title}\nURL: {page.url}\n\n{page.content[:5500]}"
    except Exception as e:
        return f"Error fetching Wikipedia page '{title}': {e}"


@tool
def get_youtube_transcript(url: str) -> str:
    """Fetch the spoken transcript/captions of a YouTube video from its URL."""
    match = re.search(r"(?:v=|youtu\.be/|shorts/)([a-zA-Z0-9_-]{11})", url)
    if not match:
        return "Error: Could not extract a valid YouTube video ID from the URL."
    video_id = match.group(1)

    try:
        if hasattr(YouTubeTranscriptApi, "fetch"):
            fetched = YouTubeTranscriptApi().fetch(video_id)
            text = " ".join(snippet.text for snippet in fetched)
        else:
            fetched = YouTubeTranscriptApi.get_transcript(video_id)
            text = " ".join(entry["text"] for entry in fetched)
        return text[:5500]
    except Exception as e:
        return f"Error fetching YouTube transcript: {e}"