File size: 3,426 Bytes
082342a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/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()