File size: 9,019 Bytes
842ec34 0de6fd1 842ec34 0de6fd1 842ec34 0de6fd1 842ec34 0de6fd1 e1b60ee 0de6fd1 842ec34 0de6fd1 e1b60ee 0de6fd1 1e02da8 0de6fd1 1e02da8 0de6fd1 1e02da8 0de6fd1 e1b60ee 0de6fd1 842ec34 | 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 | #!/usr/bin/env python3
"""
Verification Gate for quran.md — v2 (Phase 2+).
Extends the v1 gate. Verbatim-or-fail policy:
G1 raw/*.json structural integrity (v1 behaviour, unchanged)
G2 every quote_ar / text_ar claim must be a VERBATIM substring of the
stored source file it cites (source_id + source_sha256 must match)
G3 every corpus_verified root/lemma claim must exist in data/words.jsonl
G4 generated markdown: root claims shown for a verse must match the
corpus word records for that verse (roots of words present in it)
G5 xref edges: lexical edges may only use same_usage|different_usage;
refs must resolve; review_status respected
G6 schema_version consistency + data_flags sanity
Nothing is auto-deleted: failures name the file and field so an editor can
fix, flag, or quarantine the record.
"""
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
RAW_DIR = ROOT / "raw"
DATA_DIR = ROOT / "data"
SCHEMA_DIR = ROOT / "schema"
REQUIRED_KEYS = [
"schema_version", "verse_key", "surah_number", "ayah_number",
"page", "arabic_text", "sunni_perspectives", "shia_perspectives",
"isnad_matn_audit"
]
errors = []
warnings = []
def fold_root(r: str) -> str:
"""Fold root letters for comparison: strip hyphens/diacritics and unify
alef forms (أ إ آ ٱ ا -> ا, ى -> ي). Root-letter folding only; never
applied to quotes."""
if not r:
return ""
r = re.sub(r"[\u064B-\u0652\u0670\u0640-]", "", r)
r = r.replace("-", "")
for a in ("\u0623", "\u0625", "\u0622", "\u0671", "\u0627"):
r = r.replace(a, "\u0627")
r = r.replace("\u0649", "\u064A")
return r
def load_words():
words = {}
for wf in sorted(DATA_DIR.glob("words_[0-9]*.jsonl")):
for line in wf.open(encoding="utf-8"):
r = json.loads(line)
words[r["ref"]] = r
return words
def check_verse_files(words):
for f in sorted(RAW_DIR.glob("*.json")):
try:
data = json.loads(f.read_text(encoding="utf-8"))
except Exception as e:
errors.append(f"G1 {f.name}: invalid JSON ({e})")
continue
for k in REQUIRED_KEYS:
if k not in data:
errors.append(f"G1 {f.name}: missing {k}")
# G3: corpus-verified root claims must match corpus words for this verse
vk = f"{data.get('surah_number')}:{data.get('ayah_number')}"
verse_words = {w["ref"]: w for wr, w in words.items() if wr.startswith(vk + ":")}
for r in data.get("roots", []):
if r.get("verification") != "corpus_verified":
continue
ref = r.get("ref") or ""
w = verse_words.get(ref)
if not w:
errors.append(f"G3 {f.name}: corpus_verified root ref {ref} not in corpus")
continue
if fold_root(r.get("root")) != fold_root(w["root"]):
errors.append(f"G3 {f.name}: root claim '{r.get('root')}' != corpus '{w['root']}' at {ref}")
if r.get("lemma") and w.get("lemma") and r["lemma"] != w["lemma"]:
errors.append(f"G3 {f.name}: lemma claim '{r['lemma']}' != corpus '{w['lemma']}' at {ref}")
# G3b: words refs must resolve
for ref in data.get("words", []):
if ref not in words:
errors.append(f"G3 {f.name}: word ref {ref} not in data/words_* shards")
def load_stored_source(source_id: str, sha: str):
"""Stored raw source files live in raw/sources/. A claim passes only if a
file with a matching sha256 exists there. source_id may be a repo-relative
path (commentary text substrates) — honored directly when it exists."""
if source_id:
p = ROOT / source_id
if p.is_file():
if not sha or sha == _sha256(p):
return p
return None
src_dir = RAW_DIR / "sources"
for f in sorted(src_dir.rglob("*")):
if not f.is_file() or f.name.endswith(".sha256"):
continue
if sha and sha != _sha256(f):
continue
return f
return None
def _sha256(f: Path) -> str:
import hashlib
return hashlib.sha256(f.read_bytes()).hexdigest()
def check_verbatim_quotes():
"""G2: scan data/*.jsonl for quote-like fields with provenance."""
for name in ("commentary_units.jsonl", "hadith.jsonl"):
jf = DATA_DIR / name
if not jf.exists():
continue
for i, line in enumerate(jf.open(encoding="utf-8"), 1):
try:
rec = json.loads(line)
except Exception as e:
errors.append(f"G2 {name}:{i}: invalid JSON ({e})")
continue
quote = rec.get("quote_ar") or rec.get("text_ar") or ""
loc = rec.get("quote_location") or rec.get("provenance") or {}
src_id = loc.get("source_id") or rec.get("collection", "")
sha = loc.get("source_sha256") or rec.get("provenance", {}).get("source_sha256", "")
if not quote:
continue
src = load_stored_source(src_id, sha)
if src is None:
errors.append(f"G2 {name}:{i}: stored source not found for {src_id} (sha {sha[:12]}…)")
continue
text = src.read_text(encoding="utf-8")
if quote not in text:
errors.append(f"G2 {name}:{i}: quote_ar is NOT a verbatim substring of {src.name}")
def check_xref_edges():
jf = DATA_DIR / "xref_edges.jsonl"
if not jf.exists():
return
raw_keys = set()
for f in RAW_DIR.glob("*.json"):
d = json.loads(f.read_text(encoding="utf-8"))
raw_keys.add(f"{d['surah_number']}:{d['ayah_number']}")
for i, line in enumerate(jf.open(encoding="utf-8"), 1):
try:
e = json.loads(line)
except Exception as ex:
errors.append(f"G5 xref_edges.jsonl:{i}: invalid JSON ({ex})")
continue
status = e.get("review_status", "queue")
if e.get("source") == "lexical":
if status == "accepted" and e.get("relation") not in ("same_usage", "different_usage"):
errors.append(f"G5 xref_edges.jsonl:{i}: accepted lexical edge relation must be same_usage|different_usage")
if status == "accepted" and not e.get("human_reviewed"):
errors.append(f"G5 xref_edges.jsonl:{i}: accepted edge must be human_reviewed=true")
for endpoint in ("from", "to"):
ref = e.get(endpoint, "")
s, a = ref.split(":")[:2]
# endpoints may reference any verse in the corpus (not only ingested ones)
if not re.match(r"^\d+:\d+$", ref):
errors.append(f"G5 xref_edges.jsonl:{i}: bad ref {ref!r}")
if e.get("source") == "lexical" and not e.get("evidence", {}).get("idf_weight"):
warnings.append(f"G5 xref_edges.jsonl:{i}: lexical edge missing idf_weight")
def check_markdown_roots(words):
"""G4: compiled markdown root claims must match corpus words of that verse."""
md_dir = ROOT / "md" / "surahs"
if not md_dir.exists():
return
root_re = re.compile(r"^-\s\*\*`([^`]+)`[^*]*\*\*.*Root:\s*`([^`]+)`", re.M)
for f in md_dir.rglob("*.md"):
text = f.read_text(encoding="utf-8")
m = re.search(r'version:\s*"(\d+:\d+)"', text) or re.search(r'verse:\s*"(\d+:\d+)"', text)
if not m:
continue
vk = m.group(1)
verse_words = [w for ref, w in words.items() if ref.startswith(vk + ":")]
corpus_roots = {w["root"] for w in verse_words if w.get("root")}
for word_ar, root in root_re.findall(text):
if root in ("Non-Arabic proper noun",):
continue
if fold_root(root) not in {fold_root(x) for x in corpus_roots}:
errors.append(f"G4 {f.relative_to(ROOT)}: root claim '{root}' (word {word_ar}) not in corpus roots for {vk}")
def check_schema_files():
import glob
for f in glob.glob(str(SCHEMA_DIR / "*.json")):
try:
json.loads(Path(f).read_text(encoding="utf-8"))
except Exception as e:
errors.append(f"G6 {f}: invalid schema JSON ({e})")
def main():
words = load_words()
print(f"verify: {len(words)} word records loaded (from data/words_[0-9]*.jsonl shards)")
check_verse_files(words)
check_verbatim_quotes()
check_xref_edges()
check_markdown_roots(words)
check_schema_files()
n_raw = len(list(RAW_DIR.glob("*.json")))
print(f"Verified {n_raw} raw file(s).")
for w in warnings:
print(f"[warn] {w}")
if errors:
print(f"FAILED with {len(errors)} error(s):")
for e in errors[:50]:
print(f" [error] {e}")
if len(errors) > 50:
print(f" … and {len(errors) - 50} more")
sys.exit(1)
print("PASS: all gates green (G1-G6).")
if __name__ == "__main__":
main()
|