Download HOT3D/shared-v1.1/script/hot3d_bundle.py from ParityLab/Hand-Datasets-Raw: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/HOT3D/shared-v1.1/script/hot3d_bundle.py
- Command line
-
hf download hf://datasets/ParityLab/Hand-Datasets-Raw/HOT3D/shared-v1.1/script/hot3d_bundle.py
-
curl -L -o hot3d_bundle.py https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/HOT3D/shared-v1.1/script/hot3d_bundle.py
11.8 kB
| """HOT3D's actual v1.1 fields; CPU-only, without geometry recomputation.""" | |
| import copy | |
| import json | |
| import re | |
| from pathlib import Path, PurePosixPath | |
| import torch | |
| PROFILE = "pt/tensor_bundle/v1" | |
| VERSION = "hand-warehouse/1.1" | |
| RELEASE = "shared-v1.1" | |
| def safe_path(root, ref): | |
| if not isinstance(ref, str) or not ref or any(c in ref for c in ("\\", ":", "<", ">")): | |
| raise ValueError(f"Invalid relative path: {ref!r}") | |
| p = PurePosixPath(ref) | |
| if p.is_absolute() or ".." in p.parts or str(p) != ref or ref == ".": | |
| raise ValueError(f"Invalid relative path: {ref}") | |
| result = Path(root) / ref | |
| if not result.resolve().is_relative_to(Path(root).resolve()): | |
| raise ValueError(f"Reference escapes view: {ref}") | |
| return result | |
| def exact(a, b): | |
| return (a.dtype == b.dtype and a.shape == b.shape and | |
| torch.equal(a.contiguous().reshape(-1).view(torch.uint8), | |
| b.contiguous().reshape(-1).view(torch.uint8))) | |
| def at(root, keys): | |
| for key in keys: | |
| root = root[key] | |
| return root | |
| def fields(meta): | |
| """Return the fixed registered grouping, not a guessed filename merge.""" | |
| if meta["dataset_id"] != "HOT3D" or meta["hand_slots"] != ["left", "right"]: | |
| raise ValueError("Expected HOT3D and left/right slots") | |
| if meta["camera"]["model"] != "fisheye624": | |
| raise ValueError("Unreviewed camera model") | |
| result = [] | |
| for name, component in meta["components"].items(): | |
| if not component.get("available"): | |
| continue | |
| schema = component["schema_id"] | |
| locator = ["components", name] | |
| if name == "intrinsic" and schema == "camera/fisheye624/v1": | |
| bundle, key, old = "camera/camera.pt", "intrinsic", "camera/intrinsic.pt" | |
| elif name == "extrinsic" and schema == "transform/se3/v1": | |
| bundle, key, old = "camera/camera.pt", "extrinsic", "camera/extrinsic.pt" | |
| elif name == "mano" and schema == "mano/axis_angle61/v1": | |
| bundle, key, old = "annotation/mano/mano.pt", "motion", "annotation/mano/motion.pt" | |
| elif re.fullmatch(r"object_[0-9]+_pose", name) and schema == "object/rigid/v1": | |
| oid = name[7:-5] | |
| bundle, key, old = f"annotation/object/{oid}/object.pt", "pose", f"annotation/object/{oid}/pose.pt" | |
| elif ((name == "rgb" and schema == "rgb/uint8/v1") or | |
| (re.fullmatch(r"object_[0-9]+_mesh", name) and schema == "mesh/obj/v1")): | |
| if component.get("attributes"): | |
| raise ValueError(f"Unreviewed nonnumeric attributes: {name}") | |
| continue | |
| else: | |
| raise ValueError(f"Unreviewed HOT3D component: {name} / {schema}") | |
| result.append({"locator": locator, "bundle": bundle, "entry": key, | |
| "old": old, "schema": schema}) | |
| for attribute, value in component.get("attributes", {}).items(): | |
| if attribute != "visibility" or key not in {"motion", "pose"}: | |
| raise ValueError(f"Unreviewed attribute: {name}/{attribute}") | |
| result.append({"locator": locator + ["attributes", attribute], | |
| "bundle": bundle, "entry": "visibility", | |
| "old": str(PurePosixPath(old).with_name("visibility.pt")), | |
| "schema": "visibility/hand" if key == "motion" else "visibility/object"}) | |
| return result | |
| def new_metadata(old): | |
| if old["schema_version"] != "hand-warehouse/1.0" or old["release_id"] != "shared-v1.0": | |
| raise ValueError("Source must be shared-v1.0") | |
| meta = copy.deepcopy(old) | |
| for field in fields(old): | |
| original = at(old, field["locator"]) | |
| valid_ref = str(PurePosixPath(field["old"]).with_stem(PurePosixPath(field["old"]).stem + "_valid")) | |
| if original["data_ref"] != field["old"] or original.get("valid_ref") != valid_ref: | |
| raise ValueError(f"Unexpected source references: {field['locator']}") | |
| if any(k in original for k in ("data_key", "valid_key")): | |
| raise ValueError("Source is already bundled") | |
| component = at(meta, field["locator"]) | |
| component.update(data_ref=field["bundle"], valid_ref=field["bundle"], | |
| data_key=[field["entry"], "data"], valid_key=[field["entry"], "valid"], | |
| storage={"profile": PROFILE}, valid_storage={"profile": PROFILE}) | |
| meta["schema_version"], meta["release_id"] = VERSION, RELEASE | |
| return meta | |
| def check_field(data, valid, field, component, total, registry): | |
| if field["schema"].startswith("visibility/"): | |
| rule = registry["tensor_attributes"]["visibility"] | |
| # Also called on the unbundled v1.0 input. Its semantic metadata is | |
| # mandatory, but only the v1.1 Reader checks the new bundle keys. | |
| required = set(rule["required_metadata"]) - {"data_key", "valid_key", "storage", "valid_storage"} | |
| if not required.issubset(component): | |
| raise ValueError(f"Missing visibility metadata: {sorted(required - set(component))}") | |
| if component["dtype"] not in rule["allowed_dtypes"]: | |
| raise ValueError("Visibility dtype is not registered") | |
| shape = (total, 2) if field["schema"] == "visibility/hand" else (total,) | |
| valid_shape, dtype = shape, component["dtype"] | |
| if component["visibility_type"] not in {"boolean", "ratio"}: | |
| raise ValueError("Unregistered visibility type") | |
| else: | |
| rule = registry["components"][field["schema"]] | |
| shape = tuple(total if d == "T" else d for d in rule["shape"]) | |
| valid_shape = tuple(total if d == "T" else d for d in rule["valid_shape"]) | |
| dtype = rule["dtype"] | |
| if not isinstance(data, torch.Tensor) or data.device.type != "cpu" or data.dtype != getattr(torch, dtype) or tuple(data.shape) != shape: | |
| raise ValueError(f"Wrong data dtype/shape: {field['locator']}") | |
| if not isinstance(valid, torch.Tensor) or valid.device.type != "cpu" or valid.dtype != torch.bool or tuple(valid.shape) != valid_shape: | |
| raise ValueError(f"Wrong validity dtype/shape: {field['locator']}") | |
| if data.is_floating_point(): | |
| if not torch.isfinite(data[valid]).all() or not torch.isnan(data[~valid]).all(): | |
| raise ValueError(f"Source/schema finite-NaN conflict (not repaired): {field['locator']}") | |
| if field["schema"].startswith("visibility/") and component["visibility_type"] == "ratio": | |
| if not ((data[valid] >= 0) & (data[valid] <= 1)).all(): | |
| raise ValueError("Visibility ratios outside [0,1]; do not rescale during migration") | |
| class Reader: | |
| def __init__(self, view): | |
| self.view = Path(view) | |
| self.meta = json.loads((self.view / "metainfo.json").read_text()) | |
| if self.meta["schema_version"] != VERSION or self.meta["release_id"] != RELEASE: | |
| raise ValueError("Reader expects shared-v1.1") | |
| self.cache = {} | |
| def load(self, ref): | |
| if ref not in self.cache: | |
| self.cache[ref] = torch.load(safe_path(self.view, ref), map_location="cpu", weights_only=True) | |
| return self.cache[ref] | |
| def numeric(self, field): | |
| component = at(self.meta, field["locator"]) | |
| if component["data_ref"] != field["bundle"] or component["valid_ref"] != field["bundle"]: | |
| raise ValueError("Bundle path does not match registered grouping") | |
| if component["data_key"] != [field["entry"], "data"] or component["valid_key"] != [field["entry"], "valid"]: | |
| raise ValueError("Bundle key does not match registered grouping") | |
| if any(component[k] != {"profile": PROFILE} for k in ("storage", "valid_storage")): | |
| raise ValueError("Wrong numerical storage profile") | |
| bundle = self.load(field["bundle"]) | |
| entry = bundle[field["entry"]] | |
| if type(entry) is not dict or set(entry) != {"data", "valid"}: | |
| raise ValueError("Unexpected bundle leaves") | |
| return entry["data"], entry["valid"] | |
| def audit_view(view, registry, source=None, require_media=False, check_frames=True): | |
| reader = Reader(view) | |
| meta = reader.meta | |
| if source is not None: | |
| before = json.loads((Path(source) / "metainfo.json").read_text()) | |
| if meta != new_metadata(before): | |
| raise ValueError(f"Metadata changed beyond version/references: {view}") | |
| total = meta["num_frames"] | |
| grouping, rows = {}, [] | |
| for field in fields(meta): | |
| grouping.setdefault(field["bundle"], set()).add(field["entry"]) | |
| data, valid = reader.numeric(field) | |
| check_field(data, valid, field, at(meta, field["locator"]), total, registry) | |
| if source is not None: | |
| component = at(before, field["locator"]) | |
| for name, tensor in (("data_ref", data), ("valid_ref", valid)): | |
| old = torch.load(safe_path(source, component[name]), map_location="cpu", weights_only=True) | |
| if not exact(old, tensor): | |
| raise ValueError(f"Changed tensor bytes: {view} {field['locator']} {name}") | |
| rows.append({"field": "/".join(field["locator"]), "bundle": field["bundle"], | |
| "shape": list(data.shape), "valid_shape": list(valid.shape), | |
| "valid_true": int(valid.sum()), "valid_total": valid.numel(), | |
| "exact_source_bytes": source is not None}) | |
| for ref, entries in grouping.items(): | |
| if type(reader.cache[ref]) is not dict or set(reader.cache[ref]) != entries: | |
| raise ValueError(f"Extra/missing fields in {ref}") | |
| missing = [] | |
| for name, component in meta["components"].items(): | |
| if not component.get("available") or component.get("schema_id") not in {"rgb/uint8/v1", "mesh/obj/v1"}: | |
| continue | |
| if "data_key" in component or "valid_key" in component: | |
| raise ValueError("Media/mesh validity must stay standalone") | |
| for key in ("data_ref", "valid_ref"): | |
| if not safe_path(view, component[key]).is_file(): | |
| missing.append(component[key]) | |
| valid_path = safe_path(view, component["valid_ref"]) | |
| if valid_path.is_file(): | |
| tensor = reader.load(component["valid_ref"]) | |
| expected = (total,) if name == "rgb" else () | |
| if not isinstance(tensor, torch.Tensor) or tensor.dtype != torch.bool or tuple(tensor.shape) != expected: | |
| raise ValueError("Wrong standalone validity") | |
| if source is not None: | |
| old_ref = before["components"][name]["valid_ref"] | |
| old_valid = torch.load(safe_path(source, old_ref), map_location="cpu", weights_only=True) | |
| if not exact(old_valid, tensor): | |
| raise ValueError(f"Standalone validity changed: {name}") | |
| elif name == "rgb": | |
| raise ValueError("RGB validity is part of the numerical-stage input, not deferred") | |
| if require_media and missing: | |
| raise ValueError(f"Incomplete view: {len(missing)} missing media/asset references") | |
| if check_frames: | |
| frame_path = safe_path(view, meta["sampling"]["frames_ref"]) | |
| count = 0 | |
| with frame_path.open() as handle: | |
| for line in handle: | |
| frame = json.loads(line) | |
| if frame["frame_index"] != count or frame["source_locator"]["stream_id"] != meta["camera_id"]: | |
| raise ValueError("Broken frame/camera order") | |
| count += 1 | |
| if count != total: | |
| raise ValueError("Frame table length mismatch") | |
| return {"sequence": meta["sequence_id"], "camera": meta["camera_id"], | |
| "frames": total, "split": meta["split"], "fields": rows, | |
| "bundles": len(grouping), "missing_media_asset_refs": missing, | |
| "numerical_bytes_exact": source is not None} | |