File size: 20,557 Bytes
10ed3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python3
"""Validate the fixed FreiHAND migration; media decoding is a separate gate."""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path

import torch

from bundle_io import LAYOUT, PROFILE, ViewReader, safe_path
from fetch_shared_subset import REPO, REVISION, PREFIX, file_digests, json_write, verified
from migrate_freihand import check_field, validate_view

SOURCE_MANIFEST_SHA256 = "1b846defe770c148761b1918cccb8369fd7fdc5f661142d0a9ed250bb9867c9d"
REGISTRY_SHA256 = "9f3769f950b36f75f3d571c77b5a661ca8e72afae20c9f1ddd1deef140e6cca8"
NUMERIC_SCHEMAS = {"intrinsic": "camera/pinhole/v1", "keypoints_xyz": "keypoints/xyz/v1", "mano": "mano/axis_angle61/v1"}
AXES = {"intrinsic": ["T", "row", "column"], "keypoints_xyz": ["T", "hand", "joint", "coordinate"],
        "mano": ["T", "hand", "parameter"], "rgb": ["T", "height", "width", "channel"], "segment": ["T", "height", "width"]}


def canonical_hash(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()


def require_fields(value, fields, label):
    if not isinstance(value, dict) or not set(fields).issubset(value):
        missing = set(fields) - set(value) if isinstance(value, dict) else set(fields)
        raise ValueError(f"{label}: missing required fields {sorted(missing)}")


def expected_views():
    return {f"training_{start:08d}": ("train", start, min(4096, 130240-start)) for start in range(0, 130240, 4096)} | {"evaluation_00000000": ("test", 0, 3960)}


def check_source_manifest(manifest):
    if (manifest.get("repo"), manifest.get("revision"), manifest.get("source_prefix")) != (REPO, REVISION, PREFIX.rstrip("/")):
        raise ValueError("Wrong fixed source repository/revision/prefix")
    if canonical_hash(manifest) != SOURCE_MANIFEST_SHA256:
        raise ValueError("Source manifest differs from the audited immutable file inventory")


def check_source_tree(source, manifest):
    """Re-authenticate the numerical baseline once, not once per view."""
    check_source_manifest(manifest)
    entries = [item for item in manifest["files"] if item["download"]]
    for item in entries:
        verified(safe_path(source, item["relative_path"]), item)
    return len(entries)


def check_complete_media(release, reused_paths):
    for name in sorted(reused_paths):
        if not safe_path(release, name).is_file():
            raise FileNotFoundError(f"Required reused media is missing: {name}")


def check_plan(release, plan):
    """Authenticate the source inventory, then check the entire declared file set."""
    if (plan.get("repo"), plan.get("revision"), plan.get("source_prefix"), plan.get("target_prefix")) != (REPO, REVISION, PREFIX.rstrip("/"), "FreiHAND/shared-v1.1"):
        raise ValueError("Wrong assembly plan repository/revision/prefix")
    manifest = plan.get("source_manifest", {})
    check_source_manifest(manifest)
    original = {item["relative_path"]: item for item in manifest["files"]}
    expected_reuse = {name: item for name, item in original.items() if not item["download"]}
    reuse_rows = plan.get("reuse_unchanged", [])
    reuse = {item["relative_path"]: item for item in reuse_rows}
    if len(reuse) != len(reuse_rows) or reuse != expected_reuse:
        raise ValueError("Media reuse plan differs from the fixed source inventory")
    replacements = {f"data/{seq}/camera/{name}" for seq in expected_views() for name in (
        "camera/intrinsic.pt", "camera/intrinsic_valid.pt", "annotation/mano/motion.pt",
        "annotation/mano/motion_valid.pt", "annotation/keypoints/xyz.pt", "annotation/keypoints/xyz_valid.pt")}
    if set(plan.get("remove_only_after_verification", [])) != replacements or len(plan.get("remove_only_after_verification", [])) != len(replacements):
        raise ValueError("Old numerical-file removal list differs from the fixed layout")
    rows = plan.get("files", [])
    files = {item["relative_path"]: item for item in rows}
    if not files or len(files) != len(rows) or files.keys() & reuse.keys():
        raise ValueError("Invalid overlay file manifest")
    for name in files.keys() | reuse.keys():
        safe_path(release, name)
    if set(original) - replacements - set(reuse) - set(files):
        raise ValueError("Source files are missing from the assembly plan")
    actual = {p.relative_to(release).as_posix() for p in release.rglob("*") if p.is_file() and "__pycache__" not in p.parts}
    if not set(files).issubset(actual) or actual - set(files) - set(reuse):
        raise ValueError("Release file set does not match the assembly plan")
    for name, item in files.items():
        digest = file_digests(release / name)
        if any(digest[k] != item[k] for k in ("size", "sha256", "git_blob_sha1")):
            raise ValueError(f"Delivery digest changed: {name}")
    for name in actual & set(reuse):
        verified(release / name, reuse[name])
    if (plan.get("source_file_count"), plan.get("overlay_file_count"), plan.get("expected_assembled_file_count")) != (len(original), len(files), len(files)+len(reuse)):
        raise ValueError("Assembly plan file counts disagree")
    if plan.get("overlay_bytes") != sum(item["size"] for item in files.values()):
        raise ValueError("Assembly plan byte count disagrees")
    return set(reuse), {"source_bound": True, "overlay_hashes": len(files), "reused_media_hashes": len(actual & set(reuse))}


def check_metadata(meta, view, registry):
    require_fields(meta, registry["view_metadata"]["required_fields"], "view metadata")
    seq = view.parent.name
    if seq not in expected_views() or view.name != "camera":
        raise ValueError("Unknown FreiHAND view")
    split, start, total = expected_views()[seq]
    if (meta["schema_version"], meta["dataset_id"], meta["release_id"], meta["sequence_id"], meta["camera_id"]) != ("hand-warehouse/1.1", "FreiHAND", "shared-v1.1", seq, "camera"):
        raise ValueError("View identity/version does not match its directory")
    if type(meta["num_frames"]) is not int or meta["num_frames"] != total or meta["hand_slots"] != ["left", "right"] or meta["view_type"] != "exo" or meta["split"] != split:
        raise ValueError("Frame count/hand slots/view type/split mismatch")
    prefix = "training" if split == "train" else "evaluation"
    archive = "raw/data/FreiHAND_pub_v2.zip" if split == "train" else "raw/data/FreiHAND_pub_v2_eval.zip"
    if meta.get("split_scheme") != "FreiHAND_official_train_evaluation" or meta.get("split_source_locator") != {"archive": archive, "member_prefix": prefix + "/"}:
        raise ValueError("Missing or wrong official split provenance")
    require_fields(meta["sampling"], {"type", "source_fps", "frames_ref", "selection", "shard_max_images"}, "sampling")
    if meta["sample_type"] != "image" or meta["sampling"].get("type") != "independent" or meta["sampling"].get("source_fps") is not None or meta["sampling"].get("frames_ref") != "camera/frames.jsonl" or meta["sampling"]["shard_max_images"] != 4096:
        raise ValueError("Independent-image sampling or frame reference mismatch")
    if meta["camera"] != {"model": "pinhole", "schema_id": "camera/pinhole/v1", "image_size": [224, 224]}:
        raise ValueError("Camera model or image size mismatch")
    if set(meta["components"]) != set(AXES):
        raise ValueError("Missing or unregistered FreiHAND component")
    required = {"available", "schema_id", "data_ref", "axes", "valid_ref", "valid_axes", "provenance", "source_locator"}
    for name, comp in meta["components"].items():
        require_fields(comp, required, name)
        schema = NUMERIC_SCHEMAS.get(name, "rgb/uint8/v1" if name == "rgb" else ("segment/foreground_intensity/v1" if split == "train" else "segment/uint16_labels/v1"))
        if comp["available"] is not True or comp["schema_id"] != schema or comp["axes"] != AXES[name]:
            raise ValueError(f"Component availability/schema/axes mismatch: {name}")
        definition = registry["components"][schema]
        require_fields(comp, definition.get("required_metadata", []), name)
        if comp.get("attributes"):
            raise ValueError("Unregistered attributes in this fixed FreiHAND release")
        for key in ("unit", "angle_unit", "coordinate_frame"):
            if key in definition and comp.get(key) != definition[key]:
                raise ValueError(f"Component {name}: wrong {key}")
        if name == "keypoints_xyz" and comp["keypoint_schema"] != "mano21/v1":
            raise ValueError("Wrong keypoint convention")
        if name in {"keypoints_xyz", "mano"} and comp.get("coordinate_frame") != "camera":
            raise ValueError(f"Component {name}: wrong coordinate_frame")
        if name == "mano" and comp.get("model_profile") != {"version": "MANO-v1.2", "flat_hand_mean": True, "left_shapedirs_fix": False}:
            raise ValueError("Wrong MANO model profile")
        valid_axes = AXES[name][:len(definition["valid_shape"])]
        if comp["valid_axes"] != valid_axes or not isinstance(comp["source_locator"], dict) or not comp["source_locator"]:
            raise ValueError(f"Wrong validity axes or missing provenance: {name}")
        if not isinstance(comp["provenance"], dict) or comp["provenance"].get("kind") not in {"source", "format_conversion", "derived"} or not comp["provenance"].get("method"):
            raise ValueError(f"Invalid provenance: {name}")
        for key in ("data_ref", "valid_ref"):
            safe_path(view, comp[key])
        if name in LAYOUT:
            continue
        if "data_key" in comp or "valid_key" in comp or comp.get("valid_storage", {}).get("profile") == PROFILE:
            raise ValueError("Media validity cannot be wrapped as a bundle")
        expected_ref = "observation/rgb.mkv" if name == "rgb" else "annotation/segment/mask.mkv"
        expected_valid = "observation/rgb_valid.pt" if name == "rgb" else "annotation/segment/mask_valid.pt"
        if (comp["data_ref"], comp["valid_ref"]) != (expected_ref, expected_valid):
            raise ValueError("Media references differ from this fixed source")
        require_fields(comp["storage"], registry["video_metadata"]["required"], "video storage")
        if comp["storage"]["profile"] not in definition["allowed_storage_profiles"] or comp["storage"]["encoded_size"] != [224, 224] or comp.get("storage_fps") != 1 or comp.get("timebase_role") != "index_only":
            raise ValueError("Wrong media storage profile/size/timebase")
        storage = comp["storage"]
        # Training foreground values came from JPEG: lossless FFV1 storage
        # does not erase that upstream lossy provenance.
        expected_encoding = ("mkv/mjpeg_copy/v1", "mjpeg", "yuvj420p", True) if name == "rgb" else ("mkv/uint16_ffv1/v1", "ffv1", "gray" if split == "train" else "gray16le", split == "train")
        if (storage["profile"], storage["codec"], storage["pixel_format"], storage["source_lossy"]) != expected_encoding:
            raise ValueError("Media encoding declaration differs from the fixed source")
    segment = meta["components"]["segment"]
    if segment.get("coverage") != {"kind": "selected_entities", "entities": ["hand_right"]} or segment.get("segmentation_type") != "semantic":
        raise ValueError("Wrong segment coverage or segmentation_type")
    if split == "train" and (segment.get("value_range") != [0, 255] or segment.get("normalization_scale") != 1/255 or segment.get("foreground_category") != "hand" or segment.get("entity_id") != "hand_right"):
        raise ValueError("Training foreground-intensity semantics changed")
    if split == "test" and segment.get("mapping_ref") != "annotation/segment/instances.jsonl":
        raise ValueError("Missing or wrong instance mapping reference")
    return split, start, total


def check_mapping(view, meta):
    comp = meta["components"]["segment"]
    if "mapping_ref" not in comp:
        return
    path = safe_path(view, comp["mapping_ref"])
    rows = [json.loads(line) for line in path.read_text().splitlines()]
    if len(rows) != meta["num_frames"]:
        raise ValueError("Instance mapping length mismatch")
    for i, row in enumerate(rows):
        if row.get("frame_index") != i or not isinstance(row.get("labels"), list) or not row["labels"]:
            raise ValueError("Invalid instance mapping row")
        seen = set()
        for label in row["labels"]:
            require_fields(label, {"mask_value", "category_id", "entity_id", "part_id", "source_instance_id"}, "instance mapping")
            code = label["mask_value"]
            if type(code) is not int or not 1 <= code <= 65534 or code in seen:
                raise ValueError("Unknown, reserved, or duplicate mapping code")
            seen.add(code)
            if label["part_id"] is not None:
                raise ValueError("Unregistered part_id in FreiHAND instance mapping")
            if code == 65534:
                if (label["category_id"], label["entity_id"], label["source_instance_id"]) != ("background", None, 0):
                    raise ValueError("Wrong background mapping")
            elif (label["category_id"], label["entity_id"], label["source_instance_id"]) != ("hand", "hand_right", code):
                raise ValueError("Wrong hand mapping")


def validate(release, source=None, overlay_plan=None, assembly_plan=None, source_manifest=None):
    torch.set_num_threads(1)
    release = Path(release)
    if overlay_plan is not None and assembly_plan is not None:
        raise ValueError("Choose either overlay or full assembly validation")
    registry_path = safe_path(release, "doc/schema.json")
    if file_digests(registry_path)["sha256"] != REGISTRY_SHA256:
        raise ValueError("Registry differs from the supplied v1.1 specification")
    registry = json.loads(registry_path.read_text())
    if registry["schema_version"] != "hand-warehouse/1.1":
        raise ValueError("Wrong registry")
    omitted, plan_result = (set(), None)
    plan = overlay_plan if overlay_plan is not None else assembly_plan
    if plan is not None:
        omitted, plan_result = check_plan(release, plan)
        if overlay_plan is None:
            check_complete_media(release, omitted)
            omitted = set()
    source_hashes = None
    if source is not None:
        manifest = plan["source_manifest"] if plan is not None else source_manifest
        if manifest is None:
            raise ValueError("Fixed source manifest required for exact source comparison")
        source_hashes = check_source_tree(source, manifest)
    missing, seen, counts, fields, views = [], set(), Counter(), 0, 0
    expected_data_paths = set()
    for metadata in sorted((release / "data").glob("*/*/metainfo.json")):
        safe_path(release, metadata.relative_to(release).as_posix())
        reader = ViewReader(metadata.parent)
        meta = reader.meta
        split, start, total = check_metadata(meta, metadata.parent, registry)
        view_relative = metadata.parent.relative_to(release)
        paths = {"metainfo.json", "camera/frames.jsonl", *(item[0] for item in LAYOUT.values())}
        for name in LAYOUT:
            component = meta["components"][name]
            data, valid = reader.numeric(name)
            definition = registry["components"][component["schema_id"]]
            check_field(data, valid, definition, total)
            fields += 1
        for name in ("rgb", "segment"):
            component = meta["components"][name]
            valid = reader.validity(name)
            if valid.dtype != torch.bool or tuple(valid.shape) != (total,):
                raise ValueError("Media validity is not an independent bool [T] tensor")
            paths.update((component["data_ref"], component["valid_ref"]))
            path = safe_path(metadata.parent, component["data_ref"])
            if not path.is_file():
                relative = path.relative_to(release).as_posix()
                if relative not in omitted:
                    raise FileNotFoundError(f"Required media is missing: {relative}")
                missing.append(relative)
        check_mapping(metadata.parent, meta)
        if "mapping_ref" in meta["components"]["segment"]:
            paths.add(meta["components"]["segment"]["mapping_ref"])
        expected_data_paths.update((view_relative / p).as_posix() for p in paths)
        rows = [json.loads(line) for line in safe_path(metadata.parent, meta["sampling"]["frames_ref"]).read_text().splitlines()]
        if len(rows) != total:
            raise ValueError("Frame count mismatch")
        prefix = "training" if split == "train" else "evaluation"
        modulus = 32560 if split == "train" else 3960
        archive = "raw/data/FreiHAND_pub_v2.zip" if split == "train" else "raw/data/FreiHAND_pub_v2_eval.zip"
        for i, frame in enumerate(rows):
            index = start+i
            if type(frame.get("frame_index")) is not int or frame["frame_index"] != i or frame.get("sample_id") != f"FreiHAND/{prefix}/{index:08d}" or frame["sample_id"] in seen:
                raise ValueError("Frame order or sample identity mismatch")
            if "timestamp_ns" not in frame or frame["timestamp_ns"] is not None or "clock_domain" not in frame or frame["clock_domain"] is not None:
                raise ValueError("Independent images must retain unknown capture time")
            seen.add(frame["sample_id"])
            if frame.get("source_frame_id") != str(index) or frame.get("image_variant") != {"base_sample_id": index % modulus, "variant_index": index // modulus}:
                raise ValueError("Source frame or background variant mapping mismatch")
            locator = frame.get("source_locator", {})
            if (locator.get("annotation_index"), locator.get("member"), locator.get("archive")) != (index % modulus, f"{prefix}/rgb/{index:08d}.jpg", archive):
                raise ValueError("Image-to-annotation provenance mismatch")
        if source:
            validate_view(Path(source) / view_relative, metadata.parent, registry)
        counts[split] += total
        views += 1
    if views != 33 or dict(counts) != {"test": 3960, "train": 130240}:
        raise ValueError(f"Wrong full-dataset coverage: views={views}, counts={dict(counts)}")
    actual_data = {p.relative_to(release).as_posix() for p in (release / "data").rglob("*") if p.is_file()}
    if actual_data != expected_data_paths - set(missing):
        raise ValueError("Unexpected, obsolete, or missing files in the data tree")
    return {"numeric_structure_passed": True, "exact_source_comparison": bool(source),
            "verified_source_file_hashes": source_hashes,
            "views": views, "counts": dict(counts), "numeric_fields": fields,
            "missing_media": missing, "mode": "overlay" if overlay_plan is not None else "full_tree",
            "complete_media_present": not missing, "assembly_plan_checks": plan_result,
            "visual_review": "not_performed", "media_decoding": "not_performed",
            "scope": "All fixed-release structure and references; optional exact v1.0 tensor comparison and bound-manifest hashes. Media decoding and human approval are separate gates."}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument("--source", type=Path, help="Original v1.0 subset for exact byte comparisons")
    parser.add_argument("--source-manifest", type=Path, help="Fixed source inventory; required with --source when no assembly/overlay plan is supplied")
    plans = parser.add_mutually_exclusive_group()
    plans.add_argument("--overlay-plan", type=Path, help="Verify the fixed-source plan and allow its absent unchanged media")
    plans.add_argument("--assembly-plan", type=Path, help="Verify the plan and require all declared reused media to be present")
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()
    overlay = json.loads(args.overlay_plan.read_text()) if args.overlay_plan else None
    assembly = json.loads(args.assembly_plan.read_text()) if args.assembly_plan else None
    manifest = json.loads(args.source_manifest.read_text()) if args.source_manifest else None
    result = validate(args.release, args.source, overlay, assembly, manifest)
    if args.report:
        json_write(args.report, result)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()