KesherBench / fetch_unknown_texts.py
ai-arie's picture
Initial release
d59e915
Raw History Blame Contribute Delete
3.22 kB
"""Fill in the KesherBench texts whose Sefaria license is "unknown" from Sefaria's public export.
These texts are not redistributed here (their copyright status is not settled). Their rows keep `id` and `license` with
`text` empty; unknown_texts.parquet says which Sefaria version each comes from. This script downloads those versions from
Sefaria's export, cuts them into segments with the benchmark's own code, and checks every text against `text_sha1`
(a mismatch means Sefaria has edited the text since 2026-10-29; the current text is filled in and counted).
usage: python fetch_unknown_texts.py [--cache DIR] [--local EXPORT_DIR]
needs: polars, requests and the ein-mishpat-ai package (pip install git+https://github.com/ai-arie/ein-mishpat-ai)
"""
import argparse
import hashlib
import json
from pathlib import Path
from urllib.parse import quote
import polars as pl
import requests
from ein_mishpat_ai.data.normalize import clean, plain_hebrew
from ein_mishpat_ai.data.refs import walk_version
BASE = "https://storage.googleapis.com/sefaria-export/"
ap = argparse.ArgumentParser()
ap.add_argument("--cache", default=".sefaria_cache", help="where downloaded Sefaria files are kept")
ap.add_argument("--local", default=None, help="a local copy of the Sefaria export instead of downloading")
a = ap.parse_args()
def get(rel: str) -> dict:
if a.local:
return json.loads((Path(a.local) / rel).read_bytes())
f = Path(a.cache) / rel
if not f.exists():
f.parent.mkdir(parents=True, exist_ok=True)
r = requests.get(BASE + quote(rel), timeout=300)
r.raise_for_status()
f.write_bytes(r.content)
return json.loads(f.read_bytes())
man = pl.read_parquet("unknown_texts.parquet")
texts: dict[tuple[str, str], str] = {}
groups = man.group_by("path", "title", "lang", maintain_order=True)
for n, ((path, title, lang), g) in enumerate(groups, 1):
want = set(g["id"].to_list())
schema = get("schemas/" + title.replace(" ", "_") + ".json")["schema"]
seen: set[str] = set()
for _node, ref, _addr, raw in walk_version(title, schema, get(path)["text"]):
c = clean(raw)
if not c or ref in seen: # same rule as the benchmark build: the first non-empty segment of a ref
continue
seen.add(ref)
if ref in want:
texts[(ref, lang)] = plain_hebrew(c) if lang == "he" else c
print(f"[{n}] {title} ({lang}): {len(want & seen)}/{len(want)}", flush=True)
for rel, g in man.group_by("file", maintain_order=True):
rel = rel[0]
df = pl.read_parquet(rel)
sha = dict(zip(g["id"].to_list(), g["text_sha1"].to_list(), strict=True))
lang = g["lang"][0]
new = [texts.get((i, lang)) if t is None and i in sha else t for i, t in zip(df["id"].to_list(), df["text"].to_list(), strict=True)]
same = sum(hashlib.sha1(new[k].encode()).hexdigest() == sha[i] for k, i in enumerate(df["id"].to_list()) if i in sha and new[k])
missing = sum(1 for k, i in enumerate(df["id"].to_list()) if i in sha and not new[k])
df.with_columns(pl.Series("text", new, dtype=pl.String)).write_parquet(rel)
print(f"{rel}: {len(sha)} filled, {same} identical to the benchmark version, {missing} not found")