quran-md-data / scripts /verify.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
9.02 kB
#!/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()