Download FreiHAND/shared-v1.1/script/migrate_freihand.py from ParityLab/Hand-Datasets-Raw: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/FreiHAND/shared-v1.1/script/migrate_freihand.py
- Command line
-
hf download hf://datasets/ParityLab/Hand-Datasets-Raw/FreiHAND/shared-v1.1/script/migrate_freihand.py
-
curl -L -o migrate_freihand.py https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/FreiHAND/shared-v1.1/script/migrate_freihand.py
11.5 kB
| #!/usr/bin/env python3 | |
| """Exactly repack FreiHAND v1.0 numerical fields into a v1.1 non-media overlay. | |
| The source is never changed. This is not a complete release: omitted unchanged | |
| media must be staged and validated by the publisher before publication. | |
| """ | |
| import argparse | |
| from collections import Counter | |
| import copy | |
| import fcntl | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import time | |
| import torch | |
| from bundle_io import PROFILE, LAYOUT, ViewReader, exact_tensor | |
| from fetch_shared_subset import REVISION, file_digests, json_write, verified | |
| PILOT = {"training_00000000", "evaluation_00000000"} | |
| REFERENCE_KEYS = {"data_ref", "data_key", "valid_ref", "valid_key", "storage", "valid_storage"} | |
| def check_field(data, valid, definition, total): | |
| shape = tuple(total if x == "T" else x for x in definition["shape"]) | |
| valid_shape = tuple(total if x == "T" else x for x in definition["valid_shape"]) | |
| if data.dtype != getattr(torch, definition["dtype"]) or tuple(data.shape) != shape: | |
| raise ValueError(f"Wrong data dtype/shape: {data.dtype}, {tuple(data.shape)}, expected {shape}") | |
| if valid.dtype != torch.bool or tuple(valid.shape) != valid_shape: | |
| raise ValueError("Wrong validity dtype/shape") | |
| if not torch.isfinite(data[valid]).all() or not torch.isnan(data[~valid]).all(): | |
| raise ValueError("Source validity and finite/NaN values conflict; do not silently repair") | |
| def new_metadata(source): | |
| meta = copy.deepcopy(source) | |
| if meta["dataset_id"] != "FreiHAND" or meta["schema_version"] != "hand-warehouse/1.0": | |
| raise ValueError("This bounded converter expects FreiHAND v1.0") | |
| if set(meta["components"]) != {"rgb", "segment", *LAYOUT}: | |
| raise ValueError("Unexpected components: review before extending the converter") | |
| meta["schema_version"] = "hand-warehouse/1.1" | |
| meta["release_id"] = "shared-v1.1" | |
| for name, (path, entry) in LAYOUT.items(): | |
| meta["components"][name].update(data_ref=path, valid_ref=path, | |
| data_key=[entry, "data"], valid_key=[entry, "valid"], | |
| storage={"profile": PROFILE}, valid_storage={"profile": PROFILE}) | |
| return meta | |
| def validate_view(source, target, registry): | |
| before = json.loads((source / "metainfo.json").read_text()) | |
| reader = ViewReader(target) | |
| if reader.meta != new_metadata(before): | |
| raise ValueError(f"Unexpected metadata change: {target}") | |
| total = before["num_frames"] | |
| fields = {} | |
| for name, (path, entry) in LAYOUT.items(): | |
| component = before["components"][name] | |
| old_data = torch.load(source / component["data_ref"], map_location="cpu", weights_only=True) | |
| old_valid = torch.load(source / component["valid_ref"], map_location="cpu", weights_only=True) | |
| data, valid = reader.numeric(name) | |
| check_field(data, valid, registry["components"][component["schema_id"]], total) | |
| bundle = reader.cache[path] | |
| if set(bundle) != {entry} or set(bundle[entry]) != {"data", "valid"}: | |
| raise ValueError("Unexpected bundle fields") | |
| if not exact_tensor(old_data, data) or not exact_tensor(old_valid, valid): | |
| raise ValueError(f"Non-identical tensor bytes: {target} {name}") | |
| fields[name] = {"shape": list(data.shape), "valid_shape": list(valid.shape), | |
| "data_bytes": data.numel() * data.element_size(), | |
| "valid_true": int(valid.sum()), "nan_count": int(torch.isnan(data).sum()), | |
| "exact_bytes": True} | |
| for name in ("rgb", "segment"): | |
| valid = reader.validity(name) | |
| if valid.dtype != torch.bool or tuple(valid.shape) != (total,): | |
| raise ValueError("Standalone media validity must stay a bool tensor [T]") | |
| old = torch.load(source / before["components"][name]["valid_ref"], map_location="cpu", weights_only=True) | |
| if not exact_tensor(old, valid): | |
| raise ValueError("Media valid changed") | |
| if "data_key" in reader.meta["components"][name] or "valid_key" in reader.meta["components"][name]: | |
| raise ValueError("Media validity must not be wrapped") | |
| frames_ref = before["sampling"]["frames_ref"] | |
| if file_digests(source / frames_ref) != file_digests(target / frames_ref): | |
| raise ValueError("Frame map changed") | |
| frames = [json.loads(line) for line in (target / frames_ref).read_text().splitlines()] | |
| if len(frames) != total or [f["frame_index"] for f in frames] != list(range(total)): | |
| raise ValueError("Frame map length/order mismatch") | |
| modulus = 32560 if before["split"] == "train" else 3960 | |
| for frame in frames: | |
| if frame["source_locator"]["annotation_index"] != int(frame["source_frame_id"]) % modulus: | |
| raise ValueError("Original image-to-annotation mapping inconsistent") | |
| mapping = before["components"]["segment"].get("mapping_ref") | |
| if mapping: | |
| rows = [json.loads(line) for line in (target / mapping).read_text().splitlines()] | |
| if len(rows) != total or [row["frame_index"] for row in rows] != list(range(total)): | |
| raise ValueError("Instance map frame order mismatch") | |
| return {"frames": total, "split": before["split"], "fields": fields, | |
| "sample_ids": [f["sample_id"] for f in frames]} | |
| def migrate(workspace, scope): | |
| started = time.perf_counter() | |
| torch.set_num_threads(1) | |
| manifest = json.loads((workspace / "tmp/source-manifest.json").read_text()) | |
| if manifest["revision"] != REVISION: | |
| raise ValueError("Source manifest revision mismatch") | |
| source = workspace / "source/FreiHAND/shared-v1.0" | |
| target = workspace / ("tmp/pilot/shared-v1.1" if scope == "pilot" else "delivery/FreiHAND/shared-v1.1") | |
| registry = json.loads((workspace / "spec/hand-warehouse-1.1/schema.json").read_text()) | |
| entries = [item for item in manifest["files"] if scope == "all" or not item["relative_path"].startswith("data/") or Path(item["relative_path"]).parts[1] in PILOT] | |
| downloaded = [item for item in entries if item["download"]] | |
| for item in downloaded: | |
| verified(source / item["relative_path"], item) | |
| metas = [item["relative_path"] for item in entries if item["relative_path"].startswith("data/") and item["relative_path"].endswith("/metainfo.json")] | |
| expected_views = 2 if scope == "pilot" else 33 | |
| if len(metas) != expected_views: | |
| raise ValueError(f"Expected {expected_views} views, got {len(metas)}") | |
| removed = set() | |
| for relative in metas: | |
| path = Path(relative) | |
| old = json.loads((source / path).read_text()) | |
| new_metadata(old) | |
| for name in LAYOUT: | |
| for key in ("data_ref", "valid_ref"): | |
| removed.add((path.parent / old["components"][name][key]).as_posix()) | |
| # No media is copied, encoded or created; only authorized downloaded files. | |
| for item in downloaded: | |
| relative = item["relative_path"] | |
| if relative in removed or relative in metas: | |
| continue | |
| destination = target / relative | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(source / relative, destination) | |
| rows, seen, counts = [], set(), Counter() | |
| for relative in metas: | |
| view_relative = Path(relative).parent | |
| old_view, new_view = source / view_relative, target / view_relative | |
| old = json.loads((old_view / "metainfo.json").read_text()) | |
| updated = new_metadata(old) | |
| for name, (path, entry) in LAYOUT.items(): | |
| component = old["components"][name] | |
| data = torch.load(old_view / component["data_ref"], map_location="cpu", weights_only=True) | |
| valid = torch.load(old_view / component["valid_ref"], map_location="cpu", weights_only=True) | |
| check_field(data, valid, registry["components"][component["schema_id"]], old["num_frames"]) | |
| destination = new_view / path | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = destination.with_suffix(".pt.tmp") | |
| torch.save({entry: {"data": data, "valid": valid}}, temporary) | |
| reread = torch.load(temporary, map_location="cpu", weights_only=True)[entry] | |
| if not exact_tensor(data, reread["data"]) or not exact_tensor(valid, reread["valid"]): | |
| raise ValueError("Roundtrip tensor bytes changed") | |
| temporary.replace(destination) | |
| json_write(new_view / "metainfo.json", updated) | |
| result = validate_view(old_view, new_view, registry) | |
| ids = result.pop("sample_ids") | |
| if len(set(ids)) != len(ids) or seen.intersection(ids): | |
| raise ValueError("Duplicate sample IDs") | |
| seen.update(ids) | |
| counts[result["split"]] += result["frames"] | |
| rows.append({"view": view_relative.as_posix(), **result}) | |
| json_write(workspace / f"tmp/{scope}-views.json", rows) | |
| print(f"verified view {len(rows)}/{len(metas)}: {view_relative}", flush=True) | |
| expected_counts = {"train": 4096, "test": 3960} if scope == "pilot" else {"train": 130240, "test": 3960} | |
| if dict(counts) != expected_counts: | |
| raise ValueError(f"Unexpected sample coverage: {dict(counts)}") | |
| for item in downloaded: | |
| # Recheck source after all repacking and unchanged target bytes. | |
| verified(source / item["relative_path"], item) | |
| if item["relative_path"] not in removed and item["relative_path"] not in metas: | |
| verified(target / item["relative_path"], item) | |
| for relative in removed: | |
| if (target / relative).exists(): | |
| raise ValueError(f"Obsolete tensor still in overlay: {relative}") | |
| omitted = [item for item in entries if not item["download"]] | |
| report = {"scope": scope, "source_revision": REVISION, "views": len(rows), "counts": dict(counts), | |
| "numerical_repack_passed": True, "source_unchanged": True, | |
| "media_verified_locally": False, "visual_review": "not_run_no_media_downloaded", | |
| "complete_release": False, "status": "numerical_overlay_verified_pending_release_assembly", | |
| "downloaded_files": len(downloaded), "downloaded_bytes": sum(x["size"] for x in downloaded), | |
| "old_tensor_files_replaced": len(removed), "new_bundle_files": len(rows) * len(LAYOUT), | |
| "omitted_media_files": len(omitted), "omitted_media_bytes": sum(x["size"] for x in omitted), | |
| "elapsed_seconds": time.perf_counter() - started, "target": str(target), | |
| "views_report": rows, "removed_source_paths": sorted(removed), "reuse_unchanged": omitted, | |
| "upstream_note": "Component source_locator values are preserved; current source RGB/intrinsic/XYZ provenance member fields appear to share MANO/mask references. Per-frame RGB member and sample mapping are retained. This migration does not repair source provenance."} | |
| json_write(workspace / f"tmp/{scope}-report.json", report) | |
| print(json.dumps({k: report[k] for k in ("status", "views", "counts", "elapsed_seconds", "target")}), flush=True) | |
| return report | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--workspace", type=Path, required=True) | |
| parser.add_argument("--scope", choices=["pilot", "all"], required=True) | |
| args = parser.parse_args() | |
| with (args.workspace / "tmp/migration.lock").open("a") as lock: | |
| fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| migrate(args.workspace, args.scope) | |
| if __name__ == "__main__": | |
| main() | |