joshruby commited on
Commit
d78fb37
·
verified ·
1 Parent(s): af6184b

Join Hebrew and English twins of each Talmud ref: links, text, dedupe

Browse files
Files changed (1) hide show
  1. app.py +41 -47
app.py CHANGED
@@ -197,28 +197,21 @@ def load():
197
  X["en"] = en
198
 
199
  S["stage"] = "links"
200
- L = {f: hf(f"card/ner/links/{f}") for f in ["refseg.idx", "links.idx", "links.dat", "refs.txt"]}
201
  refseg = np.fromfile(L["refseg.idx"], dtype=np.uint32)
202
- # refseg.idx leaves every Talmud ref unmapped (Chullin: 0 of 4,381), so refs
203
- # without a segment are matched by the segment's own Sefaria-style ref
204
- own = {}
205
- for i in range(n):
206
- own.setdefault(refs(i)[0], i)
207
- rtxt = L["refs.txt"].read_bytes().decode("utf-8").split("\n")
208
- filled = 0
209
- for i in np.flatnonzero(refseg == NONE).tolist():
210
- if i < len(rtxt):
211
- t = own.get(rtxt[i])
212
- if t is not None:
213
- refseg[i] = t
214
- filled += 1
215
- S["refs_filled"] = filled
216
- S["refs_unmapped"] = int((refseg == NONE).sum())
217
- S["refs_sample_unmapped"] = [rtxt[i] for i in np.flatnonzero(refseg == NONE)[:: max(1, int((refseg == NONE).sum()) // 12)][:12].tolist()]
218
- X['rtxt'], X['refseg'] = rtxt, refseg
219
- del own
220
  lidx = np.fromfile(L["links.idx"], dtype=np.uint32)
221
  ldat = np.fromfile(L["links.dat"], dtype=np.uint32)
 
 
 
 
 
 
 
 
 
 
 
222
  src = np.repeat(np.arange(len(refseg), dtype=np.uint32), np.diff(lidx).astype(np.int64))
223
  a_, b_ = refseg[src], refseg[ldat]
224
  del src, ldat
@@ -301,6 +294,27 @@ def refs(s):
301
  return en_ref, he_ref
302
 
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  def text(s, cap=None):
305
  a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1])
306
  if cap:
@@ -320,7 +334,7 @@ def item(s, tag, score=None, cap=320):
320
  c = int(X["cls"][s])
321
  return {"seg": int(s), "ref": en_ref, "he": he_ref, "shelf": SHELVES[c & 0x0F] if (c & 0x0F) < 8 else "Other",
322
  "primary": bool(c & 0x10), "tag": tag, "score": None if score is None else round(float(score), 3),
323
- "text": text(s, cap), "en": english(s, cap)}
324
 
325
 
326
  # ---- meaning ------------------------------------------------------------------------------------------
@@ -414,6 +428,8 @@ def shape(segs, scores, shelves, limit, seen):
414
  if key in seen:
415
  continue
416
  seen.add(s); seen.add(key)
 
 
417
  per_work[t] += 1
418
  out.append((s, sc))
419
  if len(out) >= limit:
@@ -503,6 +519,9 @@ def passage(seg: int):
503
  ctx = sorted(range(lo, hi), key=lambda s: [int(p) if p.isdigit() else 0 for p in X["sec"][s].split(".") if p])
504
  links, comments, similar = [], [], []
505
  linked = X["ldst"][X["lptr"][seg]:X["lptr"][seg + 1]].astype(np.int64)
 
 
 
506
  # commentaries on this passage, then everything else it links to, primary sources first
507
  for t in sorted(linked.tolist(), key=lambda t: (not (X["cls"][t] & 0x10), int(X["cls"][t]) & 0x0F, t))[:400]:
508
  title = X["title"][t]
@@ -516,12 +535,12 @@ def passage(seg: int):
516
  have = set(linked.tolist())
517
  for r in X["rel"][seg]:
518
  t = int(r["seg"])
519
- if t != NONE and t < X["n"] and t not in have and X["title"][t] != X["title"][seg]:
520
  similar.append(item(t, "similar", cap=160))
521
  en_ref, he_ref = refs(seg)
522
  return {"seg": seg, "ref": en_ref, "he": he_ref, "title": X["title"][seg], "heTitle": X["he"].get(X["title"][seg], X["title"][seg]),
523
  "shelf": item(seg, "")["shelf"],
524
- "context": [{"seg": s, "focus": s == seg, "ref": refs(s)[0], "text": text(s), "en": english(s)} for s in ctx],
525
  "comments": comments, "links": links, "similar": similar[:8]}
526
 
527
 
@@ -529,28 +548,3 @@ def passage(seg: int):
529
  def root():
530
  return {"ok": True, "see": "/api/status"}
531
 
532
-
533
- @app.get("/api/debug/links")
534
- def debug_links(seg: int):
535
- need_ready()
536
- deg = np.diff(X["lptr"])
537
- a, b = int(X["lptr"][seg]), int(X["lptr"][seg + 1])
538
- w0, w1 = work_of(seg)
539
- wd = deg[w0:w1]
540
- return {"pairs": int(len(X["ldst"])), "segs_with_links": int((deg > 0).sum()), "deg": b - a,
541
- "work": X["title"][seg], "work_segs": w1 - w0, "work_segs_linked": int((wd > 0).sum()),
542
- "sample": [refs(int(t))[0] for t in X["ldst"][a:a + 8]],
543
- "linked_in_work": [refs(w0 + int(i))[0] for i in np.flatnonzero(wd > 0)[:5]]}
544
-
545
-
546
- @app.get("/api/debug/ref")
547
- def debug_ref(r: str, seg: int = -1):
548
- need_ready()
549
- hits = [i for i, x in enumerate(X["rtxt"]) if x == r][:3]
550
- out = {"matches": [{"i": i, "seg": int(X["refseg"][i]), "seg_ref": refs(int(X["refseg"][i]))[0] if X["refseg"][i] != NONE else None,
551
- "seg_title": X["title"][int(X["refseg"][i])] if X["refseg"][i] != NONE else None} for i in hits]}
552
- if seg >= 0:
553
- out["seg"] = {"title": X["title"][seg], "sec": X["sec"][seg], "ref": refs(seg)[0], "cls": int(X["cls"][seg])}
554
- near = [x for x in X["rtxt"][:] if x.startswith(r.split(":")[0] + ":")][:5]
555
- out["near"] = near
556
- return out
 
197
  X["en"] = en
198
 
199
  S["stage"] = "links"
200
+ L = {f: hf(f"card/ner/links/{f}") for f in ["refseg.idx", "links.idx", "links.dat"]}
201
  refseg = np.fromfile(L["refseg.idx"], dtype=np.uint32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  lidx = np.fromfile(L["links.idx"], dtype=np.uint32)
203
  ldat = np.fromfile(L["links.dat"], dtype=np.uint32)
204
+ # The Talmud is in the index twice under one ref, Hebrew and English
205
+ # (Chullin 59a:14 = segments 2177416 and 3356674); links reach only one.
206
+ first, twin = {}, {}
207
+ for i in range(n):
208
+ k = X["title"][i] + "\t" + X["sec"][i]
209
+ j = first.setdefault(k, i)
210
+ if j != i:
211
+ twin[i], twin[j] = j, i
212
+ X["twin"] = twin
213
+ S["twins"] = len(twin) // 2
214
+ del first
215
  src = np.repeat(np.arange(len(refseg), dtype=np.uint32), np.diff(lidx).astype(np.int64))
216
  a_, b_ = refseg[src], refseg[ldat]
217
  del src, ldat
 
294
  return en_ref, he_ref
295
 
296
 
297
+ def has_he(t):
298
+ return any("\u05d0" <= c <= "\u05ea" for c in t[:200])
299
+
300
+
301
+ def text_pair(s, cap=None):
302
+ """(Hebrew, English) for a segment, taking whichever twin holds which."""
303
+ t, e = text(s, cap), english(s, cap)
304
+ tw = X["twin"].get(s)
305
+ if tw is not None:
306
+ t2 = text(tw, cap)
307
+ if has_he(t2) and not has_he(t):
308
+ t, e = t2, e or t
309
+ elif has_he(t) and not e:
310
+ e = english(tw, cap) or (t2 if not has_he(t2) else "")
311
+ if not has_he(t) and not e:
312
+ t, e = "", t
313
+ if e == t:
314
+ e = ""
315
+ return t, e
316
+
317
+
318
  def text(s, cap=None):
319
  a, b = int(X["snip_idx"][s]), int(X["snip_idx"][s + 1])
320
  if cap:
 
334
  c = int(X["cls"][s])
335
  return {"seg": int(s), "ref": en_ref, "he": he_ref, "shelf": SHELVES[c & 0x0F] if (c & 0x0F) < 8 else "Other",
336
  "primary": bool(c & 0x10), "tag": tag, "score": None if score is None else round(float(score), 3),
337
+ **dict(zip(("text", "en"), text_pair(s, cap)))}
338
 
339
 
340
  # ---- meaning ------------------------------------------------------------------------------------------
 
428
  if key in seen:
429
  continue
430
  seen.add(s); seen.add(key)
431
+ if s in X["twin"]:
432
+ seen.add(X["twin"][s])
433
  per_work[t] += 1
434
  out.append((s, sc))
435
  if len(out) >= limit:
 
519
  ctx = sorted(range(lo, hi), key=lambda s: [int(p) if p.isdigit() else 0 for p in X["sec"][s].split(".") if p])
520
  links, comments, similar = [], [], []
521
  linked = X["ldst"][X["lptr"][seg]:X["lptr"][seg + 1]].astype(np.int64)
522
+ tw = X["twin"].get(seg)
523
+ if tw is not None:
524
+ linked = np.unique(np.concatenate([linked, X["ldst"][X["lptr"][tw]:X["lptr"][tw + 1]].astype(np.int64)]))
525
  # commentaries on this passage, then everything else it links to, primary sources first
526
  for t in sorted(linked.tolist(), key=lambda t: (not (X["cls"][t] & 0x10), int(X["cls"][t]) & 0x0F, t))[:400]:
527
  title = X["title"][t]
 
535
  have = set(linked.tolist())
536
  for r in X["rel"][seg]:
537
  t = int(r["seg"])
538
+ if t != NONE and t < X["n"] and t not in have and X["title"][t] != X["title"][seg] and len(similar) < 8:
539
  similar.append(item(t, "similar", cap=160))
540
  en_ref, he_ref = refs(seg)
541
  return {"seg": seg, "ref": en_ref, "he": he_ref, "title": X["title"][seg], "heTitle": X["he"].get(X["title"][seg], X["title"][seg]),
542
  "shelf": item(seg, "")["shelf"],
543
+ "context": [{"seg": s, "focus": s == seg, "ref": refs(s)[0], **dict(zip(("text", "en"), text_pair(s)))} for s in ctx],
544
  "comments": comments, "links": links, "similar": similar[:8]}
545
 
546
 
 
548
  def root():
549
  return {"ok": True, "see": "/api/status"}
550