"""Validate the Global Eco-Certification Knowledge Base and write a data-quality report. Usage: python scripts/validate_dataset.py [repo_root] [--report docs/data_quality_report.md] [--json validation_results.json] Errors (exit code 1): unreadable tables, duplicate or malformed IDs, invalid enum values, records without provenance, citations of unknown sources, archived documents missing or failing their SHA-256. Warnings: references to IDs that have no record of their own, non-ISO dates, unreachable source URLs. Reads Parquet when pyarrow/pandas are installed, otherwise the JSON copies (standard library only). """ import argparse import hashlib import json import re import sys from collections import Counter from pathlib import Path MISSING = {"", "unknown", "not_publicly_available", "not_applicable", None} def is_missing(v): return v is None or (isinstance(v, str) and v.strip() in MISSING) DATE_RE = re.compile(r"^\d{4}(-\d{2}(-\d{2})?)?$") def load(root, name): pq = root / "data" / f"{name}.parquet" try: import pandas as pd df = pd.read_parquet(pq) recs = df.to_dict("records") for r in recs: for k, v in r.items(): if hasattr(v, "tolist"): r[k] = v.tolist() return recs except ImportError: return json.loads((root / "json" / f"{name}.json").read_text("utf-8")) def main(): ap = argparse.ArgumentParser() ap.add_argument("root", nargs="?", default=str(Path(__file__).resolve().parent.parent)) ap.add_argument("--report", default=None) ap.add_argument("--json", default=None) args = ap.parse_args() root = Path(args.root) schema = json.loads((root / "schema.json").read_text("utf-8")) errors, warnings = [], [] data = {} for t in list(schema["tables"]) + ["official_sources", "document_metadata"]: try: data[t] = load(root, t) except Exception as e: # noqa: BLE001 if t == "document_metadata": data[t] = [] warnings.append("document_metadata table not present (no archived documents)") else: errors.append(f"{t}: cannot read table ({e})") data[t] = [] all_ids = {} for t, spec in schema["tables"].items(): for r in data[t]: rid = r.get("id") if not rid or not re.fullmatch(re.escape(spec["id_prefix"]) + r"[A-Z0-9.\-:()]+", str(rid)): errors.append(f"{t}: malformed id {rid!r}") if rid in all_ids: errors.append(f"{t}: duplicate id {rid} (also in {all_ids[rid]})") all_ids[rid] = t src_ids = {s["source_id"] for s in data["official_sources"]} stats = {} dangling = Counter() for t, spec in schema["tables"].items(): recs = data[t] miss = {} for f in spec["fields"]: n = sum(1 for r in recs if is_missing(r.get(f)) or (isinstance(r.get(f), list) and not r.get(f))) miss[f] = round(100 * n / len(recs), 1) if recs else None ver = Counter(r.get("verification_status") for r in recs) conf = Counter(r.get("confidence") for r in recs) for r in recs: if r.get("verification_status") not in schema["enums"]["verification_status"]: errors.append(f"{r['id']}: invalid verification_status {r.get('verification_status')!r}") if r.get("confidence") not in schema["enums"]["confidence"]: errors.append(f"{r['id']}: invalid confidence {r.get('confidence')!r}") sids = r.get("source_ids") or [] if not sids: errors.append(f"{r['id']}: no provenance (source_ids empty)") for s in sids: if s not in src_ids: errors.append(f"{r['id']}: cites unknown source {s}") for f in spec["date_fields"]: v = r.get(f) if not is_missing(v) and not DATE_RE.match(str(v)): warnings.append(f"{r['id']}: {f} not ISO 8601: {v!r}") for f, target in spec["refs"].items(): vals = r.get(f) if isinstance(r.get(f), list) else [r.get(f)] for v in vals: if is_missing(v) or not re.match(r"^(ORG|SCH|STD|REG|PRO|DEC|PROC|REL)-", str(v)): continue if v not in all_ids: dangling[(t, f)] += 1 warnings.append(f"{r['id']}: {f} -> {v} has no record") elif target != "*" and all_ids[v] != target: warnings.append(f"{r['id']}: {f} -> {v} is a {all_ids[v]} record, expected {target}") stats[t] = {"records": len(recs), "missing_pct": miss, "verification": dict(ver), "confidence": dict(conf), "mean_sources_per_record": round(sum(len(r.get("source_ids") or []) for r in recs) / len(recs), 2) if recs else 0} srcs = data["official_sources"] for s in srcs: if not re.match(r"^https?://[^\s]+$", str(s.get("url"))): errors.append(f"{s['source_id']}: malformed URL {s.get('url')!r}") url_status = Counter(s.get("url_check_status") for s in srcs) lic = Counter(s.get("licence_category") for s in srcs) docs = data["document_metadata"] for d in docs: p = root / d["local_path"] if not p.exists(): errors.append(f"{d['doc_id']}: archived file missing: {d['local_path']}") elif hashlib.sha256(p.read_bytes()).hexdigest() != d["sha256"]: errors.append(f"{d['doc_id']}: SHA-256 mismatch for {d['local_path']}") if d.get("licence_category") != "redistributable": errors.append(f"{d['doc_id']}: archived document is not marked redistributable") result = {"errors": errors, "warning_count": len(warnings), "warnings_sample": warnings[:200], "tables": stats, "sources": {"count": len(srcs), "url_check": dict(url_status), "licence": dict(lic)}, "documents": {"count": len(docs)}, "dangling_references": {f"{t}.{f}": n for (t, f), n in dangling.items()}} if args.json: Path(args.json).write_text(json.dumps(result, indent=1, ensure_ascii=False), "utf-8") if args.report: lines = ["# Data quality report", "", f"Research cut-off: {schema['research_cutoff']}. Generated by `scripts/validate_dataset.py`.", "", f"**Errors: {len(errors)}** ยท Warnings: {len(warnings)}", "", "## Records per table", "", "| Table | Records | Verified (primary) | Verified (secondary) | Snippet only | Unverified | High confidence | Mean sources/record |", "|---|---|---|---|---|---|---|---|"] for t, s in stats.items(): v, c, n = s["verification"], s["confidence"], s["records"] or 1 pct = lambda x: f"{x} ({round(100 * x / n)}%)" # noqa: E731 lines.append(f"| {t} | {s['records']} | {pct(v.get('verified_primary', 0))} | {pct(v.get('verified_secondary', 0))} | " f"{pct(v.get('snippet_only', 0))} | {pct(v.get('unverified', 0))} | {pct(c.get('high', 0))} | {s['mean_sources_per_record']} |") lines += ["", f"Sources: {len(srcs)} unique URLs. Licence: " + ", ".join(f"{k} {v}" for k, v in lic.items()) + ". URL check: " + ", ".join(f"{k} {v}" for k, v in url_status.items()) + f". Archived documents: {len(docs)}.", "", "## Missing-data percentage by field", "", "Share of records where the field is `unknown`, `not_publicly_available`, `not_applicable` or empty.", ""] for t, s in stats.items(): lines.append(f"### {t}\n") lines.append("| Field | Missing % |\n|---|---|") lines += [f"| {f} | {p} |" for f, p in s["missing_pct"].items()] lines.append("") if dangling: lines += ["## References to IDs without their own record", "", "These IDs are cited (e.g. as an owner or related standard) but were not researched as records; they remain valid identifiers.", "", "| Table.field | Count |", "|---|---|"] + [f"| {t}.{f} | {n} |" for (t, f), n in dangling.most_common()] if errors: lines += ["", "## Errors", ""] + [f"- {e}" for e in errors[:300]] Path(args.report).write_text("\n".join(lines) + "\n", "utf-8") print(json.dumps({"errors": len(errors), "warnings": len(warnings), "records": {t: s["records"] for t, s in stats.items()}, "sources": len(srcs), "documents": len(docs)}, indent=1)) for e in errors[:20]: print("ERROR", e) sys.exit(1 if errors else 0) if __name__ == "__main__": main()