quran-md-data / scripts /ingest_morphology.py
Z User
phase3-6 continued: NOTICE.md + DATASET_CARD.md (attribution compliance); mutashabihat detector (71 pairs) wired into graph (23,521 edges); KB expanded to 192 verses (Surah 19+60 complete, Ibrahim blocks 2:124-141, 6:74-90) with 576 commentary units + 1,662 citations; surah names + page numbers backfilled from API with provenance; probe expanded (2 real / 3 labeled fake); PERMISSION_REQUESTS.md drafts
cbbb668
Raw History Blame Contribute Delete
9.38 kB
#!/usr/bin/env python3
"""
Phase 2: deterministic morphology ingestion for quran.md.
Parses the official Quranic Arabic Corpus v0.4 morphology file
(quranic-corpus-morphology-0.4.txt, verbatim copy stored in raw/sources/),
groups segments into words, converts Buckwalter -> Arabic, and produces:
data/words.jsonl one word record per corpus word (s:a:w)
data/roots.json root -> [{ref, lemma, form}] index
data/lemma_index.json lemma -> [ref] index
NO LLM involved. Root/lemma claims produced here are `corpus_verified` by
construction and carry source_id + source_sha256 provenance.
Also updates raw/*.json verse files: attaches `words` (refs) and adds
corpus-verified roots[] entries, without touching or discarding any
existing curated content (which stays flagged `unverified_recall`).
"""
import json
import re
import sys
from collections import defaultdict
from hashlib import sha256
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
SRC_FILE = RAW_DIR / "sources" / "quranic-corpus-morphology-0.4.txt"
TANZIL_FILE = RAW_DIR / "sources" / "tanzil-quran-simple.xml"
UTHMANI_FILE = RAW_DIR / "sources" / "tanzil-quran-uthmani.xml"
DATA_DIR = ROOT / "data"
# Buckwalter transliteration -> Arabic (mechanical encoding table)
BW2AR = {
"'": "ا", "|": "آ", ">": "أ", "<": "إ", "}": "ة", "&": "ؤ",
"{": "ٱ",
"b": "ب", "t": "ت", "v": "ث", "j": "ج", "H": "ح", "x": "خ",
"d": "د", "*": "ذ", "r": "ر", "z": "ز", "s": "س", "$": "ش",
"S": "ص", "D": "ض", "T": "ط", "Z": "ظ", "E": "ع", "g": "غ",
"f": "ف", "q": "ق", "k": "ك", "l": "ل", "m": "م", "n": "ن",
"h": "ه", "w": "و", "y": "ي", "A": "ا", "Y": "ى", "~": "ّ", "o": "ْ",
"u": "ُ", "a": "َ", "i": "ِ", "F": "ً", "N": "ٍ", "K": "ٌ",
"`": "ٰ", "p": "ة", "c": "ث",
}
# Buckwalter special sequence for dagger alif ligature in corpus lemmas
BW_SEQ = {"Al": "ال"} # handled by plain char map; kept for clarity
def bw2ar(s: str) -> str:
out = []
for ch in s:
out.append(BW2AR.get(ch, ch if not ch.isascii() else ch))
return "".join(out)
def clean_ar(s: str) -> str:
return s.strip()
def parse_corpus():
"""Return {ref 's:a:w': {pos, form_ar, lemma_ar, root_ar, segments:[...]}}."""
sha = sha256(SRC_FILE.read_bytes()).hexdigest()
words = {}
row_re = re.compile(r"^\((\d+:\d+:\d+:\d+)\)\t([^\t]*)\t([^\t]+)\t(.*)$")
skipped = 0
for line in SRC_FILE.read_text(encoding="utf-8").splitlines():
if not line or line.startswith("#") or line.startswith("LOCATION"):
continue
m = row_re.match(line)
if not m:
skipped += 1
continue
loc, form_bw, tag, feats = m.groups()
s, a, w, seg = loc.strip("()").split(":")
wref = f"{int(s)}:{int(a)}:{int(w)}"
rec = words.setdefault(wref, {"pos": None, "form_bw": [], "lemma": None, "root": None, "segments": 0})
rec["segments"] += 1
rec["form_bw"].append(form_bw)
fdict = {}
for f in feats.split("|"):
if f == "STEM":
fdict["STEM"] = True
elif ":" in f:
k, v = f.split(":", 1)
fdict[k] = v
else:
fdict[f] = True
if fdict.get("STEM") or rec["pos"] is None:
rec["pos"] = tag
if fdict.get("LEM"):
rec["lemma"] = fdict["LEM"]
if fdict.get("ROOT"):
rec["root"] = fdict["ROOT"]
if skipped:
print(f"[warn] {skipped} rows did not match expected format")
return words, sha
def tanzil_ayah_word_counts(path=None):
"""Word counts per ayah from a Tanzil XML. QAC v0.4 is built on Uthmani text,
so alignment checks use the Uthmani file; the Simple (imla'i) file is the
canonical grounding text for quote verification."""
import xml.etree.ElementTree as ET
tree = ET.parse(path or UTHMANI_FILE)
counts = {}
for sura in tree.getroot().iter("sura"):
si = int(sura.attrib["index"])
for aya in sura.iter("aya"):
counts[f"{si}:{int(aya.attrib['index'])}"] = len(aya.attrib.get("text", "").split())
return counts
def main():
words, sha = parse_corpus()
print(f"parsed {len(words)} words from corpus")
total_segments = sum(w["segments"] for w in words.values())
print(f"total segments: {total_segments}")
recs = []
roots_idx = defaultdict(list)
lemma_idx = defaultdict(list)
for wref in sorted(words, key=lambda r: (int(r.split(":")[0]), int(r.split(":")[1]), int(r.split(":")[2]))):
w = words[wref]
form_ar = bw2ar(" ".join(w["form_bw"]))
lemma_ar = bw2ar(w["lemma"]) if w["lemma"] else ""
root_ar = bw2ar(w["root"]) if w["root"] else ""
recs.append({
"ref": wref,
"form": clean_ar(form_ar),
"lemma": clean_ar(lemma_ar),
"root": clean_ar(root_ar),
"pos": w["pos"],
"source_id": "morphology_quranic_arabic_corpus",
"source_sha256": sha,
})
if root_ar:
roots_idx[root_ar].append({"ref": wref, "lemma": clean_ar(lemma_ar), "form": clean_ar(form_ar)})
if lemma_ar:
lemma_idx[lemma_ar].append(wref)
DATA_DIR.mkdir(exist_ok=True)
MAX = 6_500_000
shards, cur, size = [], [], 0
for r in recs:
n = len(json.dumps(r, ensure_ascii=False).encode()) + 1
if size + n > MAX and cur:
shards.append(cur); cur, size = [], 0
cur.append(r); size += n
if cur:
shards.append(cur)
from hashlib import sha256 as _sha
manifest = {"format": "jsonl", "encoding": "utf-8", "records": len(recs), "parts": []}
for i, shard in enumerate(shards):
name = f"words_{i:02d}.jsonl"
pth = DATA_DIR / name
pth.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in shard) + "\n", encoding="utf-8")
manifest["parts"].append({"file": name, "records": len(shard), "sha256": _sha(pth.read_bytes()).hexdigest()})
(DATA_DIR / "words_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
(DATA_DIR / "roots.json").write_text(json.dumps(roots_idx, ensure_ascii=False, indent=0), encoding="utf-8")
(DATA_DIR / "lemma_index.json").write_text(json.dumps(lemma_idx, ensure_ascii=False), encoding="utf-8")
print(f"words shards: {len(recs)} records; roots: {len(roots_idx)} distinct; lemmas: {len(lemma_idx)} distinct")
# structural validation against Tanzil UTHMANI word counts (QAC v0.4 base text)
tanzil_counts = tanzil_ayah_word_counts(UTHMANI_FILE)
corpus_counts = defaultdict(int)
for r in recs:
s, a, _ = r["ref"].split(":")
corpus_counts[f"{s}:{a}"] += 1
mismatch = [k for k in tanzil_counts if corpus_counts.get(k) != tanzil_counts[k]]
print(f"verse word-count agreement: {len(tanzil_counts) - len(mismatch)}/{len(tanzil_counts)}")
if mismatch[:5]:
print(" sample mismatches:", mismatch[:5])
if len(recs) != 77430:
# Published literature cites 77,430 words; the v0.4 data dump contains
# 77,429 distinct word keys with no index gaps (verified 2026-11-26).
print(f"[note] published figure is 77,430 words; v0.4 dump has {len(recs)} distinct word keys (no index gaps; off-by-one vs published counts, recorded in provenance)")
# attach corpus morphology to ingested raw verse files (additive)
by_verse = defaultdict(list)
for r in recs:
s, a, _ = r["ref"].split(":")
by_verse[f"{s}:{a}"].append(r)
updated = 0
for jf in sorted(RAW_DIR.glob("*.json")):
v = json.loads(jf.read_text(encoding="utf-8"))
s, a = str(v["surah_number"]), str(v["ayah_number"])
wrefs = by_verse.get(f"{s}:{a}", [])
if not wrefs:
continue
v["words"] = [w["ref"] for w in wrefs]
prov = v.setdefault("provenance", {})
prov["words"] = {
"source_id": "morphology_quranic_arabic_corpus",
"source_sha256": sha,
"retrieval_url": "https://github.com/cltk/arabic_morphology_quranic-corpus (verbatim copy of http://corpus.quran.com/download)",
"retrieval_date": "2026-11-26",
"verification": "corpus_verified",
}
# add corpus-verified roots entries without touching curated roots[]
existing = {r.get("root") for r in v.get("roots", [])}
seen_roots = set()
for w in wrefs:
if w["root"] and w["root"] not in seen_roots:
seen_roots.add(w["root"])
if w["root"] not in existing:
v.setdefault("roots", []).append({
"word_ar": w["form"],
"transliteration": "",
"root": w["root"],
"meaning": "",
"internal_quranic_crossrefs": [],
"verification": "corpus_verified",
"lemma": w["lemma"],
"ref": w["ref"],
})
jf.write_text(json.dumps(v, ensure_ascii=False, indent=2), encoding="utf-8")
updated += 1
print(f"updated {updated} raw verse files with corpus morphology")
if __name__ == "__main__":
sys.exit(main())