quran-md-data / scripts /fetch_qummi_eshia.py
Z User
phase4b: Tafsir al-Qummi ingested - Imami layer now two works deep (898 units)
e046739
Raw History Blame Contribute Delete
23.4 kB
#!/usr/bin/env python3
"""
Phase 4b (Imami gap closure, source 2): fetch Tafsir al-Qummi (Ali ibn
Ibrahim al-Qummi, d. 307 AH) Arabic text from the digital library of
Madrasat al-Fiqahah (ar.lib.eshia.ir), Najaf: Maktabat al-Huda 1387/1967
edition (ed. Sayyid Tayyib al-Musawi al-Jaza'iri), and extract per-verse
commentary segments for the already-ingested verse set.
Same determinism rules as fetch_majma_eshia.py:
- NO recall: every verse segment is anchored by a quote whose folded text
matches the stored Tanzil verse text (pure string matching).
- Raw page HTML is stored per page with sha256; normalized substrate text
files are stored per surah and per verse; G2 verifies quotes verbatim
against the per-verse files.
- Normalization applied to substrate: remove bidi/ZWNJ/ZWJ control chars,
collapse runs of whitespace. Diacritics and edition punctuation are kept
verbatim.
Qummi-specific notes:
- Early hadith-based tafsir: discussion frequently covers verse RANGES and
sometimes skips verses entirely. Page spans come from the EDITION'S OWN
TOC (eshia serves the complete pericope TOC as out-of-range digital
pages: vol 1 -> page 400, vol 2 -> page 457). Verses with no pericope in
the TOC are reported as uncovered and produce NO unit (never guessed).
- Quranic quotes in the Najaf edition may appear without «» marks; the
anchor matcher therefore ALSO accepts bare >=25-char folded verse
fragments found contiguously in the substrate (folded coordinates are
mapped back to raw coordinates via fold_with_map).
Usage:
fetch_qummi_eshia.py probe V P # inspect one page (debug)
fetch_qummi_eshia.py toc # fetch + parse both TOCs, show map
fetch_qummi_eshia.py plan # show per-surah fetch spans + coverage
fetch_qummi_eshia.py fetch # fetch spans + build substrate + report
fetch_qummi_eshia.py rebuild # rebuild from cached pages only
"""
import json
import re
import sys
import time
import urllib.request
import xml.etree.ElementTree as ET
from hashlib import sha256
from pathlib import Path
from bs4 import BeautifulSoup
ROOT = Path(__file__).resolve().parent.parent
WORK = "tafsir_al_qummi"
OUT = ROOT / "raw" / "sources" / WORK
PAGES = OUT / "pages"
TEXT = OUT / "text"
BOOK = 12015
BASE = f"https://ar.lib.eshia.ir/{BOOK}"
UA = {"User-Agent": "Mozilla/5.0 (compatible; quran-md-research/0.1; academic verbatim-extraction pipeline)"}
SLEEP = 0.65
# eshia serves the complete edition TOC on these out-of-range page ids
TOC_PAGES = {1: 400, 2: 457}
# content page bounds per volume (excludes the appended TOC pages)
VOL_PAGES = {1: (1, 396), 2: (1, 452)}
TASHKEEL = re.compile(r"[\u064B-\u0652\u0670\u0640]")
QMARKS = re.compile(r"[\u06D6-\u06ED\u08A0-\u08FF\u08D3-\u08FF]")
CTRL = re.compile(r"[\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]")
JUNK = re.compile(r"جستجوی سریع.*?اعراب گذاری", re.DOTALL)
BRACKETS = "«»﴿﴾()[]{}<>\"'.,:;!?؟،؛…ـ"
PERICOPE_RE = re.compile(r"\[سورة\s+[^(\]]+\((\d+)\):\s+([^]]+)\]\s+(\d{1,3})")
VRANGE_RE = re.compile(r"الآيات\s+(\d{1,3})\s+الى\s+(\d{1,3})")
VONE_RE = re.compile(r"آية\s+(\d{1,3})")
def http_get(url: str, retries: int = 3) -> str:
for k in range(retries):
try:
req = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(req, timeout=30) as r:
return r.read().decode("utf-8", errors="replace")
except Exception:
if k == retries - 1:
raise
time.sleep(1.5 * (k + 1))
return ""
def normalize(s: str) -> str:
s = CTRL.sub("", s)
s = re.sub(r"\s+", " ", s)
return s.strip()
def page_url(v: int, p: int) -> str:
return f"{BASE}/{v}/{p}"
def html_to_text(html: str) -> str:
"""Same v2 extraction as Majma: fence to td#book-page-content, drop
sticky-menue tool chrome, strip the leading printed page number."""
soup = BeautifulSoup(html, "html.parser")
content = soup.find("td", id="book-page-content")
if content is None:
t = soup.get_text()
i = t.find("اسم الکتاب")
if i < 0:
return ""
j = t.find("اسم الکتاب", i + 10)
seg = t[i:j] if j > 0 else t[i:]
return normalize(JUNK.sub(" ", seg))
for junk in content.find_all(class_="sticky-menue"):
junk.decompose()
seg = content.get_text(" ", strip=True)
seg = re.sub(r"^\d{1,4}\s+", "", seg) # eshia prints the page number first
return normalize(JUNK.sub(" ", seg))
def page_text(v: int, p: int) -> str:
return html_to_text(fetch_page_cached(v, p))
def mfold(s: str) -> str:
"""Aggressive folding for MATCHING ONLY (never stored)."""
s = TASHKEEL.sub("", s)
s = QMARKS.sub("", s)
s = CTRL.sub("", s)
for ch in BRACKETS:
s = s.replace(ch, " ")
for a in ("أ", "إ", "آ", "ٱ", "ا"):
s = s.replace(a, "ا")
s = s.replace("ى", "ي").replace("ة", "ه")
s = re.sub(r"\s+", " ", s)
return s.strip()
def fold_with_map(s: str) -> tuple:
"""Fold exactly like mfold() but return (folded, imap) where imap[j] is
the index in the ORIGINAL string of the source char of folded char j.
Required so bare-fragment anchors found in folded coordinates can be
mapped back to raw-blob coordinates for segmentation."""
out = []
imap = []
last_ws = True # suppress leading whitespace (matches mfold strip)
for i, ch in enumerate(s):
if TASHKEEL.match(ch) or QMARKS.match(ch) or CTRL.match(ch):
continue
if ch in BRACKETS:
ch2 = " "
elif ch in ("أ", "إ", "آ", "ٱ"):
ch2 = "ا"
elif ch == "ى":
ch2 = "ي"
elif ch == "ة":
ch2 = "ه"
else:
ch2 = ch
if ch2.isspace():
if last_ws:
continue
last_ws = True
ch2 = " "
else:
last_ws = False
out.append(ch2)
imap.append(i)
folded = "".join(out).strip()
if folded != mfold(s):
raise AssertionError("fold_with_map disagrees with mfold")
drop = len(out) - len(folded) # trailing whitespace stripped
return folded, imap[:len(imap) - drop] if drop else imap
LOOSE_MAP = str.maketrans({"ئ": "ا", "ؤ": "و", "ء": "ا"})
def nsfold(s: str, loose: bool = False) -> str:
"""Nospace fold for MATCHING ONLY: fold, then drop all whitespace and
digits. Digits are Najaf-edition inline footnote markers (never part of
a Quranic verse); whitespace placement diverges between the edition and
Tanzil (e.g. "و يرث" vs "ويرث"). loose=True additionally normalizes
hamza carriers (ئ/ؤ/ء), catching يسئلون vs يسألون class divergences."""
f, _ = fold_with_map(s)
ns = "".join(c for c in f if not c.isspace() and not c.isdigit())
if loose:
ns = ns.translate(LOOSE_MAP)
return ns
def tanzil_index() -> dict:
tree = ET.parse(ROOT / "raw" / "sources" / "tanzil-quran-simple.xml")
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'])}"] = mfold(aya.attrib.get("text", ""))
return idx
QUOTE_RE = re.compile(r"[«﴿]([^«»﴿﴾]{6,400})[»﴾]")
def match_refs(text: str, tz: dict) -> dict:
"""All verse refs whose text appears on this page (string matching only).
Bracketed quotes AND bare >=25-char folded fragments both count; used by
the debug probe."""
out = {}
candidates = []
for m in QUOTE_RE.finditer(text):
candidates.append((mfold(m.group(1)), m.start()))
flat = mfold(text)
for ref, ay in tz.items():
if len(ay) >= 25 and ay in flat:
candidates.append((ay, flat.find(ay)))
for q, pos in candidates:
if len(q) < 6:
continue
best = None
for ref, ay in tz.items():
if ay in q:
ratio = len(ay) / len(q)
if best is None or ratio > best[1]:
best = (ref, ratio)
elif q in ay and len(q) >= 10:
if best is None or best[1] < 1.0:
best = (ref, 1.0)
elif len(q) >= 25 and q[:25] in ay:
if best is None or best[1] < 1.0:
best = (ref, 1.0)
if best and best[1] >= 0.55:
s, a = best[0].split(":")
key = (int(s), int(a))
if key not in out or out[key][1] < best[1]:
out[key] = (q, best[1], pos)
return out
def probe(v: int, p: int, tz: dict) -> dict:
text = page_text(v, p)
refs = match_refs(text, tz)
maxref = max(refs.keys()) if refs else None
return {"vol": v, "page": p, "bytes": len(text), "n_refs": len(refs),
"refs": sorted(refs.keys()), "max_ref": maxref, "text": text}
# ---------------------------------------------------------------- TOC parsing
def fetch_toc(vol: int) -> str:
return page_text(vol, TOC_PAGES[vol])
def parse_toc(text: str, vol: int) -> list:
"""TOC text -> pericope entries (surah, a, b, page, vol)."""
out = []
for m in PERICOPE_RE.finditer(text):
s = int(m.group(1))
rng = m.group(2)
page = int(m.group(3))
mv = VRANGE_RE.search(rng)
if mv:
a, b = int(mv.group(1)), int(mv.group(2))
else:
mv2 = VONE_RE.search(rng)
if not mv2:
continue
a = b = int(mv2.group(1))
if b >= a and page >= 1:
out.append({"surah": s, "a": a, "b": b, "page": page, "vol": vol})
return out
def load_pericopes(cache_only: bool = False) -> list:
tocs = []
for vol, tp in sorted(TOC_PAGES.items()):
pf = PAGES / f"{vol}_{tp:03d}.html"
if cache_only and not (pf.exists() and pf.stat().st_size > 12000):
raise SystemExit(f"toc page missing from cache: {pf.name}")
text = fetch_toc(vol)
parsed = parse_toc(text, vol)
if not parsed:
raise SystemExit(f"TOC parse produced 0 pericopes for vol {vol}")
tocs.extend(parsed)
surahs = sorted(set(pc["surah"] for pc in tocs))
print(f"TOC parsed: {len(tocs)} pericopes, surahs {surahs[0]}..{surahs[-1]} "
f"({len(surahs)} surahs)")
return tocs
# ingested verses per surah (from raw/*.json), resolved at fetch time
def ingested_targets() -> dict:
targets = {}
for jf in (ROOT / "raw").glob("*.json"):
d = json.loads(jf.read_text(encoding="utf-8"))
s, a = int(d["surah_number"]), int(d["ayah_number"])
targets.setdefault(s, []).append(a)
return {s: sorted(ay) for s, ay in targets.items()}
def compute_plan(pericopes: list, targets: dict) -> dict:
"""Plan per-surah fetch spans from the TOC pericope map.
Returns {surah: {"vol", "lo", "hi", "pages", "missing_verses", "covered_verses"}}.
A verse with no TOC pericope is genuinely uncovered by this work: it is
listed in missing_verses and gets NO unit.
"""
plan = {}
all_pages = sorted(set((pc["page"], pc["vol"]) for pc in pericopes))
for S, ayat in sorted(targets.items()):
covered, missing = [], []
for v in ayat:
hit = [pc for pc in pericopes
if pc["surah"] == S and pc["a"] <= v <= pc["b"]]
if hit:
covered.append(min(hit, key=lambda pc: pc["page"]))
else:
missing.append(v)
if not covered:
plan[S] = {"vol": None, "lo": None, "hi": None, "pages": [],
"missing_verses": missing, "covered_verses": []}
continue
vol = covered[0]["vol"]
lo = min(pc["page"] for pc in covered)
hi = max(pc["page"] for pc in covered)
# end bound: next pericope page strictly after hi (any surah, same vol).
# No hi+2 cap: wide pericopes (e.g. Tawbah 37-118 @ p.290) legitimately
# span many pages up to the next pericope.
nxt = [p for (p, vv) in all_pages if vv == vol and p > hi]
end = (min(nxt) - 1) if nxt else VOL_PAGES[vol][1]
if end < hi: # next pericope starts on the same page: keep fetching
end = hi
end = min(end, VOL_PAGES[vol][1]) # bound by volume content pages
plan[S] = {"vol": vol, "lo": lo, "hi": max(lo, end),
"missing_verses": missing,
"covered_verses": [v for v in ayat if v not in missing]}
return plan
# ---------------------------------------------------------------- substrate
def fetch_page_cached(v: int, p: int) -> str:
PAGES.mkdir(parents=True, exist_ok=True)
f = PAGES / f"{v}_{p:03d}.html"
if f.exists() and f.stat().st_size > 12000:
return f.read_text(encoding="utf-8", errors="replace")
html = http_get(page_url(v, p))
if len(html) > 12000:
f.write_text(html, encoding="utf-8")
time.sleep(SLEEP)
return html
def build_all(tz: dict, cache_only: bool):
targets = ingested_targets()
pericopes = load_pericopes(cache_only=cache_only)
plan = compute_plan(pericopes, targets)
(OUT / "fetch_plan.json").write_text(
json.dumps(plan, ensure_ascii=False, indent=1), encoding="utf-8")
PAGES.mkdir(parents=True, exist_ok=True)
TEXT.mkdir(parents=True, exist_ok=True)
report = {"surahs": {}, "pages": {}, "uncovered_verses": {}}
for S, sp in sorted(plan.items()):
if sp["vol"] is None:
report["uncovered_verses"][str(S)] = sp["missing_verses"]
print(f"surah {S}: NOT COVERED by Qummi per TOC ({len(sp['missing_verses'])} verses) - no units")
continue
if sp["missing_verses"]:
report["uncovered_verses"][str(S)] = sp["missing_verses"]
parts = []
for p in range(sp["lo"], sp["hi"] + 1):
pf = PAGES / f"{sp['vol']}_{p:03d}.html"
if pf.exists() and pf.stat().st_size > 12000:
html = pf.read_text(encoding="utf-8", errors="replace")
elif cache_only:
raise SystemExit(f"rebuild: cached page missing {pf.name}")
else:
html = fetch_page_cached(sp["vol"], p)
if len(html) <= 12000:
continue
report["pages"][f"{sp['vol']}:{p}"] = {
"sha256": sha256(pf.read_bytes()).hexdigest(), "bytes": len(html)}
parts.append(f"### PAGE {sp['vol']}:{p}\n{page_text(sp['vol'], p)}")
blob = "\n".join(parts)
sub = TEXT / f"{S}_pages.txt"
sub.write_text(blob + "\n", encoding="utf-8")
rep = segment_surah(S, blob, targets.get(S, []), tz)
report["surahs"][str(S)] = rep
n_ok = sum(1 for vv in rep["verses"] if vv["anchored"])
n_units = sum(1 for vv in rep["verses"] if vv.get("emit"))
print(f"surah {S}: vol {sp['vol']} pages {sp['lo']}-{sp['hi']} | "
f"substrate {len(blob)} chars | anchored {n_ok}/{len(rep['verses'])} | units {n_units}")
(OUT / "extraction_report.json").write_text(
json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8")
n_unc = sum(len(v) for v in report["uncovered_verses"].values())
print(f"uncovered verses (no TOC pericope, no unit): {n_unc}")
def scan_anchors(blob: str, S: int, tz: dict) -> list:
"""All surah-S verse anchors in RAW blob coordinates:
(pos, ayah, frag_len, method). method is one of:
bracket - bracketed quote whose folded text contains the verse
ns - longest consecutive word-run matched ignoring whitespace and
digit divergence (Qummi's inline word-glosses between verse
phrases make full-verse contiguity impossible by design)
loose - ns run that additionally normalized hamza carriers
short - tiny opener verse (muqatta'ah etc.) matched as a whole word
with letter boundaries in the folded text
"""
AR_LETTER = "\u0621-\u064A\u0671-\u06D3"
out = []
tz_s = {ref: ay for ref, ay in tz.items() if ref.startswith(f"{S}:")}
for m in QUOTE_RE.finditer(blob):
q_ns = nsfold(m.group(1))
if len(q_ns) < 6:
continue
best = None # (ayah, ratio)
for ref, ay in tz_s.items():
a_n = int(ref.split(":")[1])
ay_ns = nsfold(ay)
if len(ay_ns) < 10:
continue
if ay_ns in q_ns:
ratio = len(ay_ns) / len(q_ns)
if best is None or ratio > best[1]:
best = (a_n, ratio)
elif q_ns in ay_ns and len(q_ns) >= 10:
if best is None or best[1] < 1.0:
best = (a_n, 1.0)
if best is not None and best[1] >= 0.55:
out.append((m.start(), best[0], len(m.group(0)), "bracket"))
# bare-fragment anchors: longest consecutive word-run per verse, with
# position mapping back to raw coordinates via the nospace imap
flat, imap = fold_with_map(blob)
ns = "".join(c for c in flat if not c.isspace() and not c.isdigit())
ns_imap = [imap[j] for j, c in enumerate(flat)
if not c.isspace() and not c.isdigit()]
ns_loose = ns.translate(LOOSE_MAP)
MIN_RUN = 12 # reliable word-run length (nospace chars)
MIN_LOOSE = 14 # hamza-loose runs need extra length to stay reliable
for ref, ay in sorted(tz_s.items(), key=lambda kv: int(kv[0].split(":")[1])):
a_n = int(ref.split(":")[1])
ay_words = [w for w in ay.split(" ") if w]
run, method = None, None
# pass 1: exact nospace word-run
best = (0, None)
for i in range(len(ay_words)):
cur = ""
for j in range(i, len(ay_words)):
cur += nsfold(ay_words[j])
if cur not in ns:
break
if len(cur) > best[0]:
best = (len(cur), cur)
if best[0] >= MIN_RUN:
run, method = best[1], "ns"
else:
# pass 2: hamza-loose word-run
best_l = (0, None)
for i in range(len(ay_words)):
cur = ""
for j in range(i, len(ay_words)):
cur += nsfold(ay_words[j], loose=True)
if cur not in ns_loose:
break
if len(cur) > best_l[0]:
best_l = (len(cur), cur)
if best_l[0] >= MIN_LOOSE:
run, method = best_l[1], "loose"
if run is not None:
hay = ns_loose if method == "loose" else ns
pos = hay.find(run)
while pos >= 0:
if pos < len(ns_imap):
out.append((ns_imap[pos], a_n, len(run), method))
pos = hay.find(run, pos + 1)
elif len(nsfold(ay)) < MIN_RUN:
# pass 3: tiny opener verse, whole-word with letter boundaries
nsfull = nsfold(ay)
if nsfull:
for m2 in re.finditer(
f"(?<![{AR_LETTER}]){re.escape(nsfull)}(?![{AR_LETTER}])",
flat):
if m2.start() < len(imap):
out.append((imap[m2.start()], a_n, len(nsfull), "short"))
out.sort(key=lambda f: (f[0], -f[2]))
# de-duplicate: keep the strongest anchor at overlapping positions
dedup = []
for item in out:
if dedup and item[1] == dedup[-1][1] and abs(item[0] - dedup[-1][0]) < 30:
continue
dedup.append(item)
return dedup
def segment_surah(S: int, blob: str, targets: list, tz: dict) -> dict:
"""Cut per-verse segments; write per-verse text files; return report.
A verse is EMITTED only when it has a real anchor in the substrate
(bracketed quote or >=25-char folded fragment). Verses listed by the TOC
but whose anchor cannot be found are flagged, not emitted (honest gap).
"""
flat = scan_anchors(blob, S, tz)
PAGE_MARK = re.compile(r"### PAGE \d+:\d+\n?")
res = {"verses": []}
for a in targets:
cands = [f for f in flat if f[1] == a]
flag = None
emit = bool(cands)
if cands:
# longest quoted restatement of this ayah opens the segment
anchor = max(cands, key=lambda f: f[2])
nxt = [f[0] for f in flat if f[0] > anchor[0] and f[1] > a]
if not nxt: # boundary guard: cut at the next anchor of any verse
nxt = [f[0] for f in flat if f[0] > anchor[0]]
start, end = anchor[0], (min(nxt) if nxt else len(blob))
if end <= start:
end = len(blob)
if anchor[3] == "loose":
flag = ("anchor matched with hamza-loose folding (edition "
"orthography divergence; quote verbatim from substrate)")
elif anchor[3] == "ns":
flag = ("anchor matched ignoring intra-word spacing and inline "
"footnote markers (edition orthography; quote verbatim "
"from substrate)")
elif anchor[3] == "short":
flag = ("tiny opener verse anchored by whole-word match "
"(muqatta'ah-class opener; quote verbatim from substrate)")
else:
start, end = 0, 0
flag = ("TOC lists a pericope but no quote anchor found in "
"substrate; verse skipped (honest gap)")
seg = PAGE_MARK.sub("‖", blob[start:end]).strip() if emit else ""
f = TEXT / f"{S}-{a:03d}.txt"
f.write_text(seg + "\n", encoding="utf-8")
res["verses"].append({
"ref": f"{S}:{a}", "anchored": bool(cands), "emit": emit,
"method": (max(cands, key=lambda f: f[2])[3] if cands else None),
"flag": flag, "segment_chars": len(seg),
"sha256": sha256(f.read_bytes()).hexdigest(),
})
if flag:
print(f" note {S}:{a} {flag}")
return res
def main():
mode = sys.argv[1] if len(sys.argv) > 1 else "probe"
if mode == "probe":
tz = tanzil_index()
v, p = int(sys.argv[2]), int(sys.argv[3])
r = probe(v, p, tz)
r.pop("text")
print(json.dumps(r, ensure_ascii=False, indent=1))
return
if mode == "toc":
load_pericopes(cache_only=False)
return
if mode == "plan":
pericopes = load_pericopes(cache_only=False)
plan = compute_plan(pericopes, ingested_targets())
for S, sp in sorted(plan.items()):
if sp["vol"] is None:
print(f"surah {S:2d}: NOT COVERED ({len(sp['missing_verses'])} verses)")
continue
miss = f" missing={sp['missing_verses']}" if sp["missing_verses"] else ""
print(f"surah {S:2d}: vol {sp['vol']} pages {sp['lo']}-{sp['hi']}"
f" covered {len(sp['covered_verses'])}{miss}")
return
if mode == "fetch":
build_all(tanzil_index(), cache_only=False)
return
if mode == "rebuild":
build_all(tanzil_index(), cache_only=True)
return
print(__doc__)
if __name__ == "__main__":
main()