Datasets:
Download scripts/validate_dataset.py from ReyChiaro/SmoothStyle: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/ReyChiaro/SmoothStyle/resolve/refs%2Fpr%2F2/scripts/validate_dataset.py
- Command line
-
hf download hf://datasets/ReyChiaro/SmoothStyle@refs/pr/2/scripts/validate_dataset.py
-
curl -L -o validate_dataset.py https://huggingface.co/datasets/ReyChiaro/SmoothStyle/resolve/refs%2Fpr%2F2/scripts/validate_dataset.py
10.2 kB
| #!/usr/bin/env python3 | |
| """Validate a built SmoothStyle repository.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from typing import Any | |
| from PIL import Image | |
| IMAGE_FIELDS = ("content_file_name", "style_file_name", "target_file_name") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument("--skip-images", action="store_true") | |
| parser.add_argument("--skip-checksums", action="store_true") | |
| parser.add_argument("--huggingface", action="store_true") | |
| return parser.parse_args() | |
| def load_json(path: Path) -> Any: | |
| with path.open("r", encoding="utf-8") as handle: | |
| return json.load(handle) | |
| def load_jsonl(path: Path) -> list[dict[str, Any]]: | |
| rows = [] | |
| with path.open("r", encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, 1): | |
| try: | |
| value = json.loads(line) | |
| except json.JSONDecodeError as error: | |
| raise ValueError(f"Invalid JSON at {path}:{line_number}: {error}") from error | |
| if not isinstance(value, dict): | |
| raise ValueError(f"Expected object at {path}:{line_number}") | |
| rows.append(value) | |
| return rows | |
| def safe_resolve(split_root: Path, relative_name: str) -> Path: | |
| path = (split_root / relative_name).resolve() | |
| try: | |
| path.relative_to(split_root.resolve()) | |
| except ValueError as error: | |
| raise ValueError(f"Image path escapes split directory: {relative_name}") from error | |
| return path | |
| def validate_image(path: Path) -> None: | |
| with Image.open(path) as image: | |
| image.verify() | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def validate_checksums(root: Path) -> int: | |
| checksum_path = root / "metadata" / "checksums.sha256" | |
| entries: list[tuple[str, Path]] = [] | |
| with checksum_path.open("r", encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, 1): | |
| digest, separator, relative_name = line.rstrip("\n").partition(" ") | |
| if not separator or len(digest) != 64: | |
| raise ValueError(f"Invalid checksum line {line_number}") | |
| path = (root / relative_name).resolve() | |
| try: | |
| path.relative_to(root.resolve()) | |
| except ValueError as error: | |
| raise ValueError(f"Checksum path escapes repository: {relative_name}") from error | |
| if not path.is_file(): | |
| raise FileNotFoundError(path) | |
| entries.append((digest, path)) | |
| def check(entry: tuple[str, Path]) -> None: | |
| expected, path = entry | |
| actual = sha256(path) | |
| if actual != expected: | |
| raise ValueError(f"Checksum mismatch: {path}") | |
| with ThreadPoolExecutor(max_workers=8) as executor: | |
| list(executor.map(check, entries)) | |
| return len(entries) | |
| def validate_huggingface(root: Path, expected: dict[str, int]) -> None: | |
| try: | |
| from datasets import load_dataset | |
| except ImportError as error: | |
| raise RuntimeError( | |
| "The optional Hugging Face check requires the 'datasets' package" | |
| ) from error | |
| dataset = load_dataset("imagefolder", data_dir=str(root / "data")) | |
| if set(dataset) != set(expected): | |
| raise ValueError(f"Unexpected Hugging Face splits: {sorted(dataset)}") | |
| for split, expected_rows in expected.items(): | |
| if len(dataset[split]) != expected_rows: | |
| raise ValueError( | |
| f"Hugging Face row mismatch for {split}: " | |
| f"{len(dataset[split])} != {expected_rows}" | |
| ) | |
| expected_features = { | |
| "content", | |
| "content_id", | |
| "generator", | |
| "id", | |
| "pair_id", | |
| "strength", | |
| "strength_id", | |
| "style", | |
| "style_id", | |
| "style_source", | |
| "target", | |
| } | |
| actual_features = set(dataset[split].features) | |
| if actual_features != expected_features: | |
| raise ValueError( | |
| f"Unexpected Hugging Face features for {split}: " | |
| f"{sorted(actual_features)}" | |
| ) | |
| for image_feature in ("content", "style", "target"): | |
| if dataset[split].features[image_feature].__class__.__name__ != "Image": | |
| raise ValueError( | |
| f"{split}.{image_feature} was not inferred as an Image feature" | |
| ) | |
| def main() -> None: | |
| args = parse_args() | |
| root = args.root.resolve() | |
| stats = load_json(root / "metadata" / "dataset_stats.json") | |
| split_manifest = load_json(root / "metadata" / "split_manifest.json") | |
| all_images: set[Path] = set() | |
| split_pairs: dict[str, set[str]] = {} | |
| split_contents: dict[str, set[str]] = {} | |
| split_styles: dict[str, set[str]] = {} | |
| expected_hf_rows: dict[str, int] = {} | |
| for split in ("train", "test"): | |
| split_root = root / "data" / split | |
| rows = load_jsonl(split_root / "metadata.jsonl") | |
| expected_rows = stats["splits"][split]["examples"] | |
| if len(rows) != expected_rows: | |
| raise ValueError(f"{split} row count {len(rows)} != {expected_rows}") | |
| expected_hf_rows[split] = expected_rows | |
| ids: set[str] = set() | |
| pair_strengths: set[tuple[str, int]] = set() | |
| pairs: set[str] = set() | |
| contents: set[str] = set() | |
| styles: set[str] = set() | |
| referenced: set[Path] = set() | |
| for row in rows: | |
| required = { | |
| "id", | |
| "pair_id", | |
| "content_id", | |
| "style_id", | |
| "strength_id", | |
| "strength", | |
| *IMAGE_FIELDS, | |
| } | |
| missing = required - set(row) | |
| if missing: | |
| raise ValueError(f"Missing fields in {split}: {sorted(missing)}") | |
| if row["id"] in ids: | |
| raise ValueError(f"Duplicate sample ID: {row['id']}") | |
| ids.add(row["id"]) | |
| strength_id = row["strength_id"] | |
| if strength_id not in range(1, 11): | |
| raise ValueError(f"Invalid strength ID: {strength_id}") | |
| if abs(row["strength"] - strength_id / 10.0) > 1e-12: | |
| raise ValueError(f"Invalid scalar strength: {row}") | |
| pair_strength = (row["pair_id"], strength_id) | |
| if pair_strength in pair_strengths: | |
| raise ValueError(f"Duplicate pair/strength: {pair_strength}") | |
| pair_strengths.add(pair_strength) | |
| expected_pair = f"{row['content_id']}_{row['style_id']}" | |
| if row["pair_id"] != expected_pair: | |
| raise ValueError(f"Pair ID mismatch: {row}") | |
| pairs.add(row["pair_id"]) | |
| contents.add(row["content_id"]) | |
| styles.add(row["style_id"]) | |
| for field in IMAGE_FIELDS: | |
| path = safe_resolve(split_root, row[field]) | |
| if not path.is_file(): | |
| raise FileNotFoundError(path) | |
| referenced.add(path) | |
| all_images.add(path) | |
| for pair in pairs: | |
| strengths = { | |
| strength for candidate, strength in pair_strengths if candidate == pair | |
| } | |
| if strengths != set(range(1, 11)): | |
| raise ValueError(f"Incomplete target strengths for {split}/{pair}") | |
| actual_images = {path.resolve() for path in split_root.rglob("*.jpg")} | |
| if actual_images != referenced: | |
| missing_from_index = sorted(actual_images - referenced) | |
| missing_from_disk = sorted(referenced - actual_images) | |
| raise ValueError( | |
| f"Image/index mismatch for {split}: " | |
| f"unindexed={missing_from_index[:5]}, absent={missing_from_disk[:5]}" | |
| ) | |
| split_pairs[split] = pairs | |
| split_contents[split] = contents | |
| split_styles[split] = styles | |
| if split_pairs["train"] & split_pairs["test"]: | |
| raise ValueError("Train/test pair overlap detected") | |
| if split_contents["train"] & split_contents["test"]: | |
| raise ValueError("Train/test content overlap detected") | |
| manifest_train = set(split_manifest["train_pair_ids"]) | |
| manifest_test = set(split_manifest["test_pair_ids"]) | |
| if manifest_train != split_pairs["train"] or manifest_test != split_pairs["test"]: | |
| raise ValueError("Split manifest does not match metadata rows") | |
| expected_style_overlap = stats["totals"]["style_ids_shared_between_splits"] | |
| actual_style_overlap = len(split_styles["train"] & split_styles["test"]) | |
| if actual_style_overlap != expected_style_overlap: | |
| raise ValueError( | |
| f"Style overlap mismatch: {actual_style_overlap} != {expected_style_overlap}" | |
| ) | |
| provenance = load_jsonl(root / "metadata" / "sources.jsonl") | |
| provenance_assets = {root / row["asset_id"] for row in provenance} | |
| if {path.resolve() for path in provenance_assets} != all_images: | |
| raise ValueError("Provenance index does not cover exactly the published images") | |
| if not args.skip_images: | |
| with ThreadPoolExecutor(max_workers=8) as executor: | |
| list(executor.map(validate_image, sorted(all_images))) | |
| checksum_count = 0 | |
| if not args.skip_checksums: | |
| checksum_count = validate_checksums(root) | |
| if args.huggingface: | |
| validate_huggingface(root, expected_hf_rows) | |
| result = { | |
| "status": "ok", | |
| "examples": sum(expected_hf_rows.values()), | |
| "images": len(all_images), | |
| "style_ids_shared_between_splits": actual_style_overlap, | |
| "checksums_verified": checksum_count, | |
| "image_decoding_verified": not args.skip_images, | |
| "huggingface_loader_verified": args.huggingface, | |
| } | |
| print(json.dumps(result, indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() | |