sew-slm / sew_tools /backends.py
Flickwire's picture
Upload sew-slm model, tokenizer, ONNX exports and agent tools
3801a9b verified
Raw History Blame Contribute Delete
6.94 kB
"""Simple English Wikipedia lookup backends.
`WikipediaAPI` queries the live site (simple.wikipedia.org), so results include
articles written or changed at any time. `LocalWiki` answers from an extracted
dump (one JSON object per line: {"title": ..., "text": ...}) for offline use.
Both expose the same two methods:
search(query, n=3) -> [{"title", "snippet"}]
read(title, max_chars=900) -> {"title", "text"} or None
"""
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from .textclean import clean_plain, first_sentences
API = "https://simple.wikipedia.org/w/api.php"
# Wikimedia asks API clients to send a descriptive User-Agent with contact details:
# https://meta.wikimedia.org/wiki/User-Agent_policy -- set SEW_TOOLS_USER_AGENT to your own,
# e.g. "my-app/1.0 (https://example.org/my-app; me@example.org)". Generic agents may get HTTP 429.
DEFAULT_UA = "sew-tools/0.1 (https://github.com/Flickwire/sew-slm) python-urllib"
def _truncate(text, max_chars):
if len(text) <= max_chars:
return text
return text[:max_chars].rsplit(" ", 1)[0]
class RateLimited(RuntimeError):
"""Wikimedia asked us to back off for longer than `max_wait` seconds."""
def __init__(self, retry_after):
super().__init__(f"rate limited by Wikimedia; retry after {retry_after}s")
self.retry_after = retry_after
class WikipediaAPI:
"""Live Simple English Wikipedia via the MediaWiki Action API.
Each tool call is a single HTTP request. HTTP 429 responses are retried after the
server's Retry-After delay when that is at most `max_wait` seconds; otherwise
`RateLimited` is raised. Results are cached in memory for `cache_ttl` seconds.
"""
def __init__(self, user_agent=None, timeout=15, api_url=API, max_wait=30.0, cache_ttl=600):
self.ua = user_agent or os.environ.get("SEW_TOOLS_USER_AGENT") or DEFAULT_UA
self.timeout = timeout
self.api_url = api_url
self.max_wait = max_wait
self.cache_ttl = cache_ttl
self._cache = {}
def _get(self, **params):
params.update(format="json", formatversion="2")
url = self.api_url + "?" + urllib.parse.urlencode(sorted(params.items()))
hit = self._cache.get(url)
if hit and time.monotonic() - hit[0] < self.cache_ttl:
return hit[1]
req = urllib.request.Request(url, headers={"User-Agent": self.ua})
waited = 0.0
while True:
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
data = json.loads(r.read().decode())
break
except urllib.error.HTTPError as e:
if e.code != 429:
raise
try:
delay = float(e.headers.get("Retry-After", 5))
except ValueError:
delay = 5.0
if waited + delay > self.max_wait:
raise RateLimited(int(delay)) from None
time.sleep(delay)
waited += delay
if "error" in data:
raise RuntimeError(data["error"].get("info", "API error"))
if len(self._cache) > 512:
self._cache.clear()
self._cache[url] = (time.monotonic(), data)
return data
@staticmethod
def _clean(extract):
return clean_plain(re.sub(r"\n?==+[^=]+==+\n?", "\n", extract or ""))
def _extracts(self, titles):
"""Opening text of the given titles (follows redirects). Returns (dict, redirects, normalized)."""
data = self._get(action="query", prop="extracts", explaintext=1, exintro=1,
redirects=1, titles="|".join(titles))
q = data.get("query", {})
out = {p["title"]: self._clean(p["extract"]) for p in q.get("pages", []) if p.get("extract")}
redirects = {r["from"]: r["to"] for r in q.get("redirects", [])}
normalized = {r["from"]: r["to"] for r in q.get("normalized", [])}
return out, redirects, normalized
def search(self, query, n=3):
data = self._get(action="query", generator="search", gsrsearch=query, gsrlimit=n,
gsrnamespace=0, prop="extracts", exintro=1, explaintext=1, exlimit=n)
pages = sorted(data.get("query", {}).get("pages", []), key=lambda p: p.get("index", 0))
out = []
for p in pages:
text = self._clean(p.get("extract"))
if text:
out.append({"title": p["title"], "snippet": first_sentences(text)})
return out
def read(self, title, max_chars=900):
ex, _, _ = self._extracts([title])
if not ex: # not an exact title: read the best search match instead
data = self._get(action="query", generator="search", gsrsearch=title, gsrlimit=1,
gsrnamespace=0, prop="extracts", exintro=1, explaintext=1, exlimit=1)
ex = {p["title"]: self._clean(p.get("extract"))
for p in data.get("query", {}).get("pages", []) if p.get("extract")}
if not ex:
return None
t, text = next(iter(ex.items()))
return {"title": t, "text": _truncate(text, max_chars)}
class LocalWiki:
"""Offline index over an extracted dump: exact title lookup + title-word search."""
def __init__(self, articles_path, max_articles=None):
self.text, self.lower, self.index = {}, {}, {}
with open(articles_path) as f:
for i, line in enumerate(f):
if max_articles and i >= max_articles:
break
d = json.loads(line)
self.add(d["title"], d["text"])
def add(self, title, text):
self.text[title] = text
self.lower[title.lower()] = title
for w in set(re.findall(r"\w+", title.lower())):
self.index.setdefault(w, []).append(title)
def search(self, query, n=3):
q = query.strip().lower()
hits = [self.lower[q]] if q in self.lower else []
scores = {}
for w in re.findall(r"\w+", q):
lst = self.index.get(w, [])
if len(lst) > 5000:
continue
for t in lst:
scores[t] = scores.get(t, 0) + 1.0 / (1 + len(lst) ** 0.5)
for t, _ in sorted(scores.items(), key=lambda kv: (-kv[1], len(kv[0]))):
if len(hits) >= n:
break
if t not in hits:
hits.append(t)
return [{"title": t, "snippet": first_sentences(self.text[t])} for t in hits[:n]]
def read(self, title, max_chars=900):
t = self.lower.get(title.strip().lower())
if t is None:
hits = self.search(title, 1)
if not hits:
return None
t = hits[0]["title"]
return {"title": t, "text": _truncate(self.text[t], max_chars)}