Hand-Datasets-Raw / FreiHAND /shared-v1.1 /script /freihand_common.py
orz2333's picture
Migrate HOT3D, OakInk-v1, OakInk-v2 and FreiHAND to shared-v1.1 (#4)
10ed3aa
Raw History Blame Contribute Delete
7.45 kB
"""FreiHAND v1.1 helpers. Media remain unchanged; numerical fields use bundles."""
from pathlib import Path
import codecs, collections, hashlib, io, json, pickle, subprocess
import shutil
import numpy as np
import torch
from bundle_io import PROFILE, exact_tensor
from migrate_freihand import LAYOUT
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" / "freihand-tools"
FFMPEG = shutil.which("ffmpeg")
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)]
class View:
def __init__(self, dataset, sequence, camera, frame_ids, size, source, kind="image", split="unknown"):
assert dataset == "FreiHAND" 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.1", "dataset_id": "FreiHAND",
"release_id": "shared-v1.1", "sequence_id": sequence, "camera_id": "camera",
"sample_type": "image", "num_frames": self.count,
"hand_slots": ["left", "right"], "split": split,
"split_scheme": "FreiHAND_official_train_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": 4096,
"selection": "all released RGB images, sorted by source RGB index; all background variants retained"},
"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
bundle_ref, entry = LAYOUT[name]
path = self.path / bundle_ref; path.parent.mkdir(parents=True, exist_ok=True)
data_tensor = torch.from_numpy(value.copy()); valid_tensor = torch.from_numpy(valid.copy())
torch.save({entry: {"data": data_tensor, "valid": valid_tensor}}, path)
self.meta["components"][name] = {
"available": True, "schema_id": schema, "data_ref": bundle_ref, "data_key": [entry, "data"],
"axes": axes, "valid_ref": bundle_ref, "valid_key": [entry, "valid"], "valid_axes": axes[:valid.ndim],
"storage": {"profile": PROFILE}, "valid_storage": {"profile": PROFILE},
"provenance": {"kind": "format_conversion", "method": metadata.pop("method", "source values retained")},
"source_locator": dict(self.source), **metadata}
restored = torch.load(path, map_location="cpu", weights_only=True)[entry]
assert exact_tensor(restored["data"], data_tensor) and exact_tensor(restored["valid"], valid_tensor)
self.checks.append({"test": "tensor_serialization_exact", "file": bundle_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()