Datasets:
Download release/scripts/validate_public_release.py from NaturalDAO/pol2-score-v2: direct link, hf CLI and curl.
- Browser
- Download file 7.72 kB
-
https://huggingface.co/datasets/NaturalDAO/pol2-score-v2/resolve/main/release/scripts/validate_public_release.py
- Command line
-
hf download hf://datasets/NaturalDAO/pol2-score-v2/release/scripts/validate_public_release.py
-
curl -L -o validate_public_release.py https://huggingface.co/datasets/NaturalDAO/pol2-score-v2/resolve/main/release/scripts/validate_public_release.py
7.72 kB
| #!/usr/bin/env python3 | |
| """Validate structure, labels, cross-format parity, hashes and holdout exclusion.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| PATTERNS = { | |
| "email": re.compile(r"[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}"), | |
| "phone_cn": re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)"), | |
| "id_cn": re.compile(r"(?<!\d)\d{17}[0-9Xx](?!\d)"), | |
| "url": re.compile(r"https?://\S+"), | |
| } | |
| IGNORED_STRING_KEYS = {"case_id", "family_id", "unit_id", "source_sha", "question_sha", "source_run"} | |
| PAIRS = [ | |
| ("data/pol2-specialist/laya/train-m0.jsonl", "data/pol2-specialist/kev/train-m0.jsonl"), | |
| ("data/pol2-specialist/laya/validation.jsonl", "data/pol2-specialist/kev/validation.jsonl"), | |
| ("data/pol2-specialist/laya/calibration.jsonl", "data/pol2-specialist/kev/calibration.jsonl"), | |
| ("data/pol2-specialist/laya/score-dev.jsonl", "data/pol2-specialist/kev/score-dev.jsonl"), | |
| ("data/pol2-specialist/score-v2-new-units/laya.jsonl", "data/pol2-specialist/score-v2-new-units/kev.jsonl"), | |
| ("data/general-replay/laya/train-m10.jsonl", "data/general-replay/kev/train-m10.jsonl"), | |
| ("data/general-replay/laya/train-m25.jsonl", "data/general-replay/kev/train-m25.jsonl"), | |
| ("data/general-replay/laya/train-m40.jsonl", "data/general-replay/kev/train-m40.jsonl"), | |
| ("data/general-replay/laya/validation.jsonl", "data/general-replay/kev/validation.jsonl"), | |
| ("data/general-replay/laya/guard.jsonl", "data/general-replay/kev/guard.jsonl"), | |
| ("data/mixed-training/laya-m10.jsonl", "data/mixed-training/kev-m10.jsonl"), | |
| ] | |
| def sha(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def load(path: Path) -> list[dict]: | |
| rows = [] | |
| with path.open(encoding="utf-8") as handle: | |
| for number, line in enumerate(handle, 1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| rows.append(json.loads(line)) | |
| except Exception as exc: | |
| raise AssertionError(f"{path}:{number}: invalid JSON: {exc}") from exc | |
| return rows | |
| def strings(value, path=()): | |
| if isinstance(value, dict): | |
| for key, child in value.items(): | |
| if key not in IGNORED_STRING_KEYS: | |
| yield from strings(child, path + (key,)) | |
| elif isinstance(value, list): | |
| for child in value: | |
| yield from strings(child, path) | |
| elif isinstance(value, str): | |
| yield ".".join(path), value | |
| def decoded(row: dict) -> tuple[dict, dict, dict]: | |
| state = json.loads(row["state"]) if isinstance(row["state"], str) else row["state"] | |
| questions = json.loads(row["questions"]) if isinstance(row["questions"], str) else row["questions"] | |
| gold = json.loads(row["gold"]) if isinstance(row.get("gold"), str) else row.get("gold") | |
| return state, questions, gold | |
| def one_hot(values: dict) -> bool: | |
| return bool(values) and all(float(v) in (0.0, 1.0) for v in values.values()) and sum(float(v) for v in values.values()) == 1.0 | |
| def normalize_label(qtype: str, label): | |
| if qtype == "score": | |
| return str(int(label)) | |
| if qtype == "noul": | |
| if isinstance(label, str): | |
| return label.lower() == "true" | |
| return bool(label) | |
| return str(label) | |
| def check_answers(row: dict, path: str) -> None: | |
| _, questions, gold = decoded(row) | |
| assert isinstance(questions, dict) and questions, f"{path}: no questions" | |
| for qid, q in questions.items(): | |
| assert q.get("type") in {"choice", "score", "noul"}, f"{path}:{qid}: bad type" | |
| assert q.get("instructions"), f"{path}:{qid}: missing instructions" | |
| if q["type"] in {"choice", "score"}: | |
| assert isinstance(q.get("criteria"), (dict, list)), f"{path}:{qid}: missing criteria" | |
| if gold is not None: | |
| assert qid in gold, f"{path}:{qid}: missing gold" | |
| label = gold[qid].get("label") | |
| probabilities = gold[qid].get("probabilities") | |
| assert probabilities is not None and one_hot(probabilities), f"{path}:{qid}: non-one-hot gold" | |
| winner = sorted(probabilities, key=lambda key: float(probabilities[key]), reverse=True)[0] | |
| assert str(winner) == str(label) or (q["type"] == "noul" and str(label).lower() == str(winner).lower()), f"{path}:{qid}: label mismatch" | |
| else: | |
| assert "label" in q and "target" in q, f"{path}:{qid}: missing Kev label/target" | |
| assert one_hot(q["target"]), f"{path}:{qid}: non-one-hot Kev target" | |
| winner = sorted(q["target"], key=lambda key: float(q["target"][key]), reverse=True)[0] | |
| assert str(winner) == str(q["label"]) or (q["type"] == "noul" and str(q["label"]).lower() == str(winner).lower()), f"{path}:{qid}: Kev label mismatch" | |
| def question_view(row: dict) -> tuple[dict, dict, dict]: | |
| state, questions, gold = decoded(row) | |
| labels = {} | |
| normalized = {} | |
| for qid, q in questions.items(): | |
| normalized[qid] = { | |
| "type": q.get("type"), | |
| "instructions": q.get("instructions"), | |
| "criteria": q.get("criteria"), | |
| } | |
| if gold is not None: | |
| labels[qid] = normalize_label(q["type"], gold[qid]["label"]) | |
| else: | |
| labels[qid] = normalize_label(q["type"], q["label"]) | |
| return state, normalized, labels | |
| def main() -> None: | |
| manifest = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8")) | |
| listed = set(manifest["files"]) | |
| listed_jsonl = {relative for relative in listed if relative.endswith(".jsonl")} | |
| actual_jsonl = {str(path.relative_to(ROOT)) for path in ROOT.rglob("*.jsonl") if path.is_file()} | |
| assert listed_jsonl == actual_jsonl, f"manifest/file mismatch: missing={actual_jsonl-listed_jsonl}, extra={listed_jsonl-actual_jsonl}" | |
| assert not any("blind" in path.lower() or "sealed" in path.lower() for path in listed) | |
| total_rows = 0 | |
| warnings = [] | |
| for relative, expected in manifest["files"].items(): | |
| path = ROOT / relative | |
| assert path.stat().st_size == expected["bytes"], relative | |
| assert sha(path) == expected["sha256"], relative | |
| if path.suffix != ".jsonl": | |
| continue | |
| rows = load(path) | |
| assert len(rows) == expected["rows"], relative | |
| total_rows += len(rows) | |
| for number, row in enumerate(rows, 1): | |
| if "/lineage/" not in relative: | |
| check_answers(row, f"{relative}:{number}") | |
| for field, text in strings(row): | |
| for kind, pattern in PATTERNS.items(): | |
| for match in pattern.findall(text): | |
| warnings.append((relative, number, field, kind, match)) | |
| assert not warnings, f"privacy-pattern candidates: {warnings[:10]}" | |
| for left, right in PAIRS: | |
| a = load(ROOT / left) | |
| b = load(ROOT / right) | |
| assert len(a) == len(b), (left, right) | |
| for index, (x, y) in enumerate(zip(a, b), 1): | |
| sx, qx, lx = question_view(x) | |
| sy, qy, ly = question_view(y) | |
| assert sx == sy, f"{left}:{index} state mismatch" | |
| assert qx == qy, f"{left}:{index} question mismatch" | |
| assert lx == ly, f"{left}:{index} label mismatch" | |
| print(json.dumps({ | |
| "status": "PASS", | |
| "files": len(listed), | |
| "jsonl_rows": total_rows, | |
| "format_pairs": len(PAIRS), | |
| "blind_files_included": False, | |
| "privacy_pattern_candidates": 0, | |
| }, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |