"""Internet access for the local model (stdlib only). CLI: python web_tools.py search "query" [-n 8] python web_tools.py fetch URL [--max 20000] python web_tools.py hf-note REPO PATH_IN_REPO "text" [--type model|dataset|space] [--append] Import: from web_tools import search, fetch, hf_note search -> needs SearXNG running (searxng\\start_searxng.bat) on 127.0.0.1:8888 fetch -> direct HTTP GET, returns readable text hf_note -> writes/appends a note file in a Hugging Face repo; token from env HF_TOKEN (or HUGGINGFACE_HUB_TOKEN, or file tools\\hf_token.txt) """ import argparse, base64, gzip, json, os, re, sys, urllib.error, urllib.parse, urllib.request from html.parser import HTMLParser HERE = os.path.dirname(os.path.abspath(__file__)) SEARX = os.environ.get("SEARXNG_URL", "http://127.0.0.1:8888") UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) LocalAgent/1.0" def _get(url, headers=None, timeout=30, data=None, method=None): h = {"User-Agent": UA, "Accept-Encoding": "gzip"} h.update(headers or {}) req = urllib.request.Request(url, data=data, headers=h, method=method) with urllib.request.urlopen(req, timeout=timeout) as r: body = r.read() if r.headers.get("Content-Encoding") == "gzip": body = gzip.decompress(body) return r.headers, body def search(query, n=8, engines=None): """Return [{title,url,content,engines}] from the local SearXNG.""" p = {"q": query, "format": "json"} if engines: p["engines"] = engines try: _, b = _get(SEARX + "/search?" + urllib.parse.urlencode(p), timeout=40) except Exception as e: raise RuntimeError("SearXNG not reachable at %s (start searxng\\start_searxng.bat): %s" % (SEARX, e)) res = json.loads(b).get("results", [])[:n] return [{"title": r.get("title"), "url": r.get("url"), "content": (r.get("content") or "")[:300], "engines": r.get("engines")} for r in res] class _Text(HTMLParser): SKIP = {"script", "style", "noscript", "svg", "head", "nav", "footer", "form"} def __init__(self): super().__init__(convert_charrefs=True) self.out, self.skip = [], 0 def handle_starttag(self, t, a): if t in self.SKIP: self.skip += 1 elif t in ("p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4", "pre", "section", "article"): self.out.append("\n") def handle_endtag(self, t): if t in self.SKIP and self.skip: self.skip -= 1 def handle_data(self, d): if not self.skip: self.out.append(d) def fetch(url, max_chars=20000): """GET a URL; HTML is reduced to text, JSON/text returned as is.""" h, b = _get(url, timeout=30) ct = h.get("Content-Type", "") m = re.search(r"charset=([\w-]+)", ct) txt = b.decode(m.group(1) if m else "utf-8", "replace") if "html" in ct.lower() or txt.lstrip()[:15].lower().startswith(("