"""Convert OakInk2 into hand-warehouse/1.0. This file only converts and validates data. HTML/video review lives in ``render_oakink2_report.py``. Examples -------- python preprocess_oakink2.py inventory --root /data1/.../OakInk-v2 python preprocess_oakink2.py convert --root /data1/.../OakInk-v2 \ --mano-model-dir /path/to/mano/models --sequence python preprocess_oakink2.py full --root /data1/.../OakInk-v2 \ --mano-model-dir /path/to/mano/models --workers 2 """ from __future__ import annotations import argparse import codecs import collections import hashlib import io import json import os import pickle import shutil import subprocess import tarfile from concurrent.futures import ProcessPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path, PurePosixPath import numpy as np import torch from PIL import Image from scipy.spatial.transform import Rotation SCHEMA_VERSION = "hand-warehouse/1.0" RELEASE_ID = "shared-v1.0" RAW_REVISION = "85c3bfc9ad4d9a6b159e31ac036cf62c87b29076" OAKINK2_SPLIT_REVISION = "4cb9c461b92c032715374bd252c7179c70a14bde" def load_official_splits() -> dict[str, str]: split_root = Path(__file__).resolve().parent / "dataset_adapters" / "oakink2_sources" / "split" result: dict[str, str] = {} for split in ("train", "val", "test"): path = split_root / f"{split}.txt" if not path.is_file(): raise FileNotFoundError(f"Missing pinned official OakInk2 split list: {path}") for raw in path.read_text(encoding="utf-8").splitlines(): source_id = raw.strip() if not source_id: continue sequence_id = source_id.replace("/", "++") if sequence_id in result: raise RuntimeError(f"OakInk2 sequence occurs in more than one split: {sequence_id}") result[sequence_id] = split if len(result) != 627: raise RuntimeError(f"Expected 627 OakInk2 sequences in official split lists, found {len(result)}") return result OAKINK2_OFFICIAL_SPLITS = load_official_splits() def official_split_metadata(sequence: str) -> dict: if sequence not in OAKINK2_OFFICIAL_SPLITS: raise RuntimeError(f"Sequence is absent from pinned official OakInk2 split lists: {sequence}") split = OAKINK2_OFFICIAL_SPLITS[sequence] return { "split": split, "split_scheme": "OakInk2_TaMF_official_sequence_split", "split_source_locator": { "url": ( "https://github.com/oakink/OakInk2-TaMF/blob/" f"{OAKINK2_SPLIT_REVISION}/asset/split/{split}.txt" ), "sequence_key": sequence.replace("++", "/"), }, } def write_json(path: Path, value) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8") def write_jsonl(path: Path, rows) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8", newline="\n") as stream: for row in rows: stream.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n") def save_tensor(path: Path, value) -> None: path.parent.mkdir(parents=True, exist_ok=True) torch.save(torch.as_tensor(np.asarray(value).copy()), path) def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(8 << 20), b""): digest.update(block) return digest.hexdigest() def script_sha256() -> str: return sha256(Path(__file__).resolve()) # OakInk2 annotations are pickle files containing only NumPy arrays, tensors and # containers. Do not use pickle.load: it can import arbitrary Python objects. def _safe_torch_bytes(data: bytes): return torch.load(io.BytesIO(data), map_location="cpu", weights_only=True) class AnnotationUnpickler(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, ("torch._utils", "_rebuild_tensor_v2"): torch._utils._rebuild_tensor_v2, ("torch.storage", "_load_from_bytes"): _safe_torch_bytes, } if (module, name) not in allowed: raise pickle.UnpicklingError(f"forbidden pickle global: {module}.{name}") return allowed[(module, name)] def load_annotation(path: Path): with path.open("rb") as stream: value = AnnotationUnpickler(stream, encoding="latin1").load() required = { "cam_def", "cam_selection", "frame_id_list", "cam_intr", "cam_extr", "mocap_frame_id_list", "obj_list", "obj_transf", "raw_mano", } missing = required - value.keys() if missing: raise ValueError(f"{path.name}: missing fields {sorted(missing)}") return value class StoredState: def __setstate__(self, state): self.__dict__.update(state) class ManoModelUnpickler(AnnotationUnpickler): def find_class(self, module, name): if (module, name) in { ("chumpy.ch", "Ch"), ("chumpy.reordering", "Select"), ("scipy.sparse.csc", "csc_matrix"), }: return StoredState if (module, name) == ("__builtin__", "set"): return set return super().find_class(module, name) def _materialize_chumpy(value): if not isinstance(value, StoredState): return np.asarray(value) # MANO v1.2 shapedirs is a Chumpy Select object. return np.asarray(value.a.x).reshape(-1)[value.idxs].reshape(value.preferred_shape) def load_mano_data(model_dir: Path, side: str) -> dict: path = model_dir / f"MANO_{side.upper()}.pkl" if not path.is_file(): raise FileNotFoundError(f"MANO v1.2 model is required: {path}") with path.open("rb") as stream: data = ManoModelUnpickler(stream, encoding="latin1").load() data["shapedirs"] = _materialize_chumpy(data["shapedirs"]) data["v_template"] = _materialize_chumpy(data["v_template"]) sparse = data["J_regressor"] if isinstance(sparse, StoredState): regressor = np.zeros(sparse._shape, dtype=np.float64) for column in range(sparse._shape[1]): begin, end = sparse.indptr[column : column + 2] regressor[sparse.indices[begin:end], column] = sparse.data[begin:end] data["J_regressor"] = regressor return data def load_mano_roots(model_dir: Path) -> dict[str, dict[str, np.ndarray]]: result = {} for side in ("left", "right"): data = load_mano_data(model_dir, side) shapedirs = np.asarray(data["shapedirs"], dtype=np.float64) template = np.asarray(data["v_template"], dtype=np.float64) sparse = data["J_regressor"] regressor = np.asarray(sparse.toarray() if hasattr(sparse, "toarray") else sparse) if shapedirs.shape != (778, 3, 10) or template.shape != (778, 3) or regressor.shape != (16, 778): raise ValueError(f"unexpected MANO model shapes for {side}") result[side] = {"shapedirs": shapedirs, "template": template, "wrist": regressor[0]} return result def as_numpy(value) -> np.ndarray: if isinstance(value, torch.Tensor): value = value.detach().cpu().numpy() return np.asarray(value) def lookup(mapping: dict, key: int): if key in mapping: return mapping[key] if str(key) in mapping: return mapping[str(key)] raise KeyError(key) def quaternion_pose(rows: list[dict], prefix: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]: quaternion = np.stack([as_numpy(row[f"{prefix}__pose_coeffs"]).reshape(16, 4) for row in rows]) # Source convention is [w,x,y,z]; scipy expects [x,y,z,w]. pose = Rotation.from_quat(np.roll(quaternion.reshape(-1, 4), -1, axis=1)).as_rotvec().reshape(-1, 48) betas = np.stack([as_numpy(row[f"{prefix}__betas"]).reshape(10) for row in rows]) translation = np.stack([as_numpy(row[f"{prefix}__tsl"]).reshape(3) for row in rows]) return pose, betas, translation def camera_mano(pose, betas, source_translation, extrinsic, model) -> np.ndarray: shaped = model["template"][None] + np.einsum("vci,ti->tvc", model["shapedirs"], betas) wrist = np.einsum("v,tvc->tc", model["wrist"], shaped) # Official ManoLayer uses center_idx=0. source_translation places that # centered wrist in world coordinates; shared translation adds to the # ordinary flat-mean MANO output, hence the shape-dependent correction. world_translation = source_translation - wrist rotation = extrinsic[:, :3, :3] camera_pose = pose.copy() root_matrix = Rotation.from_rotvec(pose[:, :3]).as_matrix() camera_pose[:, :3] = Rotation.from_matrix(rotation @ root_matrix).as_rotvec() camera_translation = ( np.einsum("tij,tj->ti", rotation, wrist + world_translation) + extrinsic[:, :3, 3] - wrist ) return np.concatenate([camera_pose, betas, camera_translation], axis=1).astype(np.float32) def component(data_ref, valid_ref, schema_id, axes, valid_axes, source, **extra): return { "available": True, "data_ref": data_ref, "valid_ref": valid_ref, "schema_id": schema_id, "axes": axes, "valid_axes": valid_axes, "source_locator": source, "provenance": {"kind": "format_conversion"}, **extra, } def find_ffmpeg(explicit: str | None) -> str: if explicit: return explicit try: import imageio_ffmpeg return imageio_ffmpeg.get_ffmpeg_exe() except Exception as exc: raise RuntimeError("pass --ffmpeg or install imageio-ffmpeg") from exc def encode_rgb(tf: tarfile.TarFile, members: list[str], target: Path, ffmpeg: str, threads: int): first_bytes = tf.extractfile(members[0]).read() with Image.open(io.BytesIO(first_bytes)) as image: first = np.asarray(image.convert("RGB")) height, width = first.shape[:2] target.parent.mkdir(parents=True, exist_ok=True) command = [ ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24", "-video_size", f"{width}x{height}", "-framerate", "1", "-i", "pipe:0", "-an", "-c:v", "ffv1", "-level", "3", "-g", "1", "-threads", str(threads), str(target), ] process = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE) source_digest = hashlib.sha256() try: for index, member in enumerate(members): data = first_bytes if index == 0 else tf.extractfile(member).read() with Image.open(io.BytesIO(data)) as image: rgb = np.asarray(image.convert("RGB")) if rgb.shape != (height, width, 3): raise ValueError(f"image size changed: {member} {rgb.shape}") block = np.ascontiguousarray(rgb).tobytes() source_digest.update(block) process.stdin.write(block) process.stdin.close() error = process.stderr.read().decode("utf-8", "replace") code = process.wait() except Exception: process.kill() raise if code: raise RuntimeError(error) decoded = subprocess.Popen( [ffmpeg, "-hide_banner", "-loglevel", "error", "-threads", str(threads), "-i", str(target), "-pix_fmt", "rgb24", "-f", "rawvideo", "pipe:1"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) output_digest = hashlib.sha256() output_bytes = 0 while True: block = decoded.stdout.read(8 << 20) if not block: break output_digest.update(block) output_bytes += len(block) error = decoded.stderr.read().decode("utf-8", "replace") if decoded.wait(): raise RuntimeError(error) expected_bytes = len(members) * height * width * 3 if output_bytes != expected_bytes or output_digest.digest() != source_digest.digest(): raise ValueError("RGB round-trip mismatch") return width, height, source_digest.hexdigest() def safe_asset_name(name: str, prefix: str) -> str: relative = PurePosixPath(name).relative_to(PurePosixPath(prefix)) if not relative.parts or any(part in {"", ".", ".."} for part in relative.parts): raise ValueError(f"unsafe asset member: {name}") return relative.as_posix() def extract_object_assets(asset_tar: tarfile.TarFile, object_id: str, target: Path) -> Path | None: """Extract one object's immutable assets once for the whole sequence.""" prefix = f"object_repair/align_ds/{object_id}/" members = [member for member in asset_tar.getmembers() if member.isfile() and member.name.startswith(prefix)] for member in members: relative = safe_asset_name(member.name, prefix) output = target / relative output.parent.mkdir(parents=True, exist_ok=True) with asset_tar.extractfile(member) as source, output.open("wb") as destination: shutil.copyfileobj(source, destination) models = sorted(path for path in target.rglob("*") if path.suffix.lower() in {".obj", ".ply"}) return models[0].relative_to(target) if models else None def hardlink_tree(source: Path, target: Path) -> None: """Mirror immutable assets without storing four camera copies of each file.""" for path in source.rglob("*"): relative = path.relative_to(source) output = target / relative if path.is_dir(): output.mkdir(parents=True, exist_ok=True) elif path.is_file(): output.parent.mkdir(parents=True, exist_ok=True) try: os.link(path, output) except OSError: shutil.copy2(path, output) def manifest_map(root: Path) -> dict[str, dict]: path = root / "tmp/hf-download/manifest.json" if not path.is_file(): return {} data = json.loads(path.read_text(encoding="utf-8")) return {row["path"].split("OakInk-v2/", 1)[-1]: row for row in data["files"]} def source_identity(root: Path, sequence: str) -> dict: records = manifest_map(root) paths = [f"raw/data/data/{sequence}.tar", f"raw/data/anno_preview/{sequence}.pkl", "raw/data/object_repair.tar"] result = {} for path in paths: row = records.get(path) file_path = root / path if row: result[path] = {key: row[key] for key in ("size", "sha256", "git_oid") if key in row} else: result[path] = {"size": file_path.stat().st_size, "sha256": sha256(file_path)} return result def convert_sequence(root: Path, output: Path, model_dir: Path, sequence: str, ffmpeg: str, threads: int): raw = root / "raw/data" image_tar_path = raw / "data" / f"{sequence}.tar" annotation_path = raw / "anno_preview" / f"{sequence}.pkl" object_tar_path = raw / "object_repair.tar" for path in (image_tar_path, annotation_path, object_tar_path): if not path.is_file(): raise FileNotFoundError(path) identity = source_identity(root, sequence) checkpoint_dir = root / "tmp/oakink2-convert/checkpoints" checkpoint = checkpoint_dir / f"{sequence}.json" signature = {"script_sha256": script_sha256(), "source": identity, "output_root": str(output)} if checkpoint.is_file() and (output / "data" / sequence).is_dir(): previous = json.loads(checkpoint.read_text(encoding="utf-8")) if previous.get("signature") == signature and previous.get("status") == "complete": return {"sequence": sequence, "status": "skipped", "views": previous["views"]} annotation = load_annotation(annotation_path) frame_ids = [int(value) for value in annotation["frame_id_list"]] mocap_ids = {int(value) for value in annotation["mocap_frame_id_list"]} if not frame_ids or not set(frame_ids).issubset(mocap_ids): raise ValueError(f"{sequence}: image frames are not a subset of mocap frames") mano_rows = [lookup(annotation["raw_mano"], frame_id) for frame_id in frame_ids] mano_models = load_mano_roots(model_dir) partial = root / "tmp/oakink2-convert/partial" / sequence if partial.exists(): shutil.rmtree(partial) partial.mkdir(parents=True) views = [] with tarfile.open(image_tar_path, "r:*") as image_tar, tarfile.open(object_tar_path, "r:*") as object_tar: image_members = {member.name: member for member in image_tar.getmembers() if member.isfile()} asset_cache = partial / ".object-assets-cache" object_models = {} for object_id in annotation["obj_list"]: cache_root = asset_cache / object_id object_models[object_id] = extract_object_assets(object_tar, object_id, cache_root) selected_names = set(annotation["cam_selection"]) cameras = [serial for serial, name in annotation["cam_def"].items() if name in selected_names] if not cameras: raise ValueError(f"{sequence}: no selected cameras") for serial in cameras: camera_name = annotation["cam_def"][serial] members = [f"{sequence}/{serial}/{frame_id:06d}.png" for frame_id in frame_ids] missing = [member for member in members if member not in image_members] if missing: raise FileNotFoundError(f"{sequence}/{serial}: missing {len(missing)} RGB frames") intrinsic = np.stack([lookup(annotation["cam_intr"][camera_name], frame_id) for frame_id in frame_ids]).astype(np.float32) extrinsic = np.stack([lookup(annotation["cam_extr"][camera_name], frame_id) for frame_id in frame_ids]).astype(np.float32) if intrinsic.shape != (len(frame_ids), 3, 3) or extrinsic.shape != (len(frame_ids), 4, 4): raise ValueError(f"{sequence}/{serial}: invalid camera tensor shape") view = partial / serial width, height, rgb_digest = encode_rgb(image_tar, members, view / "observation/rgb.mkv", ffmpeg, threads) valid = np.ones(len(frame_ids), dtype=bool) save_tensor(view / "observation/rgb_valid.pt", valid) save_tensor(view / "camera/intrinsic.pt", intrinsic) save_tensor(view / "camera/intrinsic_valid.pt", valid) save_tensor(view / "camera/extrinsic.pt", extrinsic) save_tensor(view / "camera/extrinsic_valid.pt", valid) motion = np.full((len(frame_ids), 2, 61), np.nan, dtype=np.float32) for side_index, (side, prefix) in enumerate((("left", "lh"), ("right", "rh"))): pose, betas, translation = quaternion_pose(mano_rows, prefix) motion[:, side_index] = camera_mano(pose, betas, translation, extrinsic, mano_models[side]) mano_valid = np.isfinite(motion).all(axis=2) save_tensor(view / "annotation/mano/motion.pt", motion) save_tensor(view / "annotation/mano/motion_valid.pt", mano_valid) object_components = {} for object_id in annotation["obj_list"]: world = np.stack([lookup(annotation["obj_transf"][object_id], frame_id) for frame_id in frame_ids]).astype(np.float32) pose = extrinsic @ world pose_valid = np.isfinite(pose).all(axis=(1, 2)) object_root = view / "annotation/object" / object_id save_tensor(object_root / "pose.pt", pose) save_tensor(object_root / "pose_valid.pt", pose_valid) hardlink_tree(asset_cache / object_id, object_root / "assets") model_relative = object_models[object_id] mesh_ref = (object_root / "assets" / model_relative).relative_to(view).as_posix() if model_relative else None write_json(object_root / "metainfo.json", { "object_id": object_id, "source_object_id": object_id, "identity_scope": "sequence", "scope_id": sequence, "association_basis": "official OakInk2 obj_list and obj_transf", "has_model": mesh_ref is not None, "mesh_ref": mesh_ref, "unit": "m", "source_locator": {"archive": "raw/data/object_repair.tar", "object_id": object_id}, }) object_components[f"object_{object_id}_pose"] = component( f"annotation/object/{object_id}/pose.pt", f"annotation/object/{object_id}/pose_valid.pt", "object/rigid/v1", ["T", "row", "column"], ["T"], {"file": f"raw/data/anno_preview/{sequence}.pkl", "field": f"obj_transf.{object_id}"}, unit="m", convention="T_camera_from_object", object_type="rigid", entity_id=object_id, ) frame_rows = [] for index, frame_id in enumerate(frame_ids): match = { "source_frame_id": str(frame_id), "source_timestamp_ns": None, "clock_domain": None, "match_method": "exact", "delta_ns": None, "source_record_present": True, } frame_rows.append({ "frame_index": index, "source_frame_id": str(frame_id), "timestamp_ns": None, "clock_domain": None, "sync_id": f"{sequence}:{frame_id}", "source_locator": {"archive": f"raw/data/data/{sequence}.tar", "member": members[index]}, "annotation_matches": {"camera": match, "mano": match, "object": match}, }) write_jsonl(view / "camera/frames.jsonl", frame_rows) components = { "rgb": component( "observation/rgb.mkv", "observation/rgb_valid.pt", "rgb/uint8/v1", ["T", "height", "width", "channel"], ["T"], {"archive": f"raw/data/data/{sequence}.tar", "member_pattern": f"{sequence}/{serial}/{{source_frame_id}}.png"}, storage={"profile": "mkv/ffv1_rgb/v1", "codec": "ffv1", "pixel_format": "bgr0", "decoded_pixel_format": "rgb24", "source_lossy": False, "roundtrip_rgb_sha256": rgb_digest}, storage_fps=1, timebase_role="index_only", ), "intrinsic": component( "camera/intrinsic.pt", "camera/intrinsic_valid.pt", "camera/pinhole/v1", ["T", "row", "column"], ["T"], {"file": f"raw/data/anno_preview/{sequence}.pkl", "field": f"cam_intr.{camera_name}"}, ), "extrinsic": component( "camera/extrinsic.pt", "camera/extrinsic_valid.pt", "transform/se3/v1", ["T", "row", "column"], ["T"], {"file": f"raw/data/anno_preview/{sequence}.pkl", "field": f"cam_extr.{camera_name}"}, unit="m", convention="T_camera_from_world", ), "mano": component( "annotation/mano/motion.pt", "annotation/mano/motion_valid.pt", "mano/axis_angle61/v1", ["T", "hand", "parameter"], ["T", "hand"], {"file": f"raw/data/anno_preview/{sequence}.pkl", "field": "raw_mano", "time_index_ref": "camera/frames.jsonl:annotation_matches.mano"}, unit="m", angle_unit="rad", coordinate_frame="camera", model_profile={"version": "MANO-v1.2", "flat_hand_mean": True, "left_shapedirs_fix": False}, provenance={"kind": "format_conversion", "method": "source wxyz quaternion to axis-angle; official center_idx=0 wrist correction; world-to-camera transform"}, ), **object_components, } metadata = { "schema_version": SCHEMA_VERSION, "dataset_id": "OakInk2", "release_id": RELEASE_ID, "sequence_id": sequence, "camera_id": serial, "sample_type": "video", "num_frames": len(frame_ids), "hand_slots": ["left", "right"], "sampling": { "type": "dense", "source_fps": 30.0, "frames_ref": "camera/frames.jsonl", "selection": "all official frame_id_list images for this complete sequence and selected camera", "source_fps_evidence": "OakInk2 CVPR 2024 paper section 4.1: four synchronized RGB views at 30 fps", "mocap_alignment": "image frame IDs are an exact subset of mocap_frame_id_list; image IDs advance by four on the shared source frame clock, while all released 30 fps image frames are retained", }, "camera": {"model": "pinhole", "schema_id": "camera/pinhole/v1", "image_size": [width, height]}, "components": components, **official_split_metadata(sequence), "view_type": "ego" if camera_name == "egocentric" else "exo", "source_camera_name": camera_name, "omitted_components": { "depth": "not provided by the downloaded official OakInk2 release", "segment": "no official pixel mask is present in the downloaded release", "contact": "not selected for this hand-object reconstruction release", "smplx": "full-body parameters are outside the selected hand-object reconstruction fields", "program": "task-language/program annotations are outside the selected geometric training fields", }, "source_release": {"repository": "ParityLab/Hand-Datasets-Raw", "revision": RAW_REVISION}, } write_json(view / "metainfo.json", metadata) views.append({"camera_id": serial, "view_type": metadata["view_type"], "frames": len(frame_ids)}) shutil.rmtree(asset_cache) final = output / "data" / sequence final.parent.mkdir(parents=True, exist_ok=True) if final.exists(): shutil.rmtree(final) partial.replace(final) write_json(checkpoint, {"status": "complete", "sequence": sequence, "views": views, "signature": signature}) return {"sequence": sequence, "status": "converted", "views": views} def sequence_names(root: Path) -> list[str]: annotation_root = root / "raw/data/anno_preview" image_root = root / "raw/data/data" annotations = {path.stem for path in annotation_root.glob("*.pkl")} images = {path.stem for path in image_root.glob("*.tar")} if annotations != images: raise ValueError(f"annotation/image mismatch: annotation-only={len(annotations-images)}, image-only={len(images-annotations)}") return sorted(annotations) def run_convert(args, names: list[str]) -> None: root = Path(args.root).resolve() output = Path(args.output or root / RELEASE_ID).resolve() model_dir = Path(args.mano_model_dir).resolve() ffmpeg = find_ffmpeg(args.ffmpeg) runtime = root / "tmp/oakink2-convert" status_path = runtime / "status.json" lock_path = runtime / "run.lock" runtime.mkdir(parents=True, exist_ok=True) lock_stream = lock_path.open("a+", encoding="utf-8") try: import fcntl fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except (ImportError, BlockingIOError) as error: lock_stream.close() raise RuntimeError(f"another OakInk2 converter holds {lock_path}") from error started_at = datetime.now(timezone.utc).isoformat() state = { "stage": "running", "started_at": started_at, "updated_at": started_at, "pid": os.getpid(), "total_sequences": len(names), "completed_sequences": 0, "workers": args.workers, "ffmpeg_threads": args.ffmpeg_threads, "output": str(output), "last_result": None, } write_json(status_path, state) try: if args.workers == 1: iterator = (convert_sequence(root, output, model_dir, name, ffmpeg, args.ffmpeg_threads) for name in names) else: pool = ProcessPoolExecutor(max_workers=args.workers) futures = [pool.submit(convert_sequence, root, output, model_dir, name, ffmpeg, args.ffmpeg_threads) for name in names] iterator = (future.result() for future in as_completed(futures)) for result in iterator: print(json.dumps(result), flush=True) state["completed_sequences"] += 1 state["last_result"] = result state["updated_at"] = datetime.now(timezone.utc).isoformat() write_json(status_path, state) if args.workers != 1: pool.shutdown() state["stage"] = "complete" except Exception as error: state["stage"] = "failed" state["error_type"] = type(error).__name__ state["error"] = str(error) raise finally: state["updated_at"] = datetime.now(timezone.utc).isoformat() write_json(status_path, state) lock_stream.close() def main() -> None: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) inventory = sub.add_parser("inventory") inventory.add_argument("--root", required=True) for command in ("convert", "full"): item = sub.add_parser(command) item.add_argument("--root", required=True) item.add_argument("--output") item.add_argument("--mano-model-dir", required=True) item.add_argument("--ffmpeg") item.add_argument("--ffmpeg-threads", type=int, default=2) item.add_argument("--workers", type=int, default=1) if command == "convert": item.add_argument("--sequence", action="append", required=True) args = parser.parse_args() root = Path(args.root).resolve() names = sequence_names(root) if args.command == "inventory": print(json.dumps({"sequences": len(names), "first": names[:10]}, indent=2)) elif args.command == "convert": unknown = sorted(set(args.sequence) - set(names)) if unknown: raise ValueError(f"unknown sequences: {unknown}") run_convert(args, args.sequence) else: run_convert(args, names) if __name__ == "__main__": main()