Spaces:
Running
Running
Ner research API
Browse files- Dockerfile +9 -0
- README.md +5 -4
- app.py +468 -0
Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
RUN pip install --no-cache-dir torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu && \
|
| 3 |
+
pip install --no-cache-dir "transformers==4.57.1" "sentence-transformers==5.1.2" fastapi==0.115.6 "uvicorn[standard]==0.32.1" numpy==2.1.3 requests huggingface_hub
|
| 4 |
+
RUN useradd -m -u 1000 user
|
| 5 |
+
USER user
|
| 6 |
+
ENV HOME=/home/user PYTHONUNBUFFERED=1 HF_HOME=/home/user/hfcache
|
| 7 |
+
WORKDIR /home/user/app
|
| 8 |
+
COPY --chown=user app.py .
|
| 9 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,11 @@
|
|
| 1 |
---
|
| 2 |
-
title: Ner
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: gray
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Ner research
|
| 3 |
+
emoji: ๐ฏ๏ธ
|
| 4 |
+
colorFrom: gray
|
| 5 |
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
Search API for Ner research: Qwen3-Embedding-0.6B over the Ner card's own index of the Sefaria library.
|
app.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ner research API: the full Qwen3 query encoder over the card's own index.
|
| 2 |
+
|
| 3 |
+
The device turns a query into a vector with a small static table; here the
|
| 4 |
+
real Qwen3-Embedding-0.6B does it (blind test: right answer in the top 3 for
|
| 5 |
+
70% of queries against the device's 58%), searching the same 512-dim int8
|
| 6 |
+
documents, IVF lists, lexicon, snippets and rel.dat that ship on the card.
|
| 7 |
+
Everything loads in a background thread at start; /api/status says how far.
|
| 8 |
+
"""
|
| 9 |
+
import bisect, html, io, json, os, re, tarfile, threading, time
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import requests
|
| 15 |
+
from fastapi import FastAPI, HTTPException
|
| 16 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
+
from huggingface_hub import hf_hub_download
|
| 18 |
+
|
| 19 |
+
REPO, GH = "joshruby/sefaria-embed", "sirch613/Diyo"
|
| 20 |
+
DATA = Path(os.environ.get("DATA", str(Path.home() / "data")))
|
| 21 |
+
DATA.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
NPROBE = int(os.environ.get("NPROBE", "64"))
|
| 23 |
+
T_TYPED = ("Given a question or topic, retrieve passages from the Jewish library (Tanakh, Talmud, Midrash, "
|
| 24 |
+
"halacha, commentaries, responsa, Chasidut) that answer it")
|
| 25 |
+
NONE = 0xFFFFFFFF
|
| 26 |
+
SHELVES = ["Tanakh", "Talmud", "Mishnah", "Halakha", "Commentary", "Midrash", "Other", "Lexicon"]
|
| 27 |
+
|
| 28 |
+
app = FastAPI()
|
| 29 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"])
|
| 30 |
+
S = {"stage": "starting", "ready": False, "error": None, "t0": time.time()}
|
| 31 |
+
X = {} # loaded index
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def gh_headers(raw=False):
|
| 35 |
+
h = {"Authorization": f"Bearer {os.environ['GH_TOKEN']}", "Accept": "application/vnd.github+json"}
|
| 36 |
+
if raw:
|
| 37 |
+
h["Accept"] = "application/octet-stream"
|
| 38 |
+
return h
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def gh_assets(tag):
|
| 42 |
+
r = requests.get(f"https://api.github.com/repos/{GH}/releases/tags/{tag}", headers=gh_headers(), timeout=60)
|
| 43 |
+
r.raise_for_status()
|
| 44 |
+
return {a["name"]: a for a in r.json()["assets"]}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def gh_get(tag, name, dst):
|
| 48 |
+
dst = Path(dst)
|
| 49 |
+
if dst.exists():
|
| 50 |
+
return dst
|
| 51 |
+
a = gh_assets(tag)[name]
|
| 52 |
+
tmp = dst.with_suffix(dst.suffix + ".part")
|
| 53 |
+
with requests.get(a["url"], headers=gh_headers(True), stream=True, timeout=3600) as r, open(tmp, "wb") as f:
|
| 54 |
+
r.raise_for_status()
|
| 55 |
+
for b in r.iter_content(8 << 20):
|
| 56 |
+
f.write(b)
|
| 57 |
+
tmp.rename(dst)
|
| 58 |
+
return dst
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Chain(io.RawIOBase):
|
| 62 |
+
"""The tar's parts, streamed one after another as one file."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, urls):
|
| 65 |
+
self.urls, self.it = list(urls), None
|
| 66 |
+
|
| 67 |
+
def readable(self):
|
| 68 |
+
return True
|
| 69 |
+
|
| 70 |
+
def readinto(self, b):
|
| 71 |
+
while True:
|
| 72 |
+
if self.it is None:
|
| 73 |
+
if not self.urls:
|
| 74 |
+
return 0
|
| 75 |
+
self.r = requests.get(self.urls.pop(0), headers=gh_headers(True), stream=True, timeout=3600)
|
| 76 |
+
self.r.raise_for_status()
|
| 77 |
+
self.it, self.buf = self.r.iter_content(4 << 20), b""
|
| 78 |
+
if not self.buf:
|
| 79 |
+
self.buf = next(self.it, b"")
|
| 80 |
+
if not self.buf:
|
| 81 |
+
self.it = None
|
| 82 |
+
continue
|
| 83 |
+
n = min(len(b), len(self.buf))
|
| 84 |
+
b[:n], self.buf = self.buf[:n], self.buf[n:]
|
| 85 |
+
return n
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def fetch_vec2():
|
| 89 |
+
d = DATA / "vec2"
|
| 90 |
+
want = ["docs.i8", "docs.seg", "ivf.idx", "ivf.cen"]
|
| 91 |
+
if all((d / w).exists() for w in want):
|
| 92 |
+
return d
|
| 93 |
+
d.mkdir(exist_ok=True)
|
| 94 |
+
a = gh_assets("neural-v2-v1")
|
| 95 |
+
parts = sorted([x for x in a if x.startswith("card_vec2.tar")])
|
| 96 |
+
with tarfile.open(fileobj=io.BufferedReader(Chain([a[p]["url"] for p in parts]), 8 << 20), mode="r|") as t:
|
| 97 |
+
for m in t:
|
| 98 |
+
name = m.name.split("/")[-1]
|
| 99 |
+
if name in want:
|
| 100 |
+
f = t.extractfile(m)
|
| 101 |
+
with open(d / (name + ".part"), "wb") as o:
|
| 102 |
+
while True:
|
| 103 |
+
b = f.read(8 << 20)
|
| 104 |
+
if not b:
|
| 105 |
+
break
|
| 106 |
+
o.write(b)
|
| 107 |
+
(d / (name + ".part")).rename(d / name)
|
| 108 |
+
return d
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def hf(p):
|
| 112 |
+
return Path(hf_hub_download(REPO, p, repo_type="dataset", local_dir=str(DATA / "hf"), token=os.environ.get("HF_TOKEN")))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
TAGS, WS = re.compile(r"<[^>]+>"), re.compile(r"\s+")
|
| 116 |
+
MARKS = re.compile("[ึ-ื]")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def clean(s):
|
| 120 |
+
return WS.sub(" ", html.unescape(TAGS.sub(" ", s))).strip()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def plain_he(s):
|
| 124 |
+
return MARKS.sub(lambda m: " " if m.group(0) in "ึพื" else "", s)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def gematria(n):
|
| 128 |
+
h, t, c = " ืืืืืืืืื", " ืืืืื ืกืขืคืฆ", " ืงืจืฉืช"
|
| 129 |
+
if n <= 0 or n > 499:
|
| 130 |
+
return str(n)
|
| 131 |
+
out = c[n // 100].strip()
|
| 132 |
+
n %= 100
|
| 133 |
+
if n == 15:
|
| 134 |
+
return out + "ืื"
|
| 135 |
+
if n == 16:
|
| 136 |
+
return out + "ืื"
|
| 137 |
+
return out + t[n // 10].strip() + h[n % 10].strip()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def marked(n):
|
| 141 |
+
s = gematria(n)
|
| 142 |
+
if not s.isalpha() or n > 499:
|
| 143 |
+
return s
|
| 144 |
+
return s + "ืณ" if len(s) == 1 else s[:-1] + "ืด" + s[-1]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def load():
|
| 148 |
+
try:
|
| 149 |
+
S["stage"] = "lexicon"
|
| 150 |
+
lex = {f: hf(f"lex/{f}") for f in ["segs.txt", "snip.idx", "snip.txt", "terms.txt", "terms.idx", "post.idx", "post.dat"]}
|
| 151 |
+
lines = lex["segs.txt"].read_bytes().decode("utf-8").split("\n")
|
| 152 |
+
if lines[-1] == "":
|
| 153 |
+
lines.pop()
|
| 154 |
+
X["title"] = [ln.split("\t", 1)[0] for ln in lines]
|
| 155 |
+
X["sec"] = [ln.split("\t", 1)[1] if "\t" in ln else "" for ln in lines]
|
| 156 |
+
n = X["n"] = len(lines)
|
| 157 |
+
del lines
|
| 158 |
+
X["snip_idx"] = np.fromfile(lex["snip.idx"], dtype=np.uint32)
|
| 159 |
+
X["snip"] = np.memmap(lex["snip.txt"], dtype=np.uint8, mode="r")
|
| 160 |
+
X["terms"] = lex["terms.txt"].read_bytes().decode("utf-8").split("\n")
|
| 161 |
+
X["post_idx"] = np.fromfile(lex["post.idx"], dtype=np.uint32)
|
| 162 |
+
X["post"] = np.memmap(lex["post.dat"], dtype=np.uint32, mode="r")
|
| 163 |
+
X["cls"] = np.fromfile(gh_get("primary-vote2-v1", "segclass.u8", DATA / "segclass.u8"), dtype=np.uint8)
|
| 164 |
+
assert len(X["cls"]) == n
|
| 165 |
+
# works: contiguous runs of one title
|
| 166 |
+
starts = [0] + [i for i in range(1, n) if X["title"][i] != X["title"][i - 1]]
|
| 167 |
+
X["wstart"] = np.array(starts + [n], dtype=np.int64)
|
| 168 |
+
he = {}
|
| 169 |
+
for ln in hf("card/crosspoint/index.tsv").read_text(encoding="utf-8").splitlines():
|
| 170 |
+
p = ln.split("\t")
|
| 171 |
+
if len(p) >= 2:
|
| 172 |
+
he.setdefault(p[1], html.unescape(p[0]))
|
| 173 |
+
X["he"] = he
|
| 174 |
+
bav = {X["title"][s] for s in starts if (X["cls"][s] & 0x0F) == 1}
|
| 175 |
+
X["bavli"] = bav
|
| 176 |
+
|
| 177 |
+
S["stage"] = "translations"
|
| 178 |
+
en = {}
|
| 179 |
+
with open(hf("english.jsonl"), encoding="utf-8") as f:
|
| 180 |
+
for line in f:
|
| 181 |
+
j = json.loads(line)
|
| 182 |
+
en[j["ref"]] = j["text"]
|
| 183 |
+
X["en"] = en
|
| 184 |
+
|
| 185 |
+
S["stage"] = "links"
|
| 186 |
+
rel = gh_get("related-v2-v1", "rel.dat", DATA / "rel.dat")
|
| 187 |
+
rec = np.dtype([("seg", "<u4"), ("sk", "u1")])
|
| 188 |
+
X["rel"] = np.memmap(rel, dtype=rec, mode="r").reshape(n, -1)
|
| 189 |
+
|
| 190 |
+
S["stage"] = "vectors (2.9 GB)"
|
| 191 |
+
d = fetch_vec2()
|
| 192 |
+
X["docs"] = np.fromfile(d / "docs.i8", dtype=np.int8).reshape(-1, 512)
|
| 193 |
+
X["dseg"] = np.fromfile(d / "docs.seg", dtype=np.uint32)
|
| 194 |
+
X["ivf"] = np.fromfile(d / "ivf.idx", dtype=np.uint32)
|
| 195 |
+
X["cen"] = np.fromfile(d / "ivf.cen", dtype=np.int8).reshape(-1, 512).astype(np.float32)
|
| 196 |
+
|
| 197 |
+
S["stage"] = "model"
|
| 198 |
+
import torch
|
| 199 |
+
from sentence_transformers import SentenceTransformer
|
| 200 |
+
torch.set_num_threads(max(1, os.cpu_count() or 1))
|
| 201 |
+
m = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B", device="cpu")
|
| 202 |
+
m.max_seq_length = 256
|
| 203 |
+
X["model"] = m
|
| 204 |
+
encode("warm up")
|
| 205 |
+
S["stage"], S["ready"] = "ready", True
|
| 206 |
+
S["load_s"] = round(time.time() - S["t0"])
|
| 207 |
+
except Exception as e: # shown by /api/status
|
| 208 |
+
import traceback
|
| 209 |
+
traceback.print_exc()
|
| 210 |
+
S["error"] = f"{type(e).__name__}: {e}"
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
threading.Thread(target=load, daemon=True).start()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# ---- refs, text --------------------------------------------------------------------------------------
|
| 217 |
+
def work_of(s):
|
| 218 |
+
i = int(np.searchsorted(X["wstart"], s, side="right")) - 1
|
| 219 |
+
return int(X["wstart"][i]), int(X["wstart"][i + 1])
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def talmudic(title):
|
| 223 |
+
if title in X["bavli"]:
|
| 224 |
+
return True
|
| 225 |
+
_, on, base = title.rpartition(" on ")
|
| 226 |
+
return bool(on) and base in X["bavli"]
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def refs(s):
|
| 230 |
+
title, sec = X["title"][s], X["sec"][s]
|
| 231 |
+
parts = [p for p in sec.split(".") if p]
|
| 232 |
+
tal = talmudic(title) and parts and parts[0].isdigit()
|
| 233 |
+
en_parts, he_parts = [], []
|
| 234 |
+
for i, p in enumerate(parts):
|
| 235 |
+
if i == 0 and tal:
|
| 236 |
+
k = int(p)
|
| 237 |
+
daf, amud = (k + 1) // 2, "a" if k % 2 else "b"
|
| 238 |
+
en_parts.append(f"{daf}{amud}")
|
| 239 |
+
he_parts.append(f"{marked(daf)} {'ืขืดื' if amud == 'a' else 'ืขืดื'}")
|
| 240 |
+
elif p.isdigit():
|
| 241 |
+
en_parts.append(p)
|
| 242 |
+
he_parts.append(marked(int(p)))
|
| 243 |
+
else:
|
| 244 |
+
en_parts.append(p)
|
| 245 |
+
he_parts.append(p)
|
| 246 |
+
en_ref = (title + " " + ":".join(en_parts)).strip()
|
| 247 |
+
het = X["he"].get(title)
|
| 248 |
+
if het is None:
|
| 249 |
+
_, on, base = title.rpartition(" on ")
|
| 250 |
+
het = title
|
| 251 |
+
he_ref = (het + " " + ", ".join(he_parts[: 1 if tal else 2])).strip()
|
| 252 |
+
return en_ref, he_ref
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def text(s, cap=None):
|
| 256 |
+
a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1])
|
| 257 |
+
if cap:
|
| 258 |
+
b = min(b, a + cap * 3)
|
| 259 |
+
t = clean(bytes(X["snip"][a:b]).decode("utf-8", "ignore"))
|
| 260 |
+
return t[:cap] + "โฆ" if cap and len(t) > cap else t
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def english(s, cap=None):
|
| 264 |
+
t = X["en"].get(X["title"][s] + " " + X["sec"][s], "")
|
| 265 |
+
t = clean(t)
|
| 266 |
+
return t[:cap] + "โฆ" if cap and len(t) > cap else t
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def item(s, tag, score=None, cap=320):
|
| 270 |
+
en_ref, he_ref = refs(s)
|
| 271 |
+
c = int(X["cls"][s])
|
| 272 |
+
return {"seg": int(s), "ref": en_ref, "he": he_ref, "shelf": SHELVES[c & 0x0F] if (c & 0x0F) < 8 else "Other",
|
| 273 |
+
"primary": bool(c & 0x10), "tag": tag, "score": None if score is None else round(float(score), 3),
|
| 274 |
+
"text": text(s, cap), "en": english(s, cap)}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# ---- meaning ------------------------------------------------------------------------------------------
|
| 278 |
+
def encode(q):
|
| 279 |
+
v = X["model"].encode([f"Instruct: {T_TYPED}\nQuery:{q}"], normalize_embeddings=True)[0][:512]
|
| 280 |
+
return (v / (np.linalg.norm(v) + 1e-9)).astype(np.float32)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def meaning(qv, k=400):
|
| 284 |
+
ls = np.argsort(-(X["cen"] @ qv))[:NPROBE]
|
| 285 |
+
rows = np.concatenate([np.arange(X["ivf"][l], X["ivf"][l + 1]) for l in ls])
|
| 286 |
+
sc = X["docs"][rows].astype(np.float32) @ qv / 127.0
|
| 287 |
+
top = np.argsort(-sc)[:k]
|
| 288 |
+
return X["dseg"][rows[top]].astype(np.int64), sc[top]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# ---- exact words --------------------------------------------------------------------------------------
|
| 292 |
+
PREF = ["", "ื", "ื", "ื", "ื", "ื", "ืฉ", "ื", "ื", "ืื", "ืื", "ืื", "ืื", "ืืฉ", "ืฉื", "ืฉื", "ืฉื", "ืื", "ืื", "ืื", "ืืฉ", "ืื", "ืื"]
|
| 293 |
+
HEW = re.compile(r"[ื-ืช]+(?:[\"'ืดืณ][ื-ืช]+)?")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def term_id(w):
|
| 297 |
+
i = bisect.bisect_left(X["terms"], w)
|
| 298 |
+
return i if i < len(X["terms"]) and X["terms"][i] == w else -1
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def postings(t):
|
| 302 |
+
a, b = int(X["post_idx"][t]), int(X["post_idx"][t + 1])
|
| 303 |
+
return np.asarray(X["post"][a:b])
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def words_search(q, k=400):
|
| 307 |
+
ws = [w.replace("ืด", '"').replace("ืณ", "'") for w in HEW.findall(plain_he(q))]
|
| 308 |
+
if not ws:
|
| 309 |
+
return [], []
|
| 310 |
+
n, per = X["n"], []
|
| 311 |
+
for w in dict.fromkeys(ws):
|
| 312 |
+
ps = [postings(t) for t in (term_id(p + w) for p in PREF) if t >= 0]
|
| 313 |
+
if not ps:
|
| 314 |
+
continue
|
| 315 |
+
p = np.unique(np.concatenate(ps))
|
| 316 |
+
if len(p) > n // 6: # a stopword: matches everything, ranks nothing
|
| 317 |
+
continue
|
| 318 |
+
per.append((p, np.log(n / len(p))))
|
| 319 |
+
if not per:
|
| 320 |
+
return [], []
|
| 321 |
+
allp = np.concatenate([p for p, _ in per])
|
| 322 |
+
wts = np.concatenate([np.full(len(p), w, dtype=np.float32) for p, w in per])
|
| 323 |
+
u, inv = np.unique(allp, return_inverse=True)
|
| 324 |
+
score = np.bincount(inv, weights=wts)
|
| 325 |
+
cover = np.bincount(inv)
|
| 326 |
+
key = cover * 1000.0 + score
|
| 327 |
+
top = np.argsort(-key)[:max(k, 120)]
|
| 328 |
+
segs, sc = u[top].astype(np.int64), score[top]
|
| 329 |
+
phrase = " ".join(ws)
|
| 330 |
+
if len(ws) > 1:
|
| 331 |
+
sc = sc.copy()
|
| 332 |
+
for i in range(min(120, len(segs))):
|
| 333 |
+
if phrase in plain_he(text(int(segs[i]))):
|
| 334 |
+
sc[i] *= 2
|
| 335 |
+
o = np.lexsort((-sc[:120], -cover[top][:120]))
|
| 336 |
+
segs = np.concatenate([segs[:120][o], segs[120:]])
|
| 337 |
+
sc = np.concatenate([sc[:120][o], sc[120:]])
|
| 338 |
+
return segs[:k], sc[:k]
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# ---- shaping, voting ----------------------------------------------------------------------------------
|
| 342 |
+
def shape(segs, scores, shelves, limit, seen):
|
| 343 |
+
out, per_work = [], defaultdict(int)
|
| 344 |
+
for s, sc in zip(segs, scores):
|
| 345 |
+
s = int(s)
|
| 346 |
+
if s in seen:
|
| 347 |
+
continue
|
| 348 |
+
c = int(X["cls"][s]) & 0x0F
|
| 349 |
+
if shelves and c not in shelves:
|
| 350 |
+
continue
|
| 351 |
+
a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1])
|
| 352 |
+
if b - a < 40:
|
| 353 |
+
continue
|
| 354 |
+
t = X["title"][s]
|
| 355 |
+
if per_work[t] >= 3:
|
| 356 |
+
continue
|
| 357 |
+
key = text(s, 200)
|
| 358 |
+
if key in seen:
|
| 359 |
+
continue
|
| 360 |
+
seen.add(s); seen.add(key)
|
| 361 |
+
per_work[t] += 1
|
| 362 |
+
out.append((s, sc))
|
| 363 |
+
if len(out) >= limit:
|
| 364 |
+
break
|
| 365 |
+
return out
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def votes(top, decay=0.1, linkw=2.0):
|
| 369 |
+
v = defaultdict(float)
|
| 370 |
+
for s, sc in top[:20]:
|
| 371 |
+
for j, r in enumerate(X["rel"][s]):
|
| 372 |
+
t = int(r["seg"])
|
| 373 |
+
if t == NONE or t >= X["n"] or not (X["cls"][t] & 0x10):
|
| 374 |
+
continue
|
| 375 |
+
v[t] += float(sc) / (1 + decay * j) * (linkw if (int(r["sk"]) & 3) == 2 else 1.0)
|
| 376 |
+
return sorted(v.items(), key=lambda x: -x[1])
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ---- API ----------------------------------------------------------------------------------------------
|
| 380 |
+
@app.get("/api/status")
|
| 381 |
+
def status():
|
| 382 |
+
return {**{k: v for k, v in S.items() if k != "t0"}, "elapsed_s": round(time.time() - S["t0"]),
|
| 383 |
+
"segments": X.get("n")}
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def need_ready():
|
| 387 |
+
if not S["ready"]:
|
| 388 |
+
raise HTTPException(503, detail={"stage": S["stage"], "error": S["error"]})
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@app.get("/api/search")
|
| 392 |
+
def search(q: str, mode: str = "both", shelves: str = "", limit: int = 40):
|
| 393 |
+
need_ready()
|
| 394 |
+
t0 = time.time()
|
| 395 |
+
q = q.strip()[:300]
|
| 396 |
+
sh = {SHELVES.index(x) for x in shelves.split(",") if x in SHELVES}
|
| 397 |
+
seen = set()
|
| 398 |
+
m_list, w_list = [], []
|
| 399 |
+
if mode in ("both", "meaning"):
|
| 400 |
+
segs, sc = meaning(encode(q))
|
| 401 |
+
m_list = shape(segs, sc, sh, limit, seen)
|
| 402 |
+
if mode in ("both", "words"):
|
| 403 |
+
segs, sc = words_search(q)
|
| 404 |
+
w_list = shape(segs, sc, sh, limit, seen)
|
| 405 |
+
if mode == "both":
|
| 406 |
+
merged, i, j = [], 0, 0
|
| 407 |
+
while len(merged) < limit and (i < len(m_list) or j < len(w_list)):
|
| 408 |
+
if i < len(m_list):
|
| 409 |
+
merged.append((*m_list[i], "meaning")); i += 1
|
| 410 |
+
if j < len(w_list) and len(merged) < limit:
|
| 411 |
+
merged.append((*w_list[j], "words")); j += 1
|
| 412 |
+
else:
|
| 413 |
+
merged = [(s, sc, mode) for s, sc in (m_list or w_list)]
|
| 414 |
+
trail_src = m_list or w_list
|
| 415 |
+
voted = votes(trail_src)
|
| 416 |
+
shown = {s for s, _, _ in merged}
|
| 417 |
+
trail = []
|
| 418 |
+
top_v = voted[0][1] if voted else 1.0
|
| 419 |
+
for s, v in voted[:12]:
|
| 420 |
+
if len(trail) >= 8:
|
| 421 |
+
break
|
| 422 |
+
it = item(s, "source", cap=160)
|
| 423 |
+
it["weight"] = round(v / top_v, 3)
|
| 424 |
+
trail.append(it)
|
| 425 |
+
hits = [item(s, tag, sc) for s, sc, tag in merged]
|
| 426 |
+
# primaries the results point to, placed after the first and third result as on the device
|
| 427 |
+
ins = [t for t in trail if t["seg"] not in shown and t["weight"] >= 0.3][:2]
|
| 428 |
+
for pos, t in zip((1, 4), ins):
|
| 429 |
+
hits.insert(min(pos, len(hits)), {**item(t["seg"], "source"), "weight": t["weight"]})
|
| 430 |
+
counts = defaultdict(int)
|
| 431 |
+
for h in hits:
|
| 432 |
+
counts[h["shelf"]] += 1
|
| 433 |
+
return {"q": q, "mode": mode, "ms": round((time.time() - t0) * 1000), "hits": hits, "trail": trail,
|
| 434 |
+
"counts": counts, "exact": len(w_list)}
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
@app.get("/api/passage")
|
| 438 |
+
def passage(seg: int):
|
| 439 |
+
need_ready()
|
| 440 |
+
if not 0 <= seg < X["n"]:
|
| 441 |
+
raise HTTPException(404)
|
| 442 |
+
a, b = work_of(seg)
|
| 443 |
+
lo, hi = max(a, seg - 4), min(b, seg + 5)
|
| 444 |
+
ctx = sorted(range(lo, hi), key=lambda s: [int(p) if p.isdigit() else 0 for p in X["sec"][s].split(".") if p])
|
| 445 |
+
links, comments, similar = [], [], []
|
| 446 |
+
for j, r in enumerate(X["rel"][seg]):
|
| 447 |
+
t = int(r["seg"])
|
| 448 |
+
if t == NONE or t >= X["n"]:
|
| 449 |
+
continue
|
| 450 |
+
it = item(t, "link" if (int(r["sk"]) & 3) == 2 else "similar", cap=240)
|
| 451 |
+
title = X["title"][t]
|
| 452 |
+
if " on " in title and it["shelf"] == "Commentary":
|
| 453 |
+
it["by"] = title.split(" on ")[0]
|
| 454 |
+
comments.append(it)
|
| 455 |
+
elif it["tag"] == "link":
|
| 456 |
+
links.append(it)
|
| 457 |
+
else:
|
| 458 |
+
similar.append(it)
|
| 459 |
+
en_ref, he_ref = refs(seg)
|
| 460 |
+
return {"seg": seg, "ref": en_ref, "he": he_ref, "title": X["title"][seg], "heTitle": X["he"].get(X["title"][seg], X["title"][seg]),
|
| 461 |
+
"shelf": item(seg, "")["shelf"],
|
| 462 |
+
"context": [{"seg": s, "focus": s == seg, "ref": refs(s)[0], "text": text(s), "en": english(s)} for s in ctx],
|
| 463 |
+
"comments": comments, "links": links, "similar": similar[:8]}
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@app.get("/")
|
| 467 |
+
def root():
|
| 468 |
+
return {"ok": True, "see": "/api/status"}
|