AI_Forum / tools /web_tools.py
Haster1137's picture
Upload 7519 files
57d7008 verified
Raw History Blame Contribute Delete
5.66 kB
"""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(("<!doctype", "<html")):
p = _Text()
p.feed(txt)
txt = re.sub(r"[ \t]+", " ", "".join(p.out))
txt = re.sub(r"\n\s*\n+", "\n\n", txt).strip()
return txt[:max_chars]
def _token():
t = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
if not t:
f = os.path.join(HERE, "hf_token.txt")
if os.path.isfile(f):
t = open(f).read().strip()
if not t:
raise RuntimeError("No Hugging Face token: set HF_TOKEN or put it in tools\\hf_token.txt")
return t
def hf_note(repo, path, text, repo_type="model", append=False, message="agent note"):
"""Create/overwrite (or append to) a text file in an HF repo via the commit API."""
tok = _token()
base = "https://huggingface.co"
seg = {"model": "models", "dataset": "datasets", "space": "spaces"}[repo_type]
if append:
rp = "" if repo_type == "model" else seg + "/"
try:
_, old = _get("%s/%s%s/resolve/main/%s" % (base, rp, repo, urllib.parse.quote(path)),
headers={"Authorization": "Bearer " + tok})
text = old.decode("utf-8", "replace").rstrip("\n") + "\n" + text
except urllib.error.HTTPError as e:
if e.code != 404:
raise
lines = [json.dumps({"key": "header", "value": {"summary": message}}),
json.dumps({"key": "file", "value": {"content": base64.b64encode(text.encode()).decode(),
"path": path, "encoding": "base64"}})]
_, b = _get("%s/api/%s/%s/commit/main" % (base, seg, repo),
headers={"Authorization": "Bearer " + tok, "Content-Type": "application/x-ndjson"},
data="\n".join(lines).encode(), method="POST")
return json.loads(b)
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("search"); s.add_argument("query"); s.add_argument("-n", type=int, default=8)
f = sub.add_parser("fetch"); f.add_argument("url"); f.add_argument("--max", type=int, default=20000)
n = sub.add_parser("hf-note"); n.add_argument("repo"); n.add_argument("path"); n.add_argument("text")
n.add_argument("--type", default="model", choices=["model", "dataset", "space"])
n.add_argument("--append", action="store_true")
a = ap.parse_args()
if a.cmd == "search":
print(json.dumps(search(a.query, a.n), indent=1, ensure_ascii=False))
elif a.cmd == "fetch":
print(fetch(a.url, a.max))
else:
print(json.dumps(hf_note(a.repo, a.path, a.text, a.type, a.append)))
if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8")
main()