Download scripts/fetch_majma_eshia.py from bravesigma/quran-md-data: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main/scripts/fetch_majma_eshia.py
- Command line
-
hf download hf://datasets/bravesigma/quran-md-data/scripts/fetch_majma_eshia.py
-
curl -L -o fetch_majma_eshia.py https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main/scripts/fetch_majma_eshia.py
14.6 kB
| #!/usr/bin/env python3 | |
| """ | |
| Phase 4 (Imami gap): fetch Majma' al-Bayan (Tabrisi, d. 548 AH) Arabic text | |
| from the digital library of Madrasat al-Fiqahah (ar.lib.eshia.ir), Dar | |
| al-Ma'rifah edition, and extract per-verse commentary segments for the | |
| already-ingested verse set. | |
| Determinism rules (project constitution): | |
| - 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. | |
| Usage: | |
| fetch_majma_eshia.py probe V P # inspect one page (debug) | |
| fetch_majma_eshia.py locate # find surah start pages | |
| fetch_majma_eshia.py fetch # fetch spans + build substrate + report | |
| """ | |
| 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_majma_albayan" | |
| OUT = ROOT / "raw" / "sources" / WORK | |
| PAGES = OUT / "pages" | |
| TEXT = OUT / "text" | |
| BOOK = 86854 | |
| 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 | |
| # target surahs = surahs of the 192 ingested verses; anchors known from TOC | |
| TARGETS = { | |
| 1: {"start": (1, 87), "name": "الفاتحة"}, | |
| 2: {"start": (1, 111), "name": "البقرة"}, | |
| 6: {"vol_guess": [5, 6], "name": "الأنعام"}, | |
| 9: {"vol_guess": [7, 8], "name": "التوبة"}, | |
| 14: {"vol_guess": [8, 9], "name": "إبراهيم"}, | |
| 19: {"vol_guess": [9, 10], "name": "مريم"}, | |
| 60: {"vol_guess": [10], "name": "المجادلة"}, | |
| } | |
| 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]") | |
| SURAH_HEAD = re.compile(r"\((\d+)\)\s+سورة\s+([^\n(]{1,30})") | |
| JUNK = re.compile(r"جستجوی سریع.*?اعراب گذاری", re.DOTALL) | |
| BRACKETS = "«»﴿﴾()[]{}<>\"'.,:;!?؟،؛…ـ" | |
| 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 as e: | |
| 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: | |
| """Normalize a stored page HTML into the book-content text only. | |
| v2 extraction: fence to td#book-page-content (the book text container), | |
| drop the sticky-menue tool chrome inside it, and strip the leading | |
| printed page number. Site nav, header, footer (Book_Title edition line) | |
| and tool panels never enter the substrate. Inline edition footnotes stay | |
| in the flow — they are flagged downstream, never silently dropped. | |
| """ | |
| soup = BeautifulSoup(html, "html.parser") | |
| content = soup.find("td", id="book-page-content") | |
| if content is None: | |
| # defensive fallback to the v1 fencing (should not trigger on eshia) | |
| 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: | |
| """Fetch (cache-first) a page and return its normalized CONTENT text.""" | |
| 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 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 quoted on this page (string matching).""" | |
| out = {} | |
| for m in QUOTE_RE.finditer(text): | |
| q = mfold(m.group(1)) | |
| if len(q) < 6: | |
| continue | |
| best = None | |
| for ref, ay in tz.items(): | |
| if ay in q: | |
| # full verse inside a larger quoted span -> require decent coverage | |
| ratio = len(ay) / len(q) | |
| if best is None or ratio > best[1]: | |
| best = (ref, ratio) | |
| elif q in ay and len(q) >= 10: | |
| # contiguous fragment of a long verse -> size guard instead of | |
| # ratio (a 10+ char folded Quranic fragment is a reliable anchor) | |
| 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] = (m.group(1), best[1], m.start()) | |
| return out | |
| def ref_key(ref) -> tuple: | |
| s, a = str(ref).split(":") | |
| return (int(s), int(a)) | |
| def probe(v: int, p: int, tz: dict) -> dict: | |
| text = page_text(v, p) | |
| heads = [(int(m.group(1)), m.group(2).strip()) for m in SURAH_HEAD.finditer(text)] | |
| refs = match_refs(text, tz) | |
| maxref = max(refs.keys()) if refs else None | |
| return {"vol": v, "page": p, "bytes": len(text), "surah_heads": heads, | |
| "refs": sorted(refs.keys()), "max_ref": maxref, "text": text} | |
| def locate(surah: int, tz: dict, vols: list, pmax: int = 560) -> tuple: | |
| """Stride-scan + bisect within each candidate volume; return (vol,page).""" | |
| target = (surah, 1) | |
| for v in vols: | |
| hits = [] | |
| pages = list(range(10, pmax, 30)) | |
| seen_pages = set() | |
| for p in pages: | |
| if p in seen_pages: | |
| continue | |
| seen_pages.add(p) | |
| try: | |
| r = probe(v, p, tz) | |
| except Exception: | |
| continue | |
| if any(h[0] == surah for h in r["surah_heads"]): | |
| return (v, p) | |
| if r["max_ref"] is None: | |
| continue | |
| hits.append((p, r["max_ref"])) | |
| time.sleep(SLEEP) | |
| # bisect between the brackets around target | |
| below = [h for h in hits if h[1] < target] | |
| above = [h for h in hits if h[1] > target] | |
| if below and above: | |
| lo, hi = max(below)[0], min(above)[0] | |
| while hi - lo > 1: | |
| mid = (lo + hi) // 2 | |
| r = probe(v, mid, tz) | |
| time.sleep(SLEEP) | |
| if any(h[0] == surah for h in r["surah_heads"]): | |
| return (v, mid) | |
| if r["max_ref"] is None or r["max_ref"] < target: | |
| lo = mid | |
| else: | |
| hi = mid | |
| return (v, hi) | |
| raise SystemExit(f"surah {surah} not located in volumes {vols}") | |
| def main(): | |
| mode = sys.argv[1] if len(sys.argv) > 1 else "probe" | |
| tz = tanzil_index() | |
| if mode == "probe": | |
| 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 == "locate": | |
| found = {} | |
| if (OUT / "anchors.json").exists(): | |
| found = json.loads((OUT / "anchors.json").read_text(encoding="utf-8")) | |
| for s in (6, 9, 14, 19, 60): | |
| key = str(s) | |
| if key in found: | |
| continue | |
| (v, p) = locate(s, tz, TARGETS[s].get("vol_guess", [5])) | |
| found[key] = {"vol": v, "page": p, "url": page_url(v, p)} | |
| print(f"surah {s}: vol {v} page {p} ({page_url(v, p)})") | |
| (OUT / "anchors.json").write_text( | |
| json.dumps(found, ensure_ascii=False, indent=1), encoding="utf-8") | |
| time.sleep(SLEEP) | |
| print(json.dumps(found, ensure_ascii=False, indent=1)) | |
| return | |
| if mode == "fetch": | |
| fetch_all(tz) | |
| return | |
| if mode == "rebuild": | |
| build_all(tz, cache_only=True) | |
| return | |
| print(__doc__) | |
| # 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()} | |
| # walk spans resolved by the locate scans (2026-11-27) | |
| SPANS = { | |
| 1: [(1, 87, 110)], | |
| 2: [(1, 111, 210), (1, 380, 416)], | |
| 6: [(4, 481, 514)], | |
| 9: [(5, 108, 121)], | |
| 14: [(6, 486, 496)], | |
| 19: [(6, 773, 826)], | |
| 60: [(9, 405, 419)], | |
| } | |
| 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): | |
| """Rebuild substrate + per-verse segments + report from stored page HTML. | |
| cache_only=True never touches the network and fails loudly if any span | |
| page is missing from the cache (used by the `rebuild` mode). | |
| """ | |
| targets = ingested_targets() | |
| PAGES.mkdir(parents=True, exist_ok=True) | |
| TEXT.mkdir(parents=True, exist_ok=True) | |
| report = {"surahs": {}, "pages": {}} | |
| for S, spans in sorted(SPANS.items()): | |
| parts = [] | |
| for (v, lo, hi) in spans: | |
| for p in range(lo, hi + 1): | |
| pf = PAGES / f"{v}_{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(v, p) | |
| if len(html) <= 12000: | |
| continue | |
| report["pages"][f"{v}:{p}"] = {"sha256": sha256(pf.read_bytes()).hexdigest(), "bytes": len(html)} | |
| parts.append(f"### PAGE {v}:{p}\n{page_text(v, 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"]) | |
| print(f"surah {S}: substrate sha={sha256(sub.read_bytes()).hexdigest()[:12]}… anchored {n_ok}/{len(rep['verses'])}") | |
| (OUT / "extraction_report.json").write_text( | |
| json.dumps(report, ensure_ascii=False, indent=1), encoding="utf-8") | |
| def fetch_all(tz: dict): | |
| build_all(tz, cache_only=False) | |
| def scan_anchors(blob: str, S: int, tz: dict) -> list: | |
| """All surah-S quote anchors in blob coordinates: (pos, ayah, quote_len).""" | |
| out = [] | |
| tz_s = {ref: ay for ref, ay in tz.items() if ref.startswith(f"{S}:")} | |
| for m in QUOTE_RE.finditer(blob): | |
| q = mfold(m.group(1)) | |
| if len(q) < 6: | |
| continue | |
| best = None # (ayah, ratio) | |
| for ref, ay in tz_s.items(): | |
| a_n = int(ref.split(":")[1]) | |
| if ay in q and len(ay) / len(q) >= 0.55: | |
| if best is None or len(ay) > len(tz_s[f"{S}:{best}"]): | |
| best = a_n | |
| elif q in ay and len(q) >= 10: | |
| if best is None: | |
| best = a_n | |
| if best is not None: | |
| out.append((m.start(), best, len(m.group(0)))) | |
| out.sort() | |
| return out | |
| def segment_surah(S: int, blob: str, targets: list, tz: dict) -> dict: | |
| """Cut per-verse segments; write per-verse text files; return report.""" | |
| 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 | |
| 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] | |
| start, end = anchor[0], (min(nxt) if nxt else len(blob)) | |
| else: | |
| prev = [f[0] for f in flat if f[1] < a] | |
| nxt = [f[0] for f in flat if f[1] > a] | |
| start = min(prev) if prev else 0 | |
| end = min(nxt) if nxt else len(blob) | |
| flag = "short/unmatchable ayah; segment merged with neighboring verse discussion (detection limit)" | |
| seg = PAGE_MARK.sub("‖", blob[start:end]).strip() | |
| 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), "flag": flag, | |
| "segment_chars": len(seg), "sha256": sha256(f.read_bytes()).hexdigest(), | |
| }) | |
| if flag: | |
| print(f" note {S}:{a} {flag}") | |
| return res | |
| if __name__ == "__main__": | |
| main() | |