File size: 24,883 Bytes
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde145d
661e823
dde145d
661e823
 
 
 
 
 
 
 
 
 
dde145d
661e823
 
 
 
da94c61
 
 
 
 
 
 
 
 
 
dde145d
 
 
 
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d78fb37
dde145d
 
 
d78fb37
 
 
 
 
 
 
 
 
b12033a
 
 
 
 
 
 
d78fb37
 
dde145d
 
 
 
 
 
 
 
 
 
 
 
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
da94c61
661e823
 
 
 
da94c61
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde145d
661e823
 
 
 
 
 
 
 
 
d78fb37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82b22e
d78fb37
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da94c61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661e823
 
 
 
 
 
 
 
da94c61
661e823
 
da94c61
 
 
 
661e823
da94c61
 
661e823
da94c61
 
 
 
 
661e823
da94c61
 
 
 
 
 
 
 
 
 
 
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d78fb37
 
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783e1a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661e823
783e1a0
661e823
 
 
 
 
 
da94c61
661e823
da94c61
 
783e1a0
661e823
da94c61
783e1a0
661e823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783e1a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661e823
 
 
783e1a0
da94c61
 
661e823
 
 
 
 
 
 
 
 
 
 
b12033a
 
 
 
 
 
 
 
 
 
dde145d
d78fb37
 
 
dde145d
b12033a
 
 
 
 
661e823
b12033a
dde145d
 
 
 
 
 
 
 
 
d78fb37
dde145d
661e823
 
 
d78fb37
661e823
 
 
 
 
 
4e3dd3c
6960be2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
"""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", "<u4"), ("sk", "u1")])
        X["rel"] = np.memmap(rel, dtype=rec, mode="r").reshape(n, -1)

        S["stage"] = "vectors (2.9 GB)"
        d = fetch_vec2()
        X["docs"] = np.fromfile(d / "docs.i8", dtype=np.int8).reshape(-1, 512)
        X["dseg"] = np.fromfile(d / "docs.seg", dtype=np.uint32)
        X["ivf"] = np.fromfile(d / "ivf.idx", dtype=np.uint32)
        X["cen"] = np.fromfile(d / "ivf.cen", dtype=np.int8).reshape(-1, 512).astype(np.float32)

        S["stage"] = "model"
        import torch
        from sentence_transformers import SentenceTransformer
        torch.set_num_threads(cpu_quota())
        m = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B", device="cpu")
        m.max_seq_length = 256
        X["model"] = m
        encode("warm up")
        S["threads"] = torch.get_num_threads()
        S["stage"], S["ready"] = "ready", True
        S["load_s"] = round(time.time() - S["t0"])
    except Exception as e:  # shown by /api/status
        import traceback
        traceback.print_exc()
        S["error"] = f"{type(e).__name__}: {e}"


threading.Thread(target=load, daemon=True).start()


# ---- refs, text --------------------------------------------------------------------------------------
def work_of(s):
    i = int(np.searchsorted(X["wstart"], s, side="right")) - 1
    return int(X["wstart"][i]), int(X["wstart"][i + 1])


def talmudic(title):
    if title in X["bavli"]:
        return True
    _, on, base = title.rpartition(" on ")
    return bool(on) and base in X["bavli"]


def refs(s):
    title, sec = X["title"][s], X["sec"][s]
    parts = [p for p in sec.split(".") if p]
    tal = talmudic(title) and parts and parts[0].isdigit()
    en_parts, he_parts = [], []
    for i, p in enumerate(parts):
        if i == 0 and tal:
            k = int(p)
            daf, amud = (k + 1) // 2, "a" if k % 2 else "b"
            en_parts.append(f"{daf}{amud}")
            he_parts.append(f"{marked(daf)} {'ע״א' if amud == 'a' else 'ע״ב'}")
        elif p.isdigit():
            en_parts.append(p)
            he_parts.append(marked(int(p)))
        else:
            en_parts.append(p)
            he_parts.append(SECTION_HE.get(p) or X["he"].get(p) or p)
    en_ref = (title + " " + ":".join(en_parts)).strip()
    het = X["he"].get(title)
    if het is None:
        _, on, base = title.rpartition(" on ")
        het = title
    he_ref = (het + " " + ", ".join(he_parts[: 1 if tal else 2])).strip()
    return en_ref, he_ref


def has_he(t):
    return any("\u05d0" <= c <= "\u05ea" for c in t[:200])


def text_pair(s, cap=None):
    """(Hebrew, English) for a segment, taking whichever twin holds which."""
    t, e = text(s, cap), english(s, cap)
    tw = X["twin"].get(s)
    if tw is not None:
        t2 = text(tw, cap)
        if has_he(t2) and not has_he(t):
            t, e = t2, e or t
        elif has_he(t) and not e:
            e = english(tw, cap) or (t2 if not has_he(t2) else "")
    if not has_he(t) and not e:
        t, e = "", t
    if e == t:
        e = ""
    return t, e


def text(s, cap=None):
    a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1])
    if cap:
        b = min(b, a + cap * 3)
    t = clean(bytes(X["snip"][a:b]).decode("utf-8", "ignore"))
    return t[:cap] + "…" if cap and len(t) > 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])}