quran-md-data / scripts /ingest_pages.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
3.36 kB
#!/usr/bin/env python3
"""
6-Page Ingestion Pipeline for quran.md
Fetches real Arabic text, page metadata, and translations from api.quran.com/api/v4
and scaffolds canonical JSON files in /raw/ ready for tafsir/hadith enrichment.
"""
import json
import sys
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
def fetch_json(url: str) -> dict:
req = urllib.request.Request(url, headers={"User-Agent": "quran-md-ingestor/0.1"})
with urllib.request.urlopen(req, timeout=20) as resp:
return json.loads(resp.read().decode("utf-8"))
def ingest_page(page: int) -> int:
url = f"https://api.quran.com/api/v4/verses/by_page/{page}?language=en&words=true&translations=20&fields=text_uthmani,chapter_id,verse_number,verse_key"
data = fetch_json(url)
verses = data.get("verses", [])
count = 0
for v in verses:
surah = int(v["verse_key"].split(":")[0])
ayah = int(v["verse_key"].split(":")[1])
out_file = RAW_DIR / f"{surah:03d}-{ayah:03d}.json"
if out_file.exists():
continue # preserve already-enriched files like 006-074.json
sahih_trans = ""
if v.get("translations"):
sahih_trans = v["translations"][0].get("text", "")
record = {
"schema_version": "1.0.0",
"verse_key": v["verse_key"],
"surah_number": surah,
"ayah_number": ayah,
"surah_name_en": f"Surah {surah}",
"surah_name_ar": "",
"page": page,
"revelation_type": "Meccan",
"revelation_order": surah,
"arabic_text": v.get("text_uthmani", ""),
"translations": {
"sahih_international": sahih_trans,
"qarai": ""
},
"roots": [],
"themes": [],
"disputed": False,
"dispute_types": [],
"asbab_al_nuzul": {"summary": "", "sources": []},
"sunni_perspectives": {
"tafsir_summary": "Pending canonical enrichment (Tabari, Ibn Kathir, Qurtubi, Razi).",
"tafsir_sources": [],
"hadiths": []
},
"shia_perspectives": {
"tafsir_summary": "Pending canonical enrichment (Al-Mizan, Majma' al-Bayan, Qummi).",
"tafsir_sources": [],
"hadiths": []
},
"isnad_matn_audit": {
"chain_comparison": "Pending Isnad audit.",
"internal_quranic_consistency": "Pending cross-reference.",
"logical_historical_audit": "Pending Matn audit.",
"anti_bias_note": ""
}
}
out_file.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
count += 1
return count
def main():
start_page = int(sys.argv[1]) if len(sys.argv) > 1 else 1
end_page = int(sys.argv[2]) if len(sys.argv) > 2 else start_page + 5
RAW_DIR.mkdir(parents=True, exist_ok=True)
total = 0
for p in range(start_page, end_page + 1):
added = ingest_page(p)
print(f"Page {p}: ingested {added} new verse(s)")
total += added
print(f"Done. Total new verses ingested (pages {start_page}-{end_page}): {total}")
if __name__ == "__main__":
main()