File size: 7,080 Bytes
1e02da8 21b1447 1e02da8 e1b60ee 1e02da8 cbbb668 4b5c805 cbbb668 1e02da8 | 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | #!/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()
|