Download scripts/backfill_idf_weight.py from bravesigma/quran-md-data: direct link, hf CLI and curl.
- Browser
- Download file 4.15 kB
-
https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main/scripts/backfill_idf_weight.py
- Command line
-
hf download hf://datasets/bravesigma/quran-md-data/scripts/backfill_idf_weight.py
-
curl -L -o backfill_idf_weight.py https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main/scripts/backfill_idf_weight.py
4.15 kB
| #!/usr/bin/env python3 | |
| """ | |
| One-off repair: backfill idf_weight onto lexical xref edges that were emitted | |
| by generators predating the G5 idf_weight advisory. | |
| Covers exactly two producer gaps (fixed in their generators, kept here for the | |
| already-written graph): | |
| 1. evidence.kind == "parallel_phrase" (build_xrefs.py < fix): | |
| phrase_df = # verses whose folded Tanzil-simple text contains the | |
| folded phrase (fold identical to detect_mutashabihat.fold) | |
| idf_weight = ln(6236 / phrase_df) (same IDF semantics as build_xrefs) | |
| 2. evidence.kind == "llm_review" on a lexical edge (classify_xrefs.py < fix): | |
| rarest shared lemma of the verse pair (df over words_[0-9]*.jsonl), | |
| idf_weight = ln(6236 / df) + 2.0 (build_xrefs shared_lemma formula) | |
| evidence.shared_lemma is recorded for self-description. | |
| Surgical: lines that need no change are copied through byte-identical; only | |
| the deficient lines are re-serialized. Nothing is deleted or re-ranked. | |
| """ | |
| import json | |
| import math | |
| import sys | |
| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from detect_mutashabihat import fold # identical folding, matching only | |
| ROOT = Path(__file__).resolve().parent.parent | |
| DATA_DIR = ROOT / "data" | |
| SOURCES = ROOT / "raw" / "sources" | |
| N_DOCS = 6236 | |
| def main(): | |
| # folded corpus | |
| tree = ET.parse(SOURCES / "tanzil-quran-simple.xml") | |
| folded_texts = {} | |
| for sura in tree.getroot().iter("sura"): | |
| si = int(sura.attrib["index"]) | |
| for aya in sura.iter("aya"): | |
| ref = f"{si}:{int(aya.attrib['index'])}" | |
| ws = [w for w in " ".join(fold(aya.attrib.get("text", "")).split()).split(" ") if w] | |
| folded_texts[ref] = " ".join(ws) | |
| # lemma document frequencies from the morphology corpus | |
| df_lemma, verse_lemmas = {}, {} | |
| for wf in sorted(DATA_DIR.glob("words_[0-9]*.jsonl")): | |
| for line in wf.open(encoding="utf-8"): | |
| w = json.loads(line) | |
| s, a, _ = w["ref"].split(":") | |
| v = f"{s}:{a}" | |
| lem = w.get("lemma") | |
| if lem: | |
| df_lemma.setdefault(lem, set()).add(v) | |
| verse_lemmas.setdefault(v, set()).add(lem) | |
| src = DATA_DIR / "xref_edges.jsonl" | |
| out_lines = [] | |
| n_pp = n_llm = n_untouched = 0 | |
| for raw in src.open(encoding="utf-8"): | |
| e = json.loads(raw) | |
| if e.get("source") == "lexical" and not e.get("evidence", {}).get("idf_weight"): | |
| ev = e["evidence"] | |
| kind = ev.get("kind") | |
| if kind == "parallel_phrase": | |
| phrase = ev["phrase_folded"] | |
| df = sum(1 for t in folded_texts.values() if phrase in t) | |
| ev["phrase_df"] = df | |
| ev["idf_weight"] = round(math.log(N_DOCS / max(df, 1)), 3) | |
| n_pp += 1 | |
| out_lines.append(json.dumps(e, ensure_ascii=False) + "\n") | |
| elif kind == "llm_review": | |
| shared = verse_lemmas.get(e["from"], set()) & verse_lemmas.get(e["to"], set()) | |
| if not shared: | |
| print(f" !! no shared lemma for {e['from']}->{e['to']}; left untouched", file=sys.stderr) | |
| out_lines.append(raw) | |
| n_untouched += 1 | |
| continue | |
| lem = min(shared, key=lambda l: len(df_lemma[l])) | |
| ev["shared_lemma"] = lem | |
| ev["idf_weight"] = round(math.log(N_DOCS / max(len(df_lemma[lem]), 1)) + 2.0, 3) | |
| n_llm += 1 | |
| out_lines.append(json.dumps(e, ensure_ascii=False) + "\n") | |
| else: | |
| print(f" !! unexpected lexical kind {kind!r}; left untouched", file=sys.stderr) | |
| out_lines.append(raw) | |
| n_untouched += 1 | |
| else: | |
| out_lines.append(raw) | |
| with src.open("w", encoding="utf-8") as f: | |
| f.writelines(out_lines) | |
| print(f"backfilled parallel_phrase edges: {n_pp}") | |
| print(f"backfilled llm_review lexical edges: {n_llm}") | |
| print(f"left untouched: {n_untouched}") | |
| if __name__ == "__main__": | |
| main() | |