"""hand-warehouse v1.1 tensor-bundle layout: resolution, writing, cached reading. The v1.1 registry (`doc/schema.json`) is declarative; its own `note` says runtime readers/converters/validators still require adaptation. This module is that adaptation for the parts every dataset shares: * ``Registry.resolve()`` v1.0 ``data_ref`` -> (bundle file, entry key path) * ``BundleWriter`` builds one nested ``{"data": Tensor, "valid": Bool}`` tree * ``BundleReader`` loads a bundle once, then fetches fields by key * ``expanded_all_known()`` CONTRACT 3 expansion of a declared all-known scalar Section references are to ``doc/CONTRACT.md`` (hand-warehouse/1.1). """ from __future__ import annotations import hashlib import json import os from pathlib import Path, PurePosixPath import torch SCHEMA_VERSION = "hand-warehouse/1.1" RELEASE_ID = "shared-v1.1" BUNDLE_PROFILE = "pt/tensor_bundle/v1" DATA_TERMINAL = "data" VALID_TERMINAL = "valid" #: CONTRACT 3: axes declared on the three visibility scopes. VISIBILITY_AXES = { ("T", "hand", "joint"): "hand_keypoint", ("T", "hand"): "whole_hand", ("T",): "object", } def _parts(value: str): return PurePosixPath(value).parts def _is_wildcard(segment: str) -> bool: """A registry template segment is a wildcard when it carries a placeholder. Covers both ```` and the composite ``__`` (CONTRACT 4 contact pairs). """ return "<" in segment and ">" in segment def _entry_key(segment: str) -> str: """``pose.pt`` -> ``pose``; ``parts`` -> ``parts`` (CONTRACT 4: keys, not paths).""" return segment[:-3] if segment.endswith(".pt") else segment class Registry: """Read-only view over the declarative v1.1 registry.""" def __init__(self, schema: dict): if schema.get("schema_version") != SCHEMA_VERSION: raise ValueError(f"not a {SCHEMA_VERSION} registry: {schema.get('schema_version')!r}") self.schema = schema self.bundles = schema["tensor_bundles"] self.components = schema["components"] self.visibility_scopes = schema["tensor_attributes"]["visibility"]["scopes"] @classmethod def load(cls, path) -> "Registry": return cls(json.loads(Path(path).read_text(encoding="utf-8"))) # -- v1.0 reference -> v1.1 bundle entry -------------------------------- def resolve(self, data_ref: str): """Map a numeric ``data_ref`` to ``(bundle_path, keys, entry_spec)``. Returns ``None`` for anything the contract keeps out of bundles: media, JSONL, mesh/asset files, ``frames.jsonl``, ``metainfo.json``, ``articulation.json``. The bundle's own entry table decides -- an unmatched entry is never merged, so no path is guessed into a bundle. """ ref = _parts(data_ref) for bundle in self.bundles.values(): template = _parts(bundle["path"]) dir_template, filename = template[:-1], template[-1] if len(ref) <= len(dir_template): continue bound, matched = {}, True for want, got in zip(dir_template, ref): if _is_wildcard(want): bound[want] = got elif want != got: matched = False break if not matched: continue keys = [_entry_key(segment) for segment in ref[len(dir_template):]] spec = self._entry_spec(bundle, keys) if spec is None: continue directory = [bound.get(segment, segment) for segment in dir_template] return "/".join(directory + [filename]), keys, spec return None @staticmethod def _entry_spec(bundle: dict, keys: list): for name, spec in bundle["entries"].items(): template = name.split("/") if len(template) != len(keys): continue if all(_is_wildcard(w) or w == k for w, k in zip(template, keys)): return spec return None def valid_shape_template(self, schema_id: str): spec = self.components.get(schema_id) if spec is None: raise KeyError(f"schema_id {schema_id!r} is not registered") return spec.get("valid_shape") def visibility_valid_shape(self, axes): scope = VISIBILITY_AXES.get(tuple(axes)) if scope is None: raise ValueError(f"visibility axes {list(axes)} match no declared scope") return self.visibility_scopes[scope]["valid_shape"] def expanded_all_known(data: torch.Tensor, valid_shape) -> torch.Tensor: """CONTRACT 3: explicit all-true bool tensor of the field's ``valid_shape``. Symbolic dims resolve positionally against the data tensor, so the result restates the source's declared all-known validity -- it is never inferred from values or from a pose validity (``tensor_attributes.visibility``). """ if valid_shape is None: raise ValueError("field declares no valid_shape; cannot expand all-known validity") if len(valid_shape) > data.ndim: raise ValueError(f"valid_shape {list(valid_shape)} exceeds data rank {data.ndim}") dims = [] for axis, dim in enumerate(valid_shape): dims.append(data.shape[axis] if isinstance(dim, str) else int(dim)) return torch.ones(dims, dtype=torch.bool) class BundleWriter: """Accumulates one bundle's tree, then replaces the file atomically.""" def __init__(self, view_root, rel_path: str): self.view_root = Path(view_root) self.rel_path = rel_path self.tree: dict = {} def put(self, keys, data: torch.Tensor, valid: torch.Tensor): if not keys: raise ValueError("empty key path") if not isinstance(data, torch.Tensor) or not isinstance(valid, torch.Tensor): raise TypeError(f"{'/'.join(keys)}: data and valid must both be Tensors") if valid.dtype != torch.bool: raise TypeError(f"{'/'.join(keys)}: valid must be a bool Tensor, got {valid.dtype}") node = self.tree for key in keys[:-1]: node = node.setdefault(key, {}) if not isinstance(node, dict): raise TypeError(f"{'/'.join(keys)}: {key!r} already holds a leaf") leaf = "/".join(keys) if keys[-1] in node: raise ValueError(f"duplicate field {leaf}") node[keys[-1]] = {DATA_TERMINAL: data, VALID_TERMINAL: valid} return leaf def save(self): """Write to a sibling temp file, fsync, then ``os.replace`` (MIGRATION 4.3).""" if not self.tree: return None # bundle_layout_rules.omit_empty_bundles path = self.view_root / self.rel_path path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_name(path.name + ".hw11-tmp") torch.save(self.tree, temp) fd = os.open(temp, os.O_RDONLY) try: os.fsync(fd) finally: os.close(fd) os.replace(temp, path) return path class BundleReader: """Reader cache required by ``reference_rules.reader_cache``.""" def __init__(self): self._cache: dict = {} def bundle(self, view_root, rel_path: str): key = (str(Path(view_root).resolve()), rel_path) if key not in self._cache: path = Path(view_root) / rel_path if not path.is_file(): raise FileNotFoundError(f"bundle {rel_path} not found in {view_root}") self._cache[key] = torch.load(path, map_location="cpu", weights_only=True) return self._cache[key] def get(self, view_root, rel_path: str, keys): if not isinstance(keys, list) or not keys: raise TypeError(f"{rel_path}: data_key/valid_key must be a non-empty list") node = self.bundle(view_root, rel_path) for depth, key in enumerate(keys): if not isinstance(node, dict): raise KeyError(f"{rel_path}: {'/'.join(keys[:depth])} is a leaf, not a dict") if key not in node: raise KeyError(f"{rel_path}: missing key {key!r} on path {'/'.join(keys)}") node = node[key] return node def field(self, view_root, component: dict): """Fetch ``(data, valid)`` for a registered bundle component.""" for required in ("data_ref", "data_key", "valid_ref", "valid_key"): if required not in component: raise KeyError(f"component is missing {required!r}") data = self.get(view_root, component["data_ref"], component["data_key"]) valid = self.get(view_root, component["valid_ref"], component["valid_key"]) if not isinstance(data, torch.Tensor): raise TypeError(f"{component['data_ref']}: data is {type(data).__name__}, not a Tensor") if not isinstance(valid, torch.Tensor) or valid.dtype != torch.bool: raise TypeError(f"{component['valid_ref']}: valid must be a bool Tensor") return data, valid def raw_bytes(tensor: torch.Tensor) -> bytes: """Unified contiguous byte view (CONTRACT 6.2), NaN bit patterns included.""" tensor = tensor.detach().cpu().contiguous() try: return tensor.numpy().tobytes() except (TypeError, RuntimeError): return tensor.view(torch.uint8).numpy().tobytes() def same_tensor(left: torch.Tensor, right: torch.Tensor) -> bool: return ( left.dtype == right.dtype and tuple(left.shape) == tuple(right.shape) and raw_bytes(left) == raw_bytes(right) ) def sha256_file(path, block: int = 8 << 20) -> str: digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(block), b""): digest.update(chunk) return digest.hexdigest() def sha256_bytes(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest()