File size: 10,244 Bytes
917565f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/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()