quran-md-data / scripts /ingest_commentary.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
7.09 kB
#!/usr/bin/env python3
"""
Phase 3/4: build commentary_unit records from stored Arabic tafsir raw files.
Pipeline per source work:
raw API response (json, sha256 recorded) <- provenance substrate
-> deterministic HTML strip -> plain text file (sha256) <- quote substrate
-> commentary_unit records with quote_ar as VERBATIM substring of the
plain-text file (verify.py G2 enforces)
Ayah citations inside the mufassir's text are detected deterministically:
an ayah counts as cited when a distinctive folded fragment of its stored
Tanzil text appears in the mufassir's text. Matching is computed only from
stored texts (no recall).
"""
import json
import re
from hashlib import sha256
from pathlib import Path
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
SOURCES_DIR = RAW_DIR / "sources"
DATA_DIR = ROOT / "data"
WORKS = {
"tafsir_tabari": {"id": "tafsir_tabari", "author": "Muhammad ibn Jarir al-Tabari (d. 310 AH)",
"title_ar": "جامع البيان عن تأويل آي القرآن", "tradition": "sunni", "api_id": 15},
"tafsir_ibn_kathir_ar": {"id": "tafsir_ibn_kathir_ar", "author": "Ibn Kathir (d. 774 AH)",
"title_ar": "تفسير القرآن العظيم", "tradition": "sunni", "api_id": 14},
"tafsir_qurtubi": {"id": "tafsir_qurtubi", "author": "al-Qurtubi (d. 671 AH)",
"title_ar": "الجامع لأحكام القرآن", "tradition": "sunni", "api_id": 90},
}
TAG_RE = re.compile(r"<[^>]+>")
WS_RE = re.compile(r"[ \t\r\f\v]+")
TASHKEEL = re.compile(r"[\u064B-\u0652\u0670\u0640]")
def fold(s: str) -> str:
"""Orthography folding for CITATION MATCHING only (never stored as quote)."""
s = TASHKEEL.sub("", s)
for a in ("أ", "إ", "آ", "ٱ", "ا"):
s = s.replace(a, "ا")
s = s.replace("ى", "ي").replace("ة", "ه")
s = re.sub(r"\s+", " ", s)
return s
def strip_html(html_text: str) -> str:
t = TAG_RE.sub(" ", html_text)
t = WS_RE.sub(" ", t)
return t.strip()
def load_tanzil_folded(path: Path) -> dict:
tree = ET.parse(path)
idx = {}
for sura in tree.getroot().iter("sura"):
si = int(sura.attrib["index"])
for aya in sura.iter("aya"):
idx[f"{si}:{int(aya.attrib['index'])}"] = fold(aya.attrib.get("text", ""))
return idx
def detect_citations(folded_text: str, tanzil_fold: dict, tanzil_fold_uth: dict) -> set:
"""Deterministic citation detection grounded in stored texts only.
- ayahs >= 25 folded chars: first-25 or middle-25 folded fragment matches
- shorter ayahs: full folded ayah text must appear
- uthmani variant consulted for long ayahs (first 30 chars)
"""
cited = set()
for ref, ayah in tanzil_fold.items():
ayah = ayah.strip()
# Letter-openers and other ultra-short ayahs (< 12 folded chars) cannot
# be matched against plain running text without false positives — a
# documented detection limit, recorded in the unit's flags.
if len(ayah) < 12:
continue
if len(ayah) >= 25:
if ayah[:25] in folded_text:
cited.add(ref)
continue
mid = ayah[len(ayah) // 2 - 12: len(ayah) // 2 + 13]
if len(mid) >= 20 and mid in folded_text:
cited.add(ref)
else:
if ayah in folded_text:
cited.add(ref)
if ref not in cited:
uth = tanzil_fold_uth.get(ref, "").strip()
if len(uth) >= 30 and uth[:30] in folded_text:
cited.add(ref)
return cited
def main():
tanzil_fold = load_tanzil_folded(SOURCES_DIR / "tanzil-quran-simple.xml")
tanzil_fold_uth = load_tanzil_folded(SOURCES_DIR / "tanzil-quran-uthmani.xml")
units = []
for work_dir, meta in WORKS.items():
text_dir = SOURCES_DIR / work_dir / "text"
text_dir.mkdir(parents=True, exist_ok=True)
for jf in sorted((SOURCES_DIR / work_dir).glob("*.json")):
if jf.name.endswith(".sha256"):
continue
raw_sha = sha256(jf.read_bytes()).hexdigest()
resp = json.loads(jf.read_text(encoding="utf-8"))
t = resp.get("tafsir", {})
html_text = t.get("text", "")
if not html_text:
continue
plain = strip_html(html_text)
out_txt = text_dir / f"{jf.stem}.txt"
out_txt.write_text(plain + "\n", encoding="utf-8")
txt_sha = sha256(out_txt.read_bytes()).hexdigest()
quote = plain[:4000]
folded_unit = fold(plain)
cited = detect_citations(folded_unit, tanzil_fold, tanzil_fold_uth)
surah, ayah = jf.stem.split("-")
span = f"{int(surah)}:{int(ayah)}"
units.append({
"id": f"cu_{meta['id']}_{int(surah)}_{int(ayah)}",
"work": meta["id"],
"work_title_ar": meta["title_ar"],
"author": meta["author"],
"tradition": meta["tradition"],
"span": {"start": span, "end": span},
"span_roles": {span: "primary"},
"section_type": "general_exegesis",
"quote_ar": quote,
"quote_location": {
"volume": "", "page": "",
"char_start": 0,
"char_end": min(4000, len(plain)),
"source_id": f"raw/sources/{work_dir}/text/{jf.stem}.txt",
"source_sha256": txt_sha,
},
"attribution_flags": ["citation_detection: short-ayah (letter-opener) citations undetectable in plain text"],
"ayah_citations": sorted(cited),
"provenance": {
"work": meta["title_ar"],
"author": meta["author"],
"edition": "text as served by api.quran.com v4 (public API), classical Arabic original",
"license": "public_domain (classical Arabic original)",
"retrieval_url": f"https://api.quran.com/api/v4/tafsirs/{meta['api_id']}/by_ayah/{span}",
"retrieval_date": "2026-11-26",
"source_sha256": raw_sha,
"raw_response_file": f"raw/sources/{work_dir}/{jf.stem}.json",
},
})
DATA_DIR.mkdir(exist_ok=True)
out = DATA_DIR / "commentary_units.jsonl"
with out.open("w", encoding="utf-8") as f:
for u in units:
f.write(json.dumps(u, ensure_ascii=False) + "\n")
n_cited = sum(len(u["ayah_citations"]) for u in units)
print(f"commentary_units: {len(units)} (quote substrate sha256 recorded for each)")
print(f"ayah citations detected: {n_cited}")
for u in units:
if u["span"]["start"] == "6:74":
print(f"6:74 -> {u['work']}: citations={u['ayah_citations'][:10]} quote_len={len(u['quote_ar'])}")
if __name__ == "__main__":
main()