from __future__ import annotations import hashlib from collections import Counter from pathlib import Path from PIL import Image from .io import image_path, metadata_path, read_json, read_jsonl REQUIRED_FIELDS = { "id", "file_name", "dimension_id", "dimension_name", "task_group_id", "task_group_name", "task_name", "user_prompt", "last_frame_goal", "progress_goal", "foreground_rule", "background_rule", "implicit_rule", "has_progress_goal", "image_width", "image_height", "image_mode", "image_sha256", } def file_sha256(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 validate_dataset(dataset_root: str | Path, verify_hashes: bool = True) -> dict: root = Path(dataset_root) rows = read_jsonl(metadata_path(root)) taxonomy = read_json(root / "taxonomy.json") errors: list[str] = [] warnings: list[str] = [] if len(rows) != 380: errors.append(f"Expected 380 metadata rows, found {len(rows)}") ids = [row.get("id") for row in rows] if ids != list(range(380)): errors.append("IDs are not the contiguous ordered range 0..379") groups = Counter() dimensions = Counter() for row in rows: missing = REQUIRED_FIELDS - set(row) if missing: errors.append(f"id={row.get('id')}: missing fields {sorted(missing)}") continue groups[row["task_group_id"]] += 1 dimensions[row["dimension_id"]] += 1 if row["has_progress_goal"] != bool(row["progress_goal"]): errors.append(f"id={row['id']}: progress-goal flag is inconsistent") path = image_path(root, row) if not path.is_file(): errors.append(f"id={row['id']}: missing image {path}") continue try: with Image.open(path) as image: if image.size != (row["image_width"], row["image_height"]): errors.append(f"id={row['id']}: image dimensions do not match metadata") if image.mode != row["image_mode"]: errors.append(f"id={row['id']}: image mode does not match metadata") image.verify() except Exception as exc: errors.append(f"id={row['id']}: invalid image: {exc}") if verify_hashes and file_sha256(path) != row["image_sha256"]: errors.append(f"id={row['id']}: SHA-256 mismatch") if len(groups) != 38: errors.append(f"Expected 38 task groups, found {len(groups)}") for group_id, count in sorted(groups.items()): if count != 10: errors.append(f"{group_id}: expected 10 rows, found {count}") if len(dimensions) != 9: errors.append(f"Expected 9 dimensions, found {len(dimensions)}") if taxonomy.get("num_task_groups") != len(groups): errors.append("taxonomy.json task-group count does not match metadata") return { "ok": not errors, "num_rows": len(rows), "num_task_groups": len(groups), "num_dimensions": len(dimensions), "errors": errors, "warning_summary": {}, "warnings": warnings[:20], }