File size: 4,151 Bytes
4b5c805 | 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 | #!/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()
|