"""Shared helpers for the published RHD shared-v1.0 tools.""" from pathlib import Path import codecs, collections, hashlib, io, json, pickle, subprocess import imageio_ffmpeg import numpy as np import torch SCRIPT_DIR = Path(__file__).resolve().parent RELEASE_ROOT = SCRIPT_DIR.parent DATASET_ROOT = RELEASE_ROOT.parent RAW_ROOT = DATASET_ROOT / "raw" / "data" TMP_ROOT = DATASET_ROOT / "tmp" / "rhd-tools" FFMPEG = imageio_ffmpeg.get_ffmpeg_exe() FF = FFMPEG def load(path): return json.loads(Path(path).read_text(encoding="utf-8")) def save(path, value): path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8") tmp.replace(path) def write_jsonl(path, rows): path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) path.write_text("".join(json.dumps(x, ensure_ascii=False, allow_nan=False) + "\n" for x in rows), encoding="utf-8") def save_tensor(path, value): path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) torch.save(torch.as_tensor(np.asarray(value).copy()), path) lines = write_jsonl tensor = save_tensor def ffmpeg(args, data=None): result = subprocess.run([FFMPEG, "-v", "error", "-y", *map(str, args)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode: raise RuntimeError(result.stderr.decode(errors="replace")) return result.stdout def storage(profile, codec, pixel_format, size, source_lossy, parameters): version = ffmpeg(["-version"]).decode().splitlines()[0] return {"profile": profile, "codec": codec, "pixel_format": pixel_format, "encoded_size": size, "source_lossy": source_lossy, "decoder": version, "encoder_parameters": parameters} class RestrictedUnpickler(pickle.Unpickler): def find_class(self, module, name): allowed = { ("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, ("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct, ("numpy", "ndarray"): np.ndarray, ("numpy", "dtype"): np.dtype, ("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer, ("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer, ("_codecs", "encode"): codecs.encode, ("collections", "OrderedDict"): collections.OrderedDict, } if (module, name) not in allowed: raise pickle.UnpicklingError(f"Unsupported class: {module}.{name}") return allowed[(module, name)] Restricted = RestrictedUnpickler class View: def __init__(self, dataset, sequence, camera, frame_ids, size, source, kind="image", split="unknown"): assert dataset == "RHD" and camera == "camera" and kind == "image" self.root = RELEASE_ROOT self.path = RELEASE_ROOT / "data" / sequence / camera self.path.mkdir(parents=True, exist_ok=True) self.count = len(frame_ids) archive = Path(source["archive"]).name self.source = dict(source) self.checks = [] self.meta = { "schema_version": "hand-warehouse/1.0", "dataset_id": "RHD", "release_id": "shared-v1.0", "sequence_id": sequence, "camera_id": "camera", "sample_type": "image", "num_frames": self.count, "hand_slots": ["left", "right"], "split": split, "split_scheme": "RHD_official_training_evaluation", "split_source_locator": {"archive": "raw/data/" + archive, "member_prefix": split + "/"}, "sampling": {"type": "independent", "source_fps": None, "frames_ref": "camera/frames.jsonl", "shard_max_images": 512, "selection": "all source independent images sorted by source ID"}, "camera": {"model": "unknown", "schema_id": None, "image_size": size}, "components": {}, "storage_revision": "lossless-video-2026-09-18"} self.frames = [{"frame_index": i, "source_frame_id": str(fid), "timestamp_ns": None, "clock_domain": None, "source_locator": {**self.source, "source_frame_id": str(fid)}} for i, fid in enumerate(frame_ids)] @property def p(self): return self.path @property def T(self): return self.count @property def m(self): return self.meta def add(self, name, ref, schema, axes, valid, method="source values retained", **metadata): valid_ref = Path(ref).with_name(Path(ref).stem + "_valid.pt").as_posix() save_tensor(self.path / valid_ref, valid) self.meta["components"][name] = { "available": True, "schema_id": schema, "data_ref": ref, "axes": axes, "valid_ref": valid_ref, "valid_axes": axes[:np.asarray(valid).ndim], "provenance": {"kind": "format_conversion", "method": method}, "source_locator": dict(self.source), **metadata} def array(self, name, ref, schema, value, valid, axes, **metadata): value = np.asarray(value, np.float32).copy(); valid = np.asarray(valid, bool) assert value.shape[:valid.ndim] == valid.shape and value.shape[0] == self.count assert np.isfinite(value[valid]).all() value[~valid] = np.nan; save_tensor(self.path / ref, value) self.add(name, ref, schema, axes, valid, **metadata) restored = torch.load(self.path / ref, map_location="cpu", weights_only=True).numpy() assert np.array_equal(restored, value, equal_nan=True) self.checks.append({"test": "tensor_serialization_exact", "file": ref, "shape": list(value.shape), "valid_count": int(valid.sum())}) def intrinsic(self, value): self.meta["camera"].update(model="pinhole", schema_id="camera/pinhole/v1") self.array("intrinsic", "camera/intrinsic.pt", "camera/pinhole/v1", value, np.ones(self.count, bool), ["T", "row", "column"]) def finish(self): write_jsonl(self.path / "camera/frames.jsonl", self.frames) save(self.path / "metainfo.json", self.meta) save(TMP_ROOT / "checks" / f'{self.meta["sequence_id"]}__camera.checks.json', {"checks": self.checks, "frames": self.count, "input": self.source}) def sha256(path): h = hashlib.sha256() with Path(path).open("rb") as stream: for block in iter(lambda: stream.read(8 << 20), b""): h.update(block) return h.hexdigest()