#!/usr/bin/env python3 """Strictly validate a portable YOLO detection dataset before training.""" from __future__ import annotations import argparse import json from collections import Counter, defaultdict from pathlib import Path import cv2 import yaml IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} def load_names(value: object) -> dict[int, str]: if isinstance(value, list): return {i: str(name) for i, name in enumerate(value)} if isinstance(value, dict): return {int(key): str(name) for key, name in value.items()} raise ValueError("data.yaml names must be a list or mapping") def split_root(dataset_root: Path, value: str) -> Path: path = Path(value) return path if path.is_absolute() else dataset_root / path def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", type=Path, required=True) parser.add_argument("--report", type=Path) parser.add_argument("--skip-image-decode", action="store_true") args = parser.parse_args() data_path = args.data.resolve() raw = yaml.safe_load(data_path.read_text(encoding="utf-8")) root_value = raw.get("path") dataset_root = Path(root_value).expanduser() if root_value else data_path.parent if not dataset_root.is_absolute(): dataset_root = (data_path.parent / dataset_root).resolve() names = load_names(raw.get("names")) if names != {0: "player", 1: "npc", 2: "attack_object"}: raise SystemExit(f"unexpected class map: {names}") errors: list[str] = [] split_stats: dict[str, dict] = {} stems_by_split: dict[str, set[str]] = {} class_counts: Counter[str] = Counter() for split in ("train", "val", "test"): if not raw.get(split): continue image_root = split_root(dataset_root, str(raw[split])).resolve() images = sorted(path for path in image_root.rglob("*") if path.suffix.lower() in IMAGE_SUFFIXES) label_root = dataset_root / "labels" / split labels = sorted(label_root.glob("*.txt")) if label_root.is_dir() else [] image_stems = {path.stem for path in images} label_stems = {path.stem for path in labels} for stem in sorted(image_stems - label_stems)[:20]: errors.append(f"{split}: missing label for {stem}") for stem in sorted(label_stems - image_stems)[:20]: errors.append(f"{split}: orphan label {stem}") empty = 0 objects = 0 for image in images: if not args.skip_image_decode: decoded = cv2.imread(str(image)) if decoded is None or decoded.size == 0: errors.append(f"{split}: undecodable image {image}") label = label_root / f"{image.stem}.txt" if not label.is_file(): continue lines = [line.strip() for line in label.read_text(encoding="utf-8").splitlines() if line.strip()] if not lines: empty += 1 for line_number, line in enumerate(lines, 1): fields = line.split() if len(fields) != 5: errors.append(f"{label}:{line_number}: expected 5 fields") continue try: class_id = int(fields[0]) cx, cy, width, height = map(float, fields[1:]) except ValueError: errors.append(f"{label}:{line_number}: non-numeric field") continue if class_id not in names: errors.append(f"{label}:{line_number}: invalid class {class_id}") if not (0 <= cx <= 1 and 0 <= cy <= 1 and 0 < width <= 1 and 0 < height <= 1): errors.append(f"{label}:{line_number}: invalid normalized box") if cx - width / 2 < -1e-5 or cx + width / 2 > 1 + 1e-5: errors.append(f"{label}:{line_number}: x extent outside image") if cy - height / 2 < -1e-5 or cy + height / 2 > 1 + 1e-5: errors.append(f"{label}:{line_number}: y extent outside image") if class_id in names: class_counts[names[class_id]] += 1 objects += 1 stems_by_split[split] = image_stems split_stats[split] = { "images": len(images), "labels": len(labels), "empty_labels": empty, "objects": objects, } splits = sorted(stems_by_split) for i, left in enumerate(splits): for right in splits[i + 1 :]: overlap = stems_by_split[left] & stems_by_split[right] if overlap: errors.append(f"stem leakage {left}/{right}: {sorted(overlap)[:5]}") manifest = dataset_root / "export_manifest.jsonl" source_splits: defaultdict[str, set[str]] = defaultdict(set) if manifest.is_file(): for line_number, line in enumerate(manifest.read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue row = json.loads(line) source = str(row["relative_video_path"]).split("/", 1)[0] source_splits[source].add(str(row["split"])) leaked = {key: sorted(value) for key, value in source_splits.items() if len(value) > 1} if leaked: errors.append(f"recording-source split leakage: {dict(list(leaked.items())[:5])}") report = { "valid": not errors, "data": str(data_path), "dataset_root": str(dataset_root), "classes": names, "splits": split_stats, "class_objects": dict(class_counts), "source_split_leakage": 0 if not any("source split leakage" in e for e in errors) else 1, "errors": errors[:100], } output = json.dumps(report, ensure_ascii=False, indent=2) + "\n" print(output, end="") if args.report: args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(output, encoding="utf-8") if errors: raise SystemExit(f"dataset verification failed with {len(errors)} error(s)") if __name__ == "__main__": main()