quran-md-data / scripts /detect_mutashabihat.py
bravesigma's picture
fix(G5): idf_weight present on all lexical edges
4b5c805
Raw History Blame Contribute Delete
3.95 kB
#!/usr/bin/env python3
"""
Phase 3 (gap closure): parallel-phrase (mutashabihat) detection.
Deterministic, grounded only in stored Tanzil texts:
1. Fold all 6,236 ayat (diacritics stripped, alef/ya unified - matching only).
2. Build a 6-gram index over folded word sequences.
3. For every ingested verse, find partner verses sharing >=1 distinctive
6-gram; collapse overlapping grams into the longest matched phrase.
Output: data/parallel_phrases.jsonl (from, to, phrase_from, phrase_to)
build_xrefs.py consumes this to emit lexical edges with evidence
kind=parallel_phrase (relation stays null -> review queue).
"""
import json
import math
import re
from collections import defaultdict
from pathlib import Path
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
RAW_DIR = ROOT / "raw"
SOURCES = RAW_DIR / "sources"
TASHKEEL = re.compile(r"[\u064B-\u0652\u0670\u0640]")
NGRAM = 6
def fold(s):
s = TASHKEEL.sub("", s)
for a in ("أ", "إ", "آ", "ٱ", "ا"):
s = s.replace(a, "ا")
s = s.replace("ى", "ي").replace("ة", "ه")
return s
def words_of(s):
return [w for w in re.sub(r"\s+", " ", fold(s)).strip().split(" ") if w]
def main():
tree = ET.parse(SOURCES / "tanzil-quran-simple.xml")
ayat = {}
for sura in tree.getroot().iter("sura"):
si = int(sura.attrib["index"])
for aya in sura.iter("aya"):
ayat[f"{si}:{int(aya.attrib['index'])}"] = aya.attrib.get("text", "")
ingested = []
for jf in sorted(RAW_DIR.glob("*.json")):
d = json.loads(jf.read_text(encoding="utf-8"))
ingested.append(f"{d['surah_number']}:{d['ayah_number']}")
ingested_set = set(ingested)
# 6-gram index over the whole corpus
grams = defaultdict(list)
folded_texts = {}
for ref, text in ayat.items():
ws = words_of(text)
folded_texts[ref] = " ".join(ws)
for i in range(len(ws) - NGRAM + 1):
grams[" ".join(ws[i:i + NGRAM])].append(ref)
out = []
for v in ingested:
ws = words_of(ayat[v])
seen_pairs = {}
for i in range(len(ws) - NGRAM + 1):
g = " ".join(ws[i:i + NGRAM])
for other in grams.get(g, []):
if other == v or other in ingested_set:
continue
rec = seen_pairs.setdefault(other, set())
rec.add(i)
for other, idxs in seen_pairs.items():
# collapse consecutive gram windows into the longest phrase span
idxs = sorted(idxs)
spans, start, prev = [], idxs[0], idxs[0]
for i in idxs[1:]:
if i == prev + 1:
prev = i
continue
spans.append((start, prev)); start = prev = i
spans.append((start, prev))
s0, s1 = max(spans, key=lambda ab: ab[1] - ab[0])
phrase = " ".join(ws[s0:s1 + NGRAM])
# document frequency of the folded phrase over the whole corpus
# (IDF semantics identical to build_xrefs: rarity over 6,236 verses)
phrase_df = sum(1 for t in folded_texts.values() if phrase in t)
out.append({
"from": v, "to": other,
"phrase_from": ayat[v] and phrase,
"phrase_folded": phrase,
"gram": NGRAM,
"phrase_df": phrase_df,
"idf_weight": round(math.log(6236 / max(phrase_df, 1)), 3),
"spans_matched": len(spans),
})
with (DATA_DIR / "parallel_phrases.jsonl").open("w", encoding="utf-8") as f:
for r in out:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"parallel_phrases: {len(out)} pairs (distinctive {NGRAM}-gram matches)")
for r in out[:5]:
print(" ", r["from"], "->", r["to"], "|", r["phrase_from"][:60])
if __name__ == "__main__":
main()