#!/usr/bin/env python3 import csv, json, os, re, sys, time from concurrent.futures import ThreadPoolExecutor ROOT = os.environ.get("UNSC_CORPUS_ROOT", ".") FAMILIES = { "resolutions": f"{ROOT}/resolutions", "presidential_statements": f"{ROOT}/presidential_statements", "verbatim_debates": f"{ROOT}/verbatim_debates", "documents": (f"{ROOT}/documents", f"{ROOT}/documents/pdfs"), } report = [] def w(s=""): report.append(s); print(s, flush=True) def safe_name(s): return re.sub(r"[^A-Za-z0-9.]+", "_", s).strip("_") def check_pdf(path): try: sz = os.path.getsize(path) except OSError: return "missing" if sz < 1000: return "empty" try: with open(path, "rb") as f: head = f.read(5) if head[:4] != b"%PDF": return "not_pdf" f.seek(max(0, sz - 2048)) tail = f.read() if b"%%EOF" not in tail: return "truncated" except OSError: return "missing" return "ok" def has_en(rec): return bool((rec.get("files") or {}).get("EN")) def validate_family(fam, meta_dir, pdf_dir): w(f"\n### {fam}") jl = f"{meta_dir}/metadata/records.jsonl" recs, bad_json = [], 0 for i, line in enumerate(open(jl)): try: recs.append(json.loads(line)) except Exception: bad_json += 1 ids = [r.get("record_id") for r in recs] n_dupe = len(ids) - len(set(ids)) n_nosym = sum(1 for r in recs if not r.get("symbol")) w(f"- metadata: {len(recs):,} records | bad_json={bad_json} | " f"dup_ids={n_dupe} | null_symbol={n_nosym}") with_en = [r for r in recs if r.get("symbol") and has_en(r)] expected_paths = {} for r in recs: base = safe_name(r.get("symbol") or r["record_id"]) expected_paths[f"{base}-EN.pdf"] = r def one(item): fn, r = item return fn, check_pdf(os.path.join(pdf_dir, fn)) t0 = time.time() results = {} with ThreadPoolExecutor(max_workers=12) as ex: for fn, status in ex.map(one, expected_paths.items()): results[fn] = status from collections import Counter cnt = Counter(results.values()) present = sum(1 for s in results.values() if s == "ok") corrupt = {fn: s for fn, s in results.items() if s in ("empty", "not_pdf", "truncated")} absent = [fn for fn, s in results.items() if s == "missing"] w(f"- pdfs: present_ok={present:,} | corrupt={len(corrupt)} " f"({dict((k,v) for k,v in cnt.items() if k not in ('ok','missing'))}) | " f"absent={len(absent):,} [{time.time()-t0:.0f}s]") if corrupt: w(f" CORRUPT FILES: {list(corrupt.items())[:20]}") disk = set(); dsidecars = 0 try: with os.scandir(pdf_dir) as it: for e in it: if e.name.startswith("._"): dsidecars += 1 continue if e.name.endswith("-EN.pdf"): disk.add(e.name) except FileNotFoundError: pass orphans = disk - set(expected_paths.keys()) parts = [n for n in (os.listdir(pdf_dir) if os.path.isdir(pdf_dir) else []) if n.endswith(".part")] if dsidecars: w(f"- macOS ._ sidecar files present: {dsidecars:,} (cosmetic; remove with dot_clean)") w(f"- orphans (files w/o record)={len(orphans)} | .part_files={len(parts)}") if orphans: w(f" ORPHANS: {list(orphans)[:10]}") return {"records": len(recs), "present": present, "corrupt": len(corrupt), "absent": len(absent), "orphans": len(orphans), "bad_json": bad_json, "dup_ids": n_dupe, "with_en": len(with_en)} def validate_voting(): w("\n### voting_data") vdir = f"{ROOT}/voting_data" rc = f"{vdir}/roll_call.csv" from collections import Counter vc = Counter(); rows = 0; bad = 0; recids = set() with open(rc) as f: r = csv.DictReader(f) for row in r: rows += 1 recids.add(row["record_id"]) v = row["vote"] vc[v] += 1 if v not in ("Y", "N", "A", "X", ""): bad += 1 w(f"- roll_call.csv: {rows:,} rows | distinct votes={len(recids):,} | " f"vote_codes={dict(vc)} (Y/N/A/X=non-voting) | invalid={bad}") sm = f"{vdir}/summary.csv" bad_tally = 0; srows = 0 with open(sm) as f: for row in csv.DictReader(f): srows += 1 try: y = int(row["yes"] or 0); n = int(row["no"] or 0) a = int(row["abstain"] or 0); tot = int(row["total"] or 0) if tot and (y + n + a) > tot: bad_tally += 1 except ValueError: pass w(f"- summary.csv: {srows:,} rows | inconsistent_tally={bad_tally}") def main(): w("# UNSC Corpus — Validation Report") w(f"\nGenerated {time.strftime('%Y-%m-%d %H:%M')}.") w("\n## Per-family integrity") totals = {} for fam, loc in FAMILIES.items(): meta_dir, pdf_dir = (loc, f"{loc}/pdfs") if isinstance(loc, str) else loc totals[fam] = validate_family(fam, meta_dir, pdf_dir) validate_voting() w("\n## Coverage reconciliation") gap = f"{ROOT}/documents/english_coverage_final.tsv" ngap = sum(1 for _ in open(gap)) - 1 if os.path.exists(gap) else -1 tot_present = sum(t["present"] for t in totals.values()) tot_corrupt = sum(t["corrupt"] for t in totals.values()) tot_orphan = sum(t["orphans"] for t in totals.values()) w(f"- total valid English PDFs: {tot_present:,}") w(f"- total corrupt: {tot_corrupt} | total orphans: {tot_orphan}") w(f"- enumerated no-English gap list rows: {ngap:,}") verdict = "PASS" if (tot_corrupt == 0 and tot_orphan == 0 and all(t["bad_json"] == 0 and t["dup_ids"] == 0 for t in totals.values())) else "REVIEW" w(f"\n## Verdict: {verdict}") open(f"{ROOT}/VALIDATION.md", "w").write("\n".join(report)) print(f"\nwrote {ROOT}/VALIDATION.md") if __name__ == "__main__": main()