STARX33 commited on
Commit
e07cd39
·
verified ·
1 Parent(s): 6892a22

Update tools/simple_text_browser.py

Browse files
Files changed (1) hide show
  1. tools/simple_text_browser.py +75 -0
tools/simple_text_browser.py CHANGED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from duckduckgo_search import DDGS
5
+
6
+ class SimpleTextBrowser:
7
+ def __init__(
8
+ self,
9
+ timeout: int = 10,
10
+ user_agent: str | None = None,
11
+ viewport_size: int = 5000,
12
+ downloads_folder: str = "downloads",
13
+ ):
14
+ self.session = requests.Session()
15
+ self.session.headers.update({"User-Agent": user_agent or "Mozilla/5.0"})
16
+ self.timeout = timeout
17
+ self.viewport_size = viewport_size
18
+ os.makedirs(downloads_folder, exist_ok=True)
19
+ self.pages: list[str] = [""]
20
+ self._idx = 0
21
+
22
+ def _split(self, text: str):
23
+ self.pages = [
24
+ text[i : i + self.viewport_size]
25
+ for i in range(0, len(text), self.viewport_size)
26
+ ]
27
+ self._idx = 0
28
+
29
+ def visit_page(self, url: str) -> str:
30
+ """
31
+ Internal: fetch and split a page into viewports.
32
+ """
33
+ resp = self.session.get(url, timeout=self.timeout)
34
+ resp.raise_for_status()
35
+ text = resp.text
36
+ if "text/html" in resp.headers.get("content-type", ""):
37
+ text = BeautifulSoup(text, "lxml").get_text("\n")
38
+ self._split(text)
39
+ return self.pages[self._idx]
40
+
41
+ def search(self, query: str) -> str:
42
+ """
43
+ Internal: DuckDuckGo search → snippets.
44
+ """
45
+ results = list(DDGS().text(query, timelimit=None))
46
+ hits = "\n".join(
47
+ f"{i+1}. {h['title']} — {h.get('snippet','')}"
48
+ for i, h in enumerate(results)
49
+ )
50
+ full = f"Search results for '{query}':\n\n" + hits
51
+ self._split(full)
52
+ return self.pages[self._idx]
53
+
54
+ def page_down(self) -> str:
55
+ self._idx = min(self._idx + 1, len(self.pages) - 1)
56
+ return self.pages[self._idx]
57
+
58
+ def page_up(self) -> str:
59
+ self._idx = max(self._idx - 1, 0)
60
+ return self.pages[self._idx]
61
+
62
+ def find_on_page(self, search_string: str) -> str:
63
+ full = "\n".join(self.pages).lower()
64
+ pos = full.find(search_string.lower())
65
+ if pos < 0:
66
+ return f"'{search_string}' not found."
67
+ start = max(0, pos - 100)
68
+ end = min(len(full), pos + 100)
69
+ return full[start:end]
70
+
71
+ def find_next(self) -> str:
72
+ return "Use `find_on_page_ctrl_f` again with a new string to find further occurrences."
73
+
74
+ # one shared browser instance:
75
+ _BROWSER = SimpleTextBrowser()