from __future__ import annotations from datetime import datetime, timezone import json from pathlib import Path import numpy as np FRAMES = 20 GRID = (518, 294) DEPTH_SEMANTICS = 'normalized_expected_camera_z' def check_positions(positions) -> list: positions = list(range(FRAMES)) if positions is None else [int(k) for k in positions] if not positions or positions != sorted(set(positions)) or positions[0] < 0 or positions[-1] >= FRAMES: raise ValueError(f'Bad positions {positions}: need ascending unique values in 0..{FRAMES - 1}') return positions def write_clip(root, clip_id: str, rgb, positions=None) -> None: rgb, positions = np.asarray(rgb), check_positions(positions) if rgb.ndim != 4 or rgb.shape[0] != len(positions) or rgb.shape[-1] != 3: raise ValueError(f'Expected ({len(positions)}, H, W, 3) renders, got {rgb.shape}') if rgb.dtype not in (np.uint8, np.float16, np.float32): raise ValueError(f'Unsupported dtype {rgb.dtype}') directory = Path(root) / clip_id directory.mkdir(parents=True, exist_ok=True) temp = directory / 'frames.tmp.npz' np.savez_compressed(temp, rgb=rgb) temp.replace(directory / 'frames.npz') def write_depth_clip(root, clip_id: str, depth, alpha, positions=None) -> None: depth, alpha, positions = np.asarray(depth), np.asarray(alpha), check_positions(positions) if depth.ndim != 3 or depth.shape[0] != len(positions) or alpha.shape != depth.shape: raise ValueError(f'Expected depth/alpha ({len(positions)}, H, W), got {depth.shape} / {alpha.shape}') if depth.dtype not in (np.float16, np.float32) or alpha.dtype not in (np.float16, np.float32): raise ValueError(f'Unsupported dtypes {depth.dtype} / {alpha.dtype}') directory = Path(root) / clip_id directory.mkdir(parents=True, exist_ok=True) temp = directory / 'depth.tmp.npz' np.savez_compressed(temp, depth=depth, alpha=alpha) temp.replace(directory / 'depth.npz') def write_meta(root, clips, positions, extra=None) -> dict: root = Path(root) meta = {**(extra or {}), 'native_resolution': list(GRID), 'dtype': 'float32', 'positions': check_positions(positions), 'files': {c: {'format': 'npz'} for c in clips}, 'created_utc': datetime.now(timezone.utc).isoformat()} temp = root / 'meta.tmp.json' temp.write_text(json.dumps(meta, indent=1, sort_keys=True) + '\n') temp.replace(root / 'meta.json') return meta def write_depth_meta(root, clips, positions, extra=None) -> dict: root = Path(root) meta = {**(extra or {}), 'semantics': DEPTH_SEMANTICS, 'units': 'model scene units (not metric)', 'renderer': 'gsplat rasterization render_mode=ED; foreground normalized expected camera z; sky excluded', 'native_resolution': list(GRID), 'positions': check_positions(positions), 'files': {c: 'depth.npz' for c in clips if (root / c / 'depth.npz').is_file()}, 'created_utc': datetime.now(timezone.utc).isoformat()} temp = root / 'depth_meta.tmp.json' temp.write_text(json.dumps(meta, indent=1, sort_keys=True) + '\n') temp.replace(root / 'depth_meta.json') return meta