quran-md-data / scripts /build_xrefs.py
bravesigma's picture
fix(G5): idf_weight present on all lexical edges
4b5c805
Raw History Blame Contribute Delete
7.08 kB
#!/usr/bin/env python3
"""
Phase 3: cross-reference graph builder.
Lexical edges (deterministic): shared root / shared lemma between an ingested
verse and any corpus verse, IDF-weighted over the 6,236-verse corpus so very
common roots are suppressed. relation stays null and review_status='queue' —
the LLM classifier (run separately, from supplied verse text + evidence only)
assigns relation from the closed set; human review follows.
Exegetical edges (deterministic): from commentary_units.ayah_citations
(detected verbatim from stored tafsir text) with citing_mufassir.
Output: data/xref_edges.jsonl
"""
import gzip
import json
import math
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
IDF_MIN = 4.0 # suppress very common roots (df > ~115)
TOP_K_PER_VERSE = 15
N_DOCS = 6236
def main():
words = []
for wf in sorted(DATA_DIR.glob("words_[0-9]*.jsonl")):
words.extend(json.loads(l) for l in wf.open(encoding="utf-8"))
units = [json.loads(l) for l in (DATA_DIR / "commentary_units.jsonl").open(encoding="utf-8")]
# document frequency per root / lemma
df_root = defaultdict(set)
df_lemma = defaultdict(set)
word_by_ref = {}
for w in words:
word_by_ref[w["ref"]] = w
s, a, _ = w["ref"].split(":")
v = f"{s}:{a}"
if w.get("root"):
df_root[w["root"]].add(v)
if w.get("lemma"):
df_lemma[w["lemma"]].add(v)
def idf(df_count):
return math.log(N_DOCS / max(df_count, 1))
ingested = []
for f in sorted((ROOT / "raw").glob("*.json")):
d = json.loads(f.read_text(encoding="utf-8"))
ingested.append(f"{d['surah_number']}:{d['ayah_number']}")
ingested_set = set(ingested)
# verse -> words
verse_words = defaultdict(list)
for w in words:
s, a, _ = w["ref"].split(":")
verse_words[f"{s}:{a}"].append(w)
edges = []
seen = set()
# --- lexical edges ---
# (a) ALL pairs among ingested verses with any shared root/lemma — the core
# knowledge-base graph; no IDF cap here (weight itself records rarity).
# (b) ingested verse -> corpus verse: IDF-filtered top-K discovery edges.
for v in ingested:
cands = {}
for w in verse_words.get(v, []):
if w.get("lemma") and len(df_lemma[w["lemma"]]) <= 60:
for other in df_lemma[w["lemma"]]:
if other == v:
continue
key = (v, other, "shared_lemma", w["lemma"])
score = idf(len(df_lemma[w["lemma"]])) + 2.0
if score > cands.get(key, (0,))[0]:
cands[key] = (score, {"kind": "shared_lemma", "shared_lemma": w["lemma"], "idf_weight": round(score, 3), "form_ref": w["ref"]})
if w.get("root"):
for other in df_root[w["root"]]:
if other == v:
continue
ingested_target = other in ingested_set
# corpus discovery edges need rarity (IDF_MIN); ingested<->ingested
# edges keep ALL shared roots — the closed set is small and the
# usage-split analysis needs even common roots like ابو
if not ingested_target and idf(len(df_root[w["root"]])) < IDF_MIN:
continue
key = (v, other, "shared_root", w["root"])
score = idf(len(df_root[w["root"]]))
if score > cands.get(key, (0,))[0]:
cands[key] = (score, {"kind": "shared_root", "shared_root": w["root"], "idf_weight": round(score, 3), "form_ref": w["ref"]})
# split: ingested->ingested (all, no cap) vs ingested->corpus (top-K)
ranked = sorted(cands.items(), key=lambda kv: -kv[1][0])
for (v_from, v_to, kind, shared), (score, ev) in ranked:
if v_to not in ingested_set:
# corpus discovery edge: cap per verse
k_count = sum(1 for e in edges if e["from"] == v_from and e["source"] == "lexical" and e["to"] not in ingested_set)
if k_count >= TOP_K_PER_VERSE:
continue
ekey = (v_from, v_to, kind, shared)
if ekey in seen:
continue
seen.add(ekey)
edges.append({
"from": v_from,
"to": v_to,
"source": "lexical",
"relation": None,
"evidence": ev,
"confidence": min(1.0, round(score / 9.0, 3)),
"human_reviewed": False,
"review_status": "queue",
})
# --- parallel-phrase (mutashabihat) edges ---
pp_file = DATA_DIR / "parallel_phrases.jsonl"
if pp_file.exists():
for r in [json.loads(l) for l in pp_file.open(encoding="utf-8")]:
edges.append({
"from": r["from"],
"to": r["to"],
"source": "lexical",
"relation": None,
"evidence": {
"kind": "parallel_phrase",
"phrase_folded": r["phrase_folded"],
"gram": r["gram"],
"phrase_df": r["phrase_df"],
"idf_weight": r["idf_weight"],
},
"confidence": 0.9,
"human_reviewed": False,
"review_status": "queue",
})
# --- exegetical edges ---
for u in units:
v_from = u["span"]["start"]
for ref in u.get("ayah_citations", []):
if ref == v_from:
continue
edges.append({
"from": v_from,
"to": ref,
"source": "exegetical",
"relation": None,
"evidence": {
"kind": "tafsir_citation",
"commentary_unit_id": u["id"],
},
"citing_mufassir": u["work"],
"confidence": 0.9,
"human_reviewed": False,
"review_status": "queue",
})
with (DATA_DIR / "xref_edges.jsonl").open("w", encoding="utf-8") as f:
for e in edges:
f.write(json.dumps(e, ensure_ascii=False) + "\n")
n_lex = sum(1 for e in edges if e["source"] == "lexical")
n_ex = sum(1 for e in edges if e["source"] == "exegetical")
print(f"xref_edges: {len(edges)} (lexical {n_lex}, exegetical {n_ex}) all queued for review")
for e in edges:
if e["from"] == "6:74" and e["source"] == "exegetical":
print(" 6:74 exegetical ->", e["to"], "via", e["citing_mufassir"])
for e in edges:
if e["from"] == "6:74" and e["evidence"].get("kind") == "shared_lemma" and e["evidence"].get("shared_lemma", "").startswith(("أب", "اب", "اٍب")):
print(" 6:74 lemma edge ->", e["to"], e["evidence"])
if __name__ == "__main__":
main()