quran-md-data / scripts /compile.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.43 kB
#!/usr/bin/env python3
"""
Deterministic compiler for quran.md
Reads /raw/*.json -> compiles /md/surahs/<surah>/<verse>.md and /training/sft.jsonl
"""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
MD_DIR = ROOT / "md" / "surahs"
TRAIN_DIR = ROOT / "training"
def compile_verse(data: dict) -> str:
roots_md = "\n".join(
f"- **`{r['word_ar']}` ({r['transliteration']})** — Root: `{r['root']}` | Meaning: {r['meaning']}\n"
+ "".join(f" - Cross-ref: {c}\n" for c in r["internal_quranic_crossrefs"])
for r in data["roots"]
)
sunni_hadiths = "\n".join(
f"- **{h['book']} ({h['reference']})** — *Grading: {h['sunni_grading']}*\n"
f" - {h['summary']}\n - *Chain:* {h['chain_notes']}"
for h in data["sunni_perspectives"]["hadiths"]
)
shia_hadiths = "\n".join(
f"- **{h['book']} ({h['reference']})** — *Grading: {h['shia_grading']}*\n"
f" - {h['summary']}\n - *Chain:* {h['chain_notes']}"
for h in data["shia_perspectives"]["hadiths"]
)
audit = data["isnad_matn_audit"]
return f"""---
verse: "{data['verse_key']}"
surah: "{data['surah_name_en']}"
page: {data['page']}
revelation: "{data['revelation_type']}"
order: {data['revelation_order']}
disputed: {str(data['disputed']).lower()}
themes: {json.dumps(data.get('themes', []))}
---
# {data['verse_key']} — {data['surah_name_en']} ({data['surah_name_ar']})
## 1. Arabic Text & Linguistic Root Map
> {data['arabic_text']}
{roots_md}
## 2. Sunni Canonical Perspectives
- **Tafsir Summary:** {data['sunni_perspectives']['tafsir_summary']}
- **Sources:** {', '.join(data['sunni_perspectives']['tafsir_sources'])}
### Hadiths
{sunni_hadiths}
## 3. Shia Canonical Perspectives
- **Tafsir Summary:** {data['shia_perspectives']['tafsir_summary']}
- **Sources:** {', '.join(data['shia_perspectives']['tafsir_sources'])}
### Hadiths
{shia_hadiths}
## 4. Isnad (Chain) & Matn (Logic) Audit
- **Chain Comparison:** {audit['chain_comparison']}
- **Internal Quranic Consistency:** {audit['internal_quranic_consistency']}
- **Logical & Historical Audit:** {audit['logical_historical_audit']}
- **Anti-Bias Note:** {audit['anti_bias_note']}
"""
def main():
TRAIN_DIR.mkdir(parents=True, exist_ok=True)
sft_records = []
for json_file in sorted(RAW_DIR.glob("*.json")):
data = json.loads(json_file.read_text(encoding="utf-8"))
surah_slug = f"{data['surah_number']:03d}-{data['surah_name_en'].lower().replace(' ', '-').replace(chr(39), '')}"
out_dir = MD_DIR / surah_slug
out_dir.mkdir(parents=True, exist_ok=True)
md_content = compile_verse(data)
verse_filename = f"{data['surah_number']:03d}-{data['ayah_number']:03d}.md"
(out_dir / verse_filename).write_text(md_content, encoding="utf-8")
sft_records.append({
"instruction": f"Analyze Quran {data['verse_key']} ({data['surah_name_en']}) using Arabic root morphology, canonical Sunni and Shia tafsirs/hadiths, and an Isnad/Matn audit.",
"output": md_content
})
with (TRAIN_DIR / "sft.jsonl").open("w", encoding="utf-8") as f:
for rec in sft_records:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(f"Compiled {len(sft_records)} verse(s) to /md/ and /training/sft.jsonl")
if __name__ == "__main__":
main()