File size: 7,452 Bytes
10ed3aa d378823 10ed3aa d378823 10ed3aa d378823 10ed3aa d378823 10ed3aa d378823 10ed3aa d378823 | 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 | """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()
|