File size: 11,823 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 | """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}
|