utdr-dataset-toolkit / scripts /validate_public_release.py
cmdr-chara
Publish source-free UTDR dataset toolkit
ff0ca4d
Raw
History Blame Contribute Delete
4.92 kB
#!/usr/bin/env python3
"""Validate the deliberately source-free public toolkit release."""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
SPLITS = ("train", "validation", "test")
REQUIRED_FILES = (
"README.md",
"LICENSE",
"NOTICE.md",
"metrics/private_release_summary.json",
"schemas/chat-example.schema.json",
"docs/methodology.md",
"docs/private-source-boundary.md",
"docs/validation-summary.md",
)
PROHIBITED_SUFFIXES = {
".zip",
".gml",
".png",
".jpg",
".jpeg",
".gif",
".webp",
".wav",
".ogg",
".mp3",
".flac",
}
PROHIBITED_DATA_FIELDS = {"raw_excerpt", "source_text", "image_bytes", "audio_bytes"}
EXPECTED_ROLES = ("system", "user", "assistant")
def normalized_digest(value: object) -> str:
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True)
normalized = " ".join(encoded.lower().split())
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
def load_jsonl(path: Path) -> list[dict]:
rows: list[dict] = []
with path.open(encoding="utf-8-sig") as handle:
for line_number, line in enumerate(handle, 1):
if not line.strip():
continue
try:
row = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{line_number}: invalid JSON: {exc}") from exc
if not isinstance(row, dict):
raise ValueError(f"{path}:{line_number}: row must be an object")
rows.append(row)
if not rows:
raise ValueError(f"{path}: split is empty")
return rows
def validate_row(path: Path, index: int, row: dict) -> None:
label = f"{path}:{index}"
if row.get("synthetic") is not True:
raise ValueError(f"{label}: every public row must be explicitly synthetic")
if not isinstance(row.get("id"), str) or not row["id"].strip():
raise ValueError(f"{label}: missing id")
if not isinstance(row.get("task"), str) or not row["task"].strip():
raise ValueError(f"{label}: missing task")
if PROHIBITED_DATA_FIELDS.intersection(row):
raise ValueError(f"{label}: contains a prohibited private-source field")
messages = row.get("messages")
if not isinstance(messages, list) or len(messages) != len(EXPECTED_ROLES):
raise ValueError(f"{label}: messages must contain system, user, and assistant")
roles = tuple(message.get("role") for message in messages if isinstance(message, dict))
if roles != EXPECTED_ROLES:
raise ValueError(f"{label}: unexpected role sequence {roles}")
for message in messages:
if not isinstance(message.get("content"), str) or not message["content"].strip():
raise ValueError(f"{label}: message content must be non-empty text")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
args = parser.parse_args()
root = args.root.resolve()
errors: list[str] = []
for relative in REQUIRED_FILES:
if not (root / relative).is_file():
errors.append(f"missing required file: {relative}")
prohibited = [
path.relative_to(root).as_posix()
for path in root.rglob("*")
if path.is_file() and path.suffix.lower() in PROHIBITED_SUFFIXES
]
if prohibited:
errors.append("prohibited extracted/binary files: " + ", ".join(prohibited[:10]))
seen_ids: set[str] = set()
fingerprints: dict[str, str] = {}
counts: dict[str, int] = {}
for split in SPLITS:
path = root / "data" / "synthetic" / f"{split}.jsonl"
try:
rows = load_jsonl(path)
counts[split] = len(rows)
for index, row in enumerate(rows, 1):
validate_row(path.relative_to(root), index, row)
row_id = row["id"]
if row_id in seen_ids:
raise ValueError(f"duplicate id: {row_id}")
seen_ids.add(row_id)
fingerprint = normalized_digest(row["messages"])
if fingerprint in fingerprints:
raise ValueError(
f"cross-split duplicate: {row_id} matches {fingerprints[fingerprint]}"
)
fingerprints[fingerprint] = row_id
except (OSError, ValueError) as exc:
errors.append(str(exc))
if errors:
print("PUBLIC_RELEASE_VALIDATION=FAIL")
for error in errors:
print(f"- {error}")
return 1
print("PUBLIC_RELEASE_VALIDATION=PASS")
print("synthetic_rows=" + str(sum(counts.values())))
print("split_counts=" + json.dumps(counts, sort_keys=True))
print("prohibited_files=0")
return 0
if __name__ == "__main__":
sys.exit(main())