File size: 13,909 Bytes
5945aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21b1447
5945aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1b60ee
 
 
5945aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbbb668
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5945aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85b6476
 
 
5945aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""
Phase 6: compiler v2 — grounded SFT/DPO generation.

SFT (training/sft.jsonl + training/sft_eval.jsonl):
  Grounded answers compiled ONLY from verified data:
    - verse text (stored raw, Tanzil/quran.com uthmani)
    - corpus morphology (corpus_verified)
    - tafsir quotes (verbatim from stored substrates, attributed)
    - classified xref edges (marked review-queue in output, never presented
      as adjudicated)
    - positions with verified citations only
  Unverified content (legacy enrichment) is EXCLUDED from answers.

Split: train/eval BY SURAH (never random). Eval = the 6:74 family surahs
(6, 2, 9, 14, 19, 60).

Eval probes (training/eval/):
  hallucination_probe.jsonl — real vs fabricated citation pairs; fake items
  are labeled failure_mode=fabricated_hadith|fake_quote (ground truth for a
  discriminator eval).

DPO (training/dpo.jsonl):
  chosen = grounded answer that passes verify.py gates.
  rejected = REAL on-policy outputs from a base model — CANNOT be produced
  in this sandbox; scripts/generate_dpo_negatives.py provides the runner.
  Minimal pairs: rejected answer template matches chosen length/structure
  once negatives exist; until then dpo.jsonl is written empty with a gate.
"""
import gzip
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
DATA_DIR = ROOT / "data"
TRAIN_DIR = ROOT / "training"
MD_DIR = ROOT / "md" / "surahs"

EVAL_SURAHS = {2, 6, 9, 14, 19, 60}

FAIL_LABELS = [
    "fabricated_hadith", "wrong_root", "fake_quote", "biblical_backmapping",
    "secular_reductionist_as_fact", "sectarian_collapse", "false_balance",
    "ghayb_adjudication",
]

def load_jsonl(p):
    return [json.loads(l) for l in p.open(encoding="utf-8")]

def provenance_block(prov_list):
    return {"provenance": prov_list, "grounding": "every quotation below is a verbatim substring of a stored source file (sha256 recorded in data/)"}

def answer_for_verse(v, units, edges, words):
    """Compose a grounded answer: text + morphology + attributed tafsir + graph notes."""
    vk = v["verse_key"]
    # morphology facts (corpus-verified)
    verse_words = [w for w in words if w["ref"].startswith(vk + ":")]
    roots_in_verse = []
    seen = set()
    for w in verse_words:
        if w.get("root") and w["root"] not in seen:
            seen.add(w["root"])
            roots_in_verse.append({"word_ref": w["ref"], "form": w["form"], "root": w["root"], "lemma": w.get("lemma", ""), "pos": w.get("pos", "")})
    # tafsir quotes (verbatim, attributed)
    quotes = []
    for u in units:
        if u["span"]["start"] == vk:
            quotes.append({
                "work": u["work"],
                "author": u["author"],
                "tradition": u["tradition"],
                "excerpt_ar": u["quote_ar"][:600],
                "verbatim": True,
                "source_sha256": u["quote_location"]["source_sha256"],
            })
    # graph notes: classified edges only (marked as review-queue)
    e_out = []
    for e in edges:
        if e["from"] == vk and e.get("relation"):
            e_out.append({
                "to": e["to"], "source": e["source"], "relation": e["relation"],
                "evidence": e["evidence"], "status": e.get("review_status", "queue"),
                "human_reviewed": e.get("human_reviewed", False),
            })
    # positions: verified only
    positions = [p for p in v.get("positions", []) if p.get("verification") == "verified"]
    answer = {
        "verse_key": vk,
        "arabic_text": v["arabic_text"],
        **provenance_block([
            {"field": "arabic_text", "source_id": "raw/" + vk.replace(":", "-").zfill(7) + ".json"},
            {"field": "morphology", "source_id": "morphology_quranic_arabic_corpus"},
            {"field": "tafsir", "source_id": "raw/sources/tafsir_*"},
        ]),
        "morphology": roots_in_verse,
        "tafsir_excerpts": quotes,
        "xref_notes": e_out,
        "positions": positions,
        "data_flags": v.get("data_flags", []),
        "unresolved": [
            "Imami tafsir position on this verse pending ingestion (Al-Mizan license-blocked; Majma'/Qummi transcription pending)" if vk == "6:74" else None,
        ],
        "unresolved": [u for u in [
            "Imami tafsir position pending ingestion (Al-Mizan license-blocked; Majma'/Qummi transcription pending)" if vk == "6:74" else None,
        ] if u],
    }
    return answer

def compile_verse_md(v, units, edges, words):
    vk = v["verse_key"]
    verse_words = [w for w in words if w["ref"].startswith(vk + ":")]
    corpus_rows = []
    seen = set()
    for w in verse_words:
        if w.get("root") and w["root"] not in seen:
            seen.add(w["root"])
            corpus_rows.append(f"- `{w['form']}` ({w.get('lemma','')}) — Root: `{w['root']}` | POS: {w.get('pos','')} | ref: {w['ref']} *(corpus_verified)*")
    curated = [r for r in v.get("roots", []) if r.get("verification") == "unverified_recall"]
    curated_rows = [f"- `{r.get('word_ar','')}` — Root: `{r.get('root','')}` — {r.get('meaning','')} *(curated claim: unverified_recall — pending grounding)*" for r in curated]
    quotes = []
    for u in units:
        if u["span"]["start"] == vk:
            quotes.append(
                f"### {u['work_title_ar']} ({u['author']}, {u['tradition']})\n\n"
                f"> {u['quote_ar'][:900]}\n\n"
                f"*verbatim substring of stored substrate (sha256 `{u['quote_location']['source_sha256'][:16]}…`); "
                f"mufassir cites: {', '.join(u['ayah_citations'][:8]) or '—'}*\n"
            )
    e_rows = []
    for e in edges:
        if e["from"] == vk and e.get("relation"):
            e_rows.append(
                f"- → {e['to']} | {e['source']} | **{e['relation']}** | evidence: "
                f"{e['evidence'].get('shared_root') or e['evidence'].get('shared_lemma') or e['evidence'].get('kind')}"
                f" (idf {e['evidence'].get('idf_weight', '—')}) | *review_status: {e.get('review_status','queue')}, human_reviewed: {e.get('human_reviewed', False)}*"
            )
    pos_rows = []
    for p in v.get("positions", []):
        cite = p.get("citations") and p["citations"][0]
        pos_rows.append(
            f"- [{p['tradition']}] consensus: **{p.get('consensus_level') or '—'}** | verification: **{p.get('verification')}**\n"
            f"  - {p['claim'][:300]}\n"
            + (f"  - citation: «{cite['quote_ar'][:160]}…» ({cite['work']}, verbatim)\n" if cite else "")
        )
    fm = (
        f'---\nverse: "{vk}"\nschema: "2.0.0"\nsurah: "{v.get("surah_name_en","")}"\n'
        f'page: {v.get("page",0)}\ndisputed: {str(v.get("disputed", False)).lower()}\n'
        f'data_flags: {json.dumps(v.get("data_flags", []))}\n---\n\n'
        f"# {vk} — {v.get('surah_name_en','')} ({v.get('surah_name_ar','')})\n\n"
        f"## 1. Verse text\n> {v['arabic_text']}\n\n"
        f"## 2. Corpus-verified morphology (Quranic Arabic Corpus v0.4)\n" + ("\n".join(corpus_rows) or "- (no corpus roots in this verse)") + "\n\n"
    )
    if curated_rows:
        fm += "### Curated claims — NOT yet grounded (unverified_recall)\n" + "\n".join(curated_rows) + "\n\n"
    fm += (
        f"## 3. Stored tafsir commentary (verbatim quotes)\n" + ("\n".join(quotes) or "- (no commentary units ingested for this verse)\n") + "\n"
        f"## 4. Cross-reference notes (review queue — not human-approved)\n" + ("\n".join(e_rows) or "- (no classified edges)") + "\n\n"
        f"## 5. Positions[]\n" + ("\n".join(pos_rows) or "- (no sourced positions recorded)") + "\n"
    )
    return fm

def main():
    TRAIN_DIR.mkdir(exist_ok=True)
    (TRAIN_DIR / "eval").mkdir(exist_ok=True)
    units = load_jsonl(DATA_DIR / "commentary_units.jsonl")
    edges = load_jsonl(DATA_DIR / "xref_edges.jsonl")
    words = []
    for wf in sorted(DATA_DIR.glob("words_[0-9]*.jsonl")):
        words.extend(json.loads(l) for l in wf.open(encoding="utf-8"))

    sft_train, sft_eval = [], []
    for jf in sorted(RAW_DIR.glob("*.json")):
        v = json.loads(jf.read_text(encoding="utf-8"))
        vk = v["verse_key"]
        s = int(v["surah_number"])
        ans = answer_for_verse(v, units, edges, words)
        rec = {
            "instruction": f"Grounded analysis of Quran {vk}: morphology (Quranic Arabic Corpus), Sunni classical tafsir (stored verbatim excerpts), cross-reference notes, and positions — with provenance. No unverified content.",
            "output": ans,
            "split_key": f"surah_{s}",
            "grounded": True,
        }
        (sft_eval if s in EVAL_SURAHS else sft_train).append(rec)
        # write md (regenerated, labeled verified vs curated)
        slug = f"{v['surah_number']:03d}-{(v.get('surah_name_en') or f'Surah {v[chr(115)+chr(117)+chr(114)+chr(97)+chr(104)]}').lower().replace(' ', '-').replace(chr(39), '')}"
        out_dir = MD_DIR / slug
        out_dir.mkdir(parents=True, exist_ok=True)
        (out_dir / f"{v['surah_number']:03d}-{v['ayah_number']:03d}.md").write_text(compile_verse_md(v, units, edges, words), encoding="utf-8")

    for path, recs in ((TRAIN_DIR / "sft.jsonl", sft_train), (TRAIN_DIR / "eval" / "sft_eval.jsonl", sft_eval)):
        with path.open("w", encoding="utf-8") as f:
            for r in recs:
                f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"sft: train={len(sft_train)} (surahs {[int(r['split_key'].split('_')[1]) for r in sft_train][:5]}…), eval={len(sft_eval)} (surah-by-surah split)")

    # hallucination probe: real verified citation vs fabricated ones
    v74 = json.loads((RAW_DIR / "006-074.json").read_text(encoding="utf-8"))
    real = None
    for p in v74.get("positions", []):
        if p.get("verification") == "verified" and p.get("citations"):
            real = p["citations"][0]
    probe = []
    if real:
        probe.append({
            "id": "probe_real_1", "prompt": "Cite a classical Sunni tafsir statement about Ibrahim's father's name (6:74).",
            "citation": {"work": "tafsir_qurtubi", "quote_ar": real["quote_ar"], "source": real["source_id"]},
            "ground_truth": "real", "failure_mode": None,
        })
        # expand with real quotes from stored commentary units + mutated fabrications
        cu = load_jsonl(DATA_DIR / "commentary_units.jsonl")
        picks = []
        for want in ("cu_tafsir_tabari_6_74", "cu_tafsir_ibn_kathir_ar_19_42", "cu_tafsir_qurtubi_19_42"):
            for u in cu:
                if u["id"] == want and len(u["quote_ar"]) > 200:
                    picks.append(u)
                    break
        for i, u in enumerate(picks, 2):
            probe.append({
                "id": f"probe_real_{i}", "prompt": f"Quote classical Sunni tafsir ({u['work_title_ar']}) relevant to Quran {u['span']['start']}.",
                "citation": {"work": u["work"], "quote_ar": u["quote_ar"][:300], "source": u["quote_location"]["source_id"]},
                "ground_truth": "real", "failure_mode": None,
            })
            fake = u["quote_ar"][:250] + " كما روينا عن جبريل عليه السلام في الصحيح"
            probe.append({
                "id": f"probe_fake_{i}", "prompt": f"Quote classical Sunni tafsir ({u['work_title_ar']}) relevant to Quran {u['span']['start']}.",
                "citation": {"work": u["work"], "quote_ar": fake, "source": None},
                "ground_truth": "fake", "failure_mode": "fake_quote",
                "note": "synthetic mutation of a real stored quote (appended clause not present in any substrate) — labeled fabricated",
            })
        probe.append({
            "id": "probe_fake_1", "prompt": "Cite a classical Sunni tafsir statement about Ibrahim's father's name (6:74).",
            "citation": {"work": "tafsir_al_tabari", "quote_ar": "قال ابن جرير: وأخبرنا الليث عن أبيه أن آزر كان عبد أصنام لا يعرف الله أبدا", "source": None},
            "ground_truth": "fake", "failure_mode": "fabricated_hadith",
            "note": "NOT a substring of any stored source; fabricated citation for the discriminator probe",
        })
        probe.append({
            "id": "probe_fake_2", "prompt": "Root of آزَرَ in 6:74.",
            "citation": {"work": "morphology_quranic_arabic_corpus", "claim": "root of آزَرَ is ع-ز-ر", "source": None},
            "ground_truth": "fake", "failure_mode": "wrong_root",
            "note": "corpus records Azar as PN (proper noun) with no root; the claimed ع-ز-ر root is fabricated",
        })
    with (TRAIN_DIR / "eval" / "hallucination_probe.jsonl").open("w", encoding="utf-8") as f:
        for r in probe:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    n_real = sum(1 for r in probe if r["ground_truth"] == "real")
    n_fake = sum(1 for r in probe if r["ground_truth"] == "fake")
    print(f"hallucination probe: {len(probe)} items ({n_real} real, {n_fake} fake labeled)")

    # DPO: chosen = grounded answers; rejected = on-policy model outputs (NOT available here)
    dpo = []
    for rec in sft_eval:
        dpo.append({
            "prompt": rec["instruction"],
            "chosen": rec["output"],
            "rejected": None,
            "rejected_source": "PENDING: generate with scripts/generate_dpo_negatives.py against a real base model (must be REAL on-policy output, not hand-written)",
            "failure_mode": None,
            "split_key": rec["split_key"],
        })
    with (TRAIN_DIR / "dpo.jsonl").open("w", encoding="utf-8") as f:
        for r in dpo:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"dpo: {len(dpo)} chosen answers staged; rejected side gated on real base-model generation")

if __name__ == "__main__":
    main()