"""Ner research API: the full Qwen3 query encoder over the card's own index. The device turns a query into a vector with a small static table; here the real Qwen3-Embedding-0.6B does it (blind test: right answer in the top 3 for 70% of queries against the device's 58%), searching the same 512-dim int8 documents, IVF lists, lexicon, snippets and rel.dat that ship on the card. Everything loads in a background thread at start; /api/status says how far. """ import bisect, html, io, json, os, re, tarfile, threading, time from collections import defaultdict from pathlib import Path import numpy as np import requests from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from huggingface_hub import hf_hub_download REPO, GH = "joshruby/sefaria-embed", "sirch613/Diyo" DATA = Path(os.environ.get("DATA", str(Path.home() / "data"))) DATA.mkdir(parents=True, exist_ok=True) NPROBE = int(os.environ.get("NPROBE", "64")) T_TYPED = ("Given a question or topic, retrieve passages from the Jewish library (Tanakh, Talmud, Midrash, " "halacha, commentaries, responsa, Chasidut) that answer it") NONE = 0xFFFFFFFF SHELVES = ["Tanakh", "Talmud", "Mishnah", "Halakha", "Commentary", "Midrash", "Other", "Lexicon"] app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"]) S = {"stage": "starting", "ready": False, "error": None, "t0": time.time()} X = {} # loaded index def gh_headers(raw=False): h = {"Authorization": f"Bearer {os.environ['GH_TOKEN']}", "Accept": "application/vnd.github+json"} if raw: h["Accept"] = "application/octet-stream" return h def gh_assets(tag): r = requests.get(f"https://api.github.com/repos/{GH}/releases/tags/{tag}", headers=gh_headers(), timeout=60) r.raise_for_status() return {a["name"]: a for a in r.json()["assets"]} def gh_get(tag, name, dst): dst = Path(dst) if dst.exists(): return dst a = gh_assets(tag)[name] tmp = dst.with_suffix(dst.suffix + ".part") with requests.get(a["url"], headers=gh_headers(True), stream=True, timeout=3600) as r, open(tmp, "wb") as f: r.raise_for_status() for b in r.iter_content(8 << 20): f.write(b) tmp.rename(dst) return dst class Chain(io.RawIOBase): """The tar's parts, streamed one after another as one file.""" def __init__(self, urls): self.urls, self.it = list(urls), None def readable(self): return True def readinto(self, b): while True: if self.it is None: if not self.urls: return 0 self.r = requests.get(self.urls.pop(0), headers=gh_headers(True), stream=True, timeout=3600) self.r.raise_for_status() self.it, self.buf = self.r.iter_content(4 << 20), b"" if not self.buf: self.buf = next(self.it, b"") if not self.buf: self.it = None continue n = min(len(b), len(self.buf)) b[:n], self.buf = self.buf[:n], self.buf[n:] return n def fetch_vec2(): d = DATA / "vec2" want = ["docs.i8", "docs.seg", "ivf.idx", "ivf.cen"] if all((d / w).exists() for w in want): return d d.mkdir(exist_ok=True) a = gh_assets("neural-v2-v1") parts = sorted([x for x in a if x.startswith("card_vec2.tar")]) with tarfile.open(fileobj=io.BufferedReader(Chain([a[p]["url"] for p in parts]), 8 << 20), mode="r|") as t: for m in t: name = m.name.split("/")[-1] if name in want: f = t.extractfile(m) with open(d / (name + ".part"), "wb") as o: while True: b = f.read(8 << 20) if not b: break o.write(b) (d / (name + ".part")).rename(d / name) return d def hf(p): return Path(hf_hub_download(REPO, p, repo_type="dataset", local_dir=str(DATA / "hf"), token=os.environ.get("HF_TOKEN"))) TAGS, WS = re.compile(r"<[^>]+>"), re.compile(r"\s+") MARKS = re.compile("[֑-ׇ]") def clean(s): return WS.sub(" ", html.unescape(TAGS.sub(" ", s))).strip() def plain_he(s): return MARKS.sub(lambda m: " " if m.group(0) in "־׃" else "", s) def gematria(n): h, t, c = " אבגדהוזחט", " יכלמנסעפצ", " קרשת" if n <= 0 or n > 999: return str(n) out = "ת" * (n // 400) + c[(n % 400) // 100].strip() n %= 100 if n == 15: return out + "טו" if n == 16: return out + "טז" return out + t[n // 10].strip() + h[n % 10].strip() def marked(n): s = gematria(n) if not s.isalpha() or n > 999: return s return s + "׳" if len(s) == 1 else s[:-1] + "״" + s[-1] def cpu_quota(): try: q, p = Path("/sys/fs/cgroup/cpu.max").read_text().split() if q != "max": return max(1, round(int(q) / int(p))) except Exception: pass return len(os.sched_getaffinity(0)) SECTION_HE = {"Orach Chayim": "אורח חיים", "Yoreh De'ah": "יורה דעה", "Even HaEzer": "אבן העזר", "Choshen Mishpat": "חושן משפט", "Introduction": "הקדמה", "Preface": "פתיחה", "Addenda": "הוספות"} def load(): try: S["stage"] = "lexicon" lex = {f: hf(f"lex/{f}") for f in ["segs.txt", "snip.idx", "snip.txt", "terms.txt", "terms.idx", "post.idx", "post.dat"]} lines = lex["segs.txt"].read_bytes().decode("utf-8").split("\n") if lines[-1] == "": lines.pop() X["title"] = [ln.split("\t", 1)[0] for ln in lines] X["sec"] = [ln.split("\t", 1)[1] if "\t" in ln else "" for ln in lines] n = X["n"] = len(lines) del lines X["snip_idx"] = np.fromfile(lex["snip.idx"], dtype=np.uint32) X["snip"] = np.memmap(lex["snip.txt"], dtype=np.uint8, mode="r") X["terms"] = lex["terms.txt"].read_bytes().decode("utf-8").split("\n") X["post_idx"] = np.fromfile(lex["post.idx"], dtype=np.uint32) X["post"] = np.memmap(lex["post.dat"], dtype=np.uint32, mode="r") X["cls"] = np.fromfile(gh_get("primary-vote2-v1", "segclass.u8", DATA / "segclass.u8"), dtype=np.uint8) assert len(X["cls"]) == n # works: contiguous runs of one title starts = [0] + [i for i in range(1, n) if X["title"][i] != X["title"][i - 1]] X["wstart"] = np.array(starts + [n], dtype=np.int64) he = {} for ln in hf("card/crosspoint/index.tsv").read_text(encoding="utf-8").splitlines(): p = ln.split("\t") if len(p) >= 2: he.setdefault(p[1], html.unescape(p[0])) X["he"] = he bav = {X["title"][s] for s in starts if (X["cls"][s] & 0x0F) == 1} X["bavli"] = bav S["stage"] = "translations" en = {} with open(hf("english.jsonl"), encoding="utf-8") as f: for line in f: j = json.loads(line) en[j["ref"]] = j["text"] X["en"] = en S["stage"] = "links" L = {f: hf(f"card/ner/links/{f}") for f in ["refseg.idx", "links.idx", "links.dat"]} refseg = np.fromfile(L["refseg.idx"], dtype=np.uint32) lidx = np.fromfile(L["links.idx"], dtype=np.uint32) ldat = np.fromfile(L["links.dat"], dtype=np.uint32) # The Talmud is in the index twice under one ref, Hebrew and English # (Chullin 59a:14 = segments 2177416 and 3356674); links reach only one. first, twin = {}, {} for i in range(n): k = X["title"][i] + "\t" + X["sec"][i] j = first.setdefault(k, i) if j != i: twin[i], twin[j] = j, i X["twin"] = twin # "Rashi on Chullin" comments on "Chullin": base title -> commentary works on = defaultdict(list) for a, b in zip(X["wstart"][:-1].tolist(), X["wstart"][1:].tolist()): t = X["title"][a] if " on " in t: on[t.split(" on ", 1)[1]].append((a, b)) X["on"] = dict(on) S["twins"] = len(twin) // 2 del first src = np.repeat(np.arange(len(refseg), dtype=np.uint32), np.diff(lidx).astype(np.int64)) a_, b_ = refseg[src], refseg[ldat] del src, ldat keep = (a_ != NONE) & (b_ != NONE) & (a_ != b_) a2, b2 = np.concatenate([a_[keep], b_[keep]]), np.concatenate([b_[keep], a_[keep]]) del a_, b_, keep o = np.lexsort((b2, a2)); a2, b2 = a2[o], b2[o] dup = np.r_[False, (a2[1:] == a2[:-1]) & (b2[1:] == b2[:-1])] a2, b2 = a2[~dup], b2[~dup] X["lptr"] = np.searchsorted(a2, np.arange(n + 1, dtype=np.uint32)) X["ldst"] = b2 del a2, o, dup rel = gh_get("related-v2-v1", "rel.dat", DATA / "rel.dat") rec = np.dtype([("seg", " cap else t def english(s, cap=None): t = X["en"].get(X["title"][s] + " " + X["sec"][s], "") t = clean(t) return t[:cap] + "…" if cap and len(t) > cap else t def item(s, tag, score=None, cap=320): en_ref, he_ref = refs(s) c = int(X["cls"][s]) return {"seg": int(s), "ref": en_ref, "he": he_ref, "shelf": SHELVES[c & 0x0F] if (c & 0x0F) < 8 else "Other", "primary": bool(c & 0x10), "twin": X["twin"].get(int(s)), "tag": tag, "score": None if score is None else round(float(score), 3), **dict(zip(("text", "en"), text_pair(s, cap)))} # ---- meaning ------------------------------------------------------------------------------------------ def encode(q): v = X["model"].encode([f"Instruct: {T_TYPED}\nQuery:{q}"], normalize_embeddings=True)[0][:512] return (v / (np.linalg.norm(v) + 1e-9)).astype(np.float32) def meaning(qv, k=400): ls = np.argsort(-(X["cen"] @ qv))[:NPROBE] rows = np.concatenate([np.arange(X["ivf"][l], X["ivf"][l + 1]) for l in ls]) sc = X["docs"][rows].astype(np.float32) @ qv / 127.0 top = np.argsort(-sc)[:k] return X["dseg"][rows[top]].astype(np.int64), sc[top] # ---- exact words -------------------------------------------------------------------------------------- # As NerLexicalSearch.cpp reads the lexicon: postings pack the segment in the # low 22 bits, tf in bits 22-30, and bit 31 marks a form made by peeling a # Hebrew prefix (weighted 0.35); BM25-saturated tf; then the top candidates' # text is read for how many query words it holds and whether in order. SEG_MASK, TF_MASK, DERIVED = (1 << 22) - 1, 0x1FF, 1 << 31 MAX_POSTINGS = 400_000 # the device stops at 50,000; here there is room WORD = re.compile(r"[א-ת]{2,}|[A-Za-z][A-Za-z']+") PFX = "ובכלמשה" def match_text(s): return " " + " ".join(WORD.findall(plain_he(clean(s)).lower())) + " " def has_word(t, w): for m in re.finditer(r"(?<= )([%s]{0,2})%s(?= )" % (PFX, re.escape(w)), t): return True return False def term_id(w): i = bisect.bisect_left(X["terms"], w) return i if i < len(X["terms"]) and X["terms"][i] == w else -1 def words_search(q, k=400): ws = list(dict.fromkeys(w.lower() for w in WORD.findall(plain_he(q)))) if not ws: return [], [] n, segs_l, wts_l = X["n"], [], [] for w in ws: t = term_id(w) if t < 0: continue a, b = int(X["post_idx"][t]), int(X["post_idx"][t + 1]) if b == a or b - a > MAX_POSTINGS: continue p = np.asarray(X["post"][a:b]) tf = np.maximum((p >> 22) & TF_MASK, 1).astype(np.float32) wt = np.log(n / (b - a)) * tf * 2.2 / (tf + 1.2) * np.where(p & DERIVED, 0.35, 1.0) segs_l.append((p & SEG_MASK).astype(np.int64)); wts_l.append(wt.astype(np.float32)) if not segs_l: return [], [] u, inv = np.unique(np.concatenate(segs_l), return_inverse=True) score = np.bincount(inv, weights=np.concatenate(wts_l)) top = np.argsort(-score)[:max(k, 120)] segs, sc = u[top], score[top].copy() phrase = " " + " ".join(ws) + " " for i in range(min(120, len(segs))): t = match_text(text(int(segs[i]), 1024)) found = sum(has_word(t, w) for w in ws) sc[i] *= (0.25 + found / len(ws)) * (2.0 if len(ws) > 1 and phrase in t else 1.0) o = np.argsort(-sc[:120], kind="stable") return np.concatenate([segs[:120][o], segs[120:]])[:k], np.concatenate([sc[:120][o], sc[120:]])[:k] # ---- shaping, voting ---------------------------------------------------------------------------------- def shape(segs, scores, shelves, limit, seen): out, per_work = [], defaultdict(int) for s, sc in zip(segs, scores): s = int(s) if s in seen: continue c = int(X["cls"][s]) & 0x0F if shelves and c not in shelves: continue a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1]) if b - a < 40: continue t = X["title"][s] if per_work[t] >= 3: continue key = text(s, 200) if key in seen: continue seen.add(s); seen.add(key) if s in X["twin"]: seen.add(X["twin"][s]) per_work[t] += 1 out.append((s, sc)) if len(out) >= limit: break return out def votes(top, decay=0.1, linkw=2.0): v = defaultdict(float) for s, sc in top[:20]: for j, r in enumerate(X["rel"][s]): t = int(r["seg"]) if t == NONE or t >= X["n"] or not (X["cls"][t] & 0x10): continue v[t] += float(sc) / (1 + decay * j) * (linkw if (int(r["sk"]) & 3) == 2 else 1.0) return sorted(v.items(), key=lambda x: -x[1]) # ---- API ---------------------------------------------------------------------------------------------- @app.get("/api/status") def status(): return {**{k: v for k, v in S.items() if k != "t0"}, "elapsed_s": round(time.time() - S["t0"]), "segments": X.get("n")} def need_ready(): if not S["ready"]: raise HTTPException(503, detail={"stage": S["stage"], "error": S["error"]}) # ---- rerank on ZeroGPU --------------------------------------------------------------------------------- RERANK_SPACE = os.environ.get("RERANK_SPACE", "joshruby/ner-rerank") _pool = None _client = None def rerank_scores(q, docs, timeout=25): """p(yes) per doc from Qwen3-Reranker-4B (joshruby/ner-rerank, ZeroGPU, PRO quota), or None.""" global _pool, _client import concurrent.futures as cf from gradio_client import Client if _pool is None: _pool = cf.ThreadPoolExecutor(4) def call(): global _client if _client is None: _client = Client(RERANK_SPACE, hf_token=os.environ.get("HF_TOKEN"), verbose=False) return json.loads(_client.predict(q, json.dumps(docs, ensure_ascii=False), api_name="/rerank")) try: return _pool.submit(call).result(timeout=timeout) except Exception as e: print("rerank failed:", type(e).__name__, e, flush=True) _client = None return None @app.get("/api/search") def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40, rerank: int = 1): need_ready() t0 = time.time() q = q.strip()[:300] sh = {SHELVES.index(x) for x in shelves.split(",") if x in SHELVES} seen = set() m_list, w_list = [], [] tm = {} if mode in ("both", "meaning"): t = time.time(); qv = encode(q); tm["encode"] = time.time() - t t = time.time(); segs, sc = meaning(qv); tm["vectors"] = time.time() - t m_list = shape(segs, sc, sh, 40 if rerank else limit, seen) if mode in ("both", "words"): t = time.time(); segs, sc = words_search(q); tm["words"] = time.time() - t w_list = shape(segs, sc, sh, 25 if rerank and mode == "both" else limit, seen) if mode == "both": merged, i, j = [], 0, 0 while len(merged) < limit and (i < len(m_list) or j < len(w_list)): if i < len(m_list): merged.append((*m_list[i], "meaning")); i += 1 if j < len(w_list) and len(merged) < limit: merged.append((*w_list[j], "words")); j += 1 else: merged = [(s, sc, mode) for s, sc in (m_list or w_list)] trail_src = m_list or w_list voted = votes(trail_src) shown = {s for s, _, _ in merged} trail = [] top_v = voted[0][1] if voted else 1.0 for s, v in voted[:12]: if len(trail) >= 8: break it = item(s, "source", cap=160) it["weight"] = round(v / top_v, 3) trail.append(it) reranked = False if rerank and mode == "both": pool = {} for s_, sc_ in m_list: pool.setdefault(int(s_), "meaning") for s_, sc_ in w_list: pool.setdefault(int(s_), "words") for t_ in trail: if not sh or SHELVES.index(t_["shelf"]) in sh: pool.setdefault(t_["seg"], "source") items = [item(s_, tag_) for s_, tag_ in pool.items()] t = time.time() rs = rerank_scores(q, [f"{h['ref']}\n{h['text']}\n{h['en']}".strip() for h in items]) tm["rerank"] = time.time() - t if rs is not None and len(rs) == len(items): reranked = True per = defaultdict(int) hits = [] for h, r_ in sorted(zip(items, rs), key=lambda x: -x[1]): w = X["title"][h["seg"]] if per[w] >= 3: continue per[w] += 1 hits.append({**h, "score": r_}) if len(hits) >= limit: break if not reranked: merged = merged[:limit] hits = [item(s, tag, sc) for s, sc, tag in merged] # primaries the results point to, placed after the first and third result as on the device ins = [t for t in trail if t["seg"] not in shown and t["weight"] >= 0.3][:2] for pos, t in zip((1, 4), ins): hits.insert(min(pos, len(hits)), {**item(t["seg"], "source"), "weight": t["weight"]}) counts = defaultdict(int) for h in hits: counts[h["shelf"]] += 1 return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail, "reranked": reranked, "counts": counts, "exact": len(w_list), "timing_ms": {k: round(v * 1000) for k, v in tm.items()}} @app.get("/api/passage") def passage(seg: int): need_ready() if not 0 <= seg < X["n"]: raise HTTPException(404) a, b = work_of(seg) lo, hi = max(a, seg - 4), min(b, seg + 5) ctx = sorted(range(lo, hi), key=lambda s: [int(p) if p.isdigit() else 0 for p in X["sec"][s].split(".") if p]) links, comments, similar = [], [], [] # commentaries laid out on this passage's own numbering title, sec = X["title"][seg], X["sec"][seg] pre = sec.rstrip(".") + "." amud = sec.split(".")[0] + "." structural = [] for a, b in X["on"].get(title, []): exact = [t for t in range(a, b) if X["sec"][t].startswith(pre)] if not exact and talmudic(title): exact = [t for t in range(a, b) if X["sec"][t].startswith(amud)][:6] structural += sorted(exact, key=lambda t: [int(p) if p.isdigit() else 0 for p in X["sec"][t].split(".") if p])[:12] linked = X["ldst"][X["lptr"][seg]:X["lptr"][seg + 1]].astype(np.int64) tw = X["twin"].get(seg) if tw is not None: linked = np.unique(np.concatenate([linked, X["ldst"][X["lptr"][tw]:X["lptr"][tw + 1]].astype(np.int64)])) # commentaries on this passage, then everything else it links to, primary sources first done = set() for t in structural + sorted(linked.tolist(), key=lambda t: (not (X["cls"][t] & 0x10), int(X["cls"][t]) & 0x0F, t))[:400]: if t in done: continue done.add(t) title = X["title"][t] if " on " in title: if len(comments) < 120: it = item(t, "link", cap=400) it["by"] = title.split(" on ")[0] comments.append(it) elif len(links) < 40: links.append(item(t, "link", cap=160)) have = set(linked.tolist()) for r in X["rel"][seg]: t = int(r["seg"]) if t != NONE and t < X["n"] and t not in have and X["title"][t] != X["title"][seg] and len(similar) < 8: similar.append(item(t, "similar", cap=160)) en_ref, he_ref = refs(seg) return {"seg": seg, "ref": en_ref, "he": he_ref, "title": X["title"][seg], "heTitle": X["he"].get(X["title"][seg], X["title"][seg]), "shelf": item(seg, "")["shelf"], "context": [{"seg": s, "focus": s == seg, "ref": refs(s)[0], **dict(zip(("text", "en"), text_pair(s)))} for s in ctx], "comments": comments, "links": links, "similar": similar[:8]} @app.get("/") def root(): return {"ok": True, "see": "/api/status"} def ref_index(): if "refidx" not in X: d = {} for i in range(X["n"]): d.setdefault(refs(i)[0].lower(), i) X["refidx"] = d return X["refidx"] @app.get("/api/ref") def by_ref(r: str): """A Sefaria-style ref ("Rashi on Chullin 59a:14:1") -> its segment and its link count.""" need_ready() s = ref_index().get(r.strip().lower()) if s is None: raise HTTPException(404) return {"seg": s, "ref": refs(s)[0], "he": refs(s)[1], "links": int(X["lptr"][s + 1] - X["lptr"][s]), "twin": X["twin"].get(s), "cls": int(X["cls"][s])}