| """User input loader. |
| |
| Expected directory layout under ``--input-dir``: |
| |
| inputs/case_xxx/ |
| first_frame.png (H, W, 3) uint8 |
| prompt.txt text prompt (scene description) |
| geometry.npz keys: poses_c2w (N, 4, 4), K (3, 3), |
| intrinsics_size (2,) optional |
| pointcloud.npz keys: points (M, 3) float32 |
| fg_mask_first.png optional, single-channel; >0 = foreground |
| bg_projection.mp4 required when condition_source="mp4" |
| fg_projection.mp4 optional FG conditioning video |
| |
| For the CSV / four-field path (``load_user_inputs_from_paths``), only |
| ``input_image``, ``text``, ``bg_projection``, ``fg_projection`` are required; |
| dummy identity poses + a tiny point cloud are synthesized so the existing |
| ``condition_source="mp4"`` pipeline path still works (geometry is unused for |
| scene rendering in that mode). |
| |
| All geometry must be in the same world coordinate system; intrinsics ``K`` is |
| defined at ``intrinsics_size`` (defaults to first_frame resolution). |
| """ |
| from __future__ import annotations |
|
|
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Optional, Tuple, Union |
|
|
| import cv2 |
| import numpy as np |
| from PIL import Image |
|
|
|
|
| @dataclass |
| class UserInputs: |
| first_frame: np.ndarray |
| first_frame_pil: Image.Image |
| prompt: str |
| poses_c2w: np.ndarray |
| K: np.ndarray |
| intrinsics_size: Tuple[int, int] |
| points_world: np.ndarray |
| fg_mask: Optional[np.ndarray] |
| |
| |
| scene_proj_frames: Optional[np.ndarray] = None |
| fg_proj_frames: Optional[np.ndarray] = None |
|
|
|
|
| def _load_image_rgb(path: Path) -> np.ndarray: |
| img_bgr = cv2.imread(str(path), cv2.IMREAD_COLOR) |
| if img_bgr is None: |
| raise FileNotFoundError(f"Cannot read image: {path}") |
| return cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) |
|
|
|
|
| def _maybe_resize_image(img: np.ndarray, target_hw: Tuple[int, int]) -> np.ndarray: |
| H, W = target_hw |
| if img.shape[:2] == (H, W): |
| return img |
| return cv2.resize(img, (W, H), interpolation=cv2.INTER_LINEAR) |
|
|
|
|
| def _maybe_resize_mask(mask: np.ndarray, target_hw: Tuple[int, int]) -> np.ndarray: |
| H, W = target_hw |
| if mask.shape[:2] == (H, W): |
| return mask |
| return cv2.resize(mask.astype(np.uint8), (W, H), |
| interpolation=cv2.INTER_NEAREST).astype(bool) |
|
|
|
|
| def _scale_intrinsics(K: np.ndarray, |
| src_hw: Tuple[int, int], |
| dst_hw: Tuple[int, int]) -> np.ndarray: |
| if src_hw == dst_hw: |
| return K.astype(np.float32) |
| sh, sw = src_hw |
| dh, dw = dst_hw |
| K_new = K.copy().astype(np.float32) |
| K_new[0, 0] *= dw / sw |
| K_new[1, 1] *= dh / sh |
| K_new[0, 2] *= dw / sw |
| K_new[1, 2] *= dh / sh |
| return K_new |
|
|
|
|
| def make_dummy_geometry(n_poses: int, |
| target_hw: Tuple[int, int] |
| ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: |
| """Synthesize identity poses + a pinhole K + a tiny point cloud. |
| |
| Used by the CSV / four-field path when ``condition_source="mp4"``: scene |
| and FG come from precomputed videos, so real geometry is unused for |
| rendering. The loader / pipeline still expect these arrays to exist |
| (anchors + optional multi-iter IoU), so we fill safe placeholders. |
| """ |
| if n_poses < 1: |
| raise ValueError(f"n_poses must be >= 1, got {n_poses}") |
| H, W = int(target_hw[0]), int(target_hw[1]) |
| poses = np.eye(4, dtype=np.float32)[None].repeat(n_poses, axis=0) |
| |
| fx = fy = float(max(H, W)) |
| K = np.array([[fx, 0.0, W / 2.0], |
| [0.0, fy, H / 2.0], |
| [0.0, 0.0, 1.0]], dtype=np.float32) |
| |
| points = np.array([[0.0, 0.0, 2.0]], dtype=np.float32) |
| return poses, K, points |
|
|
|
|
| def _resolve_prompt(text: str) -> str: |
| """Accept either an inline prompt string or a path to a ``.txt`` file.""" |
| raw = str(text).strip() |
| if not raw: |
| raise ValueError("empty text / prompt") |
| p = Path(raw) |
| if p.is_file() and p.suffix.lower() in {".txt", ".prompt"}: |
| raw = p.read_text(encoding="utf-8").strip() |
| if not raw: |
| raise ValueError(f"Empty prompt file: {p}") |
| return raw |
|
|
|
|
| def load_user_inputs_from_paths( |
| input_image: Union[str, Path], |
| text: str, |
| bg_projection: Union[str, Path], |
| fg_projection: Optional[Union[str, Path]] = None, |
| target_hw: Tuple[int, int] = (480, 832), |
| n_poses: Optional[int] = None, |
| ) -> UserInputs: |
| """Load the four-field CSV-style inputs directly (no case folder needed). |
| |
| Parameters |
| ---------- |
| input_image: |
| Path to the first-frame RGB image. |
| text: |
| Inline prompt, or a path to a ``.txt`` prompt file. |
| bg_projection: |
| Path to ``bg_projection.mp4`` (static / scene conditioning). |
| fg_projection: |
| Optional path to ``fg_projection.mp4``. Pass ``None`` / empty to skip. |
| target_hw: |
| Inference resolution ``(H, W)``. |
| n_poses: |
| Length of the dummy pose trajectory. Defaults to |
| ``len(bg_frames)`` so indexing never overflows the video length. |
| """ |
| from .precomputed import read_video_frames |
|
|
| img_path = Path(input_image) |
| bg_path = Path(bg_projection) |
| if not img_path.exists(): |
| raise FileNotFoundError(f"input_image missing: {img_path}") |
| if not bg_path.exists(): |
| raise FileNotFoundError(f"bg_projection missing: {bg_path}") |
|
|
| prompt = _resolve_prompt(text) |
|
|
| first_frame_raw = _load_image_rgb(img_path) |
| first_frame = _maybe_resize_image(first_frame_raw, target_hw) |
| first_frame_pil = Image.fromarray(first_frame) |
|
|
| scene_proj_frames = read_video_frames(bg_path, target_hw) |
| fg_proj_frames: Optional[np.ndarray] = None |
| if fg_projection: |
| fg_path = Path(fg_projection) |
| if str(fg_path).strip() and fg_path.exists(): |
| fg_proj_frames = read_video_frames(fg_path, target_hw) |
| elif str(fg_path).strip(): |
| raise FileNotFoundError(f"fg_projection missing: {fg_path}") |
|
|
| n = int(n_poses) if n_poses is not None else max(1, len(scene_proj_frames)) |
| poses_c2w, K, points_world = make_dummy_geometry(n, target_hw) |
|
|
| return UserInputs( |
| first_frame=first_frame, |
| first_frame_pil=first_frame_pil, |
| prompt=prompt, |
| poses_c2w=poses_c2w, |
| K=K, |
| intrinsics_size=tuple(target_hw), |
| points_world=points_world, |
| fg_mask=None, |
| scene_proj_frames=scene_proj_frames, |
| fg_proj_frames=fg_proj_frames, |
| ) |
|
|
|
|
| def load_user_inputs(input_dir: str | Path, |
| target_hw: Tuple[int, int], |
| *, |
| allow_dummy_geometry: bool = False) -> UserInputs: |
| """Load all user-provided inputs and align them to target resolution. |
| |
| target_hw is the (H, W) at which inference runs (typically 480x832 for the |
| 14B LiveWorld checkpoint). First frame and fg_mask are resized to this. |
| Intrinsics K is rescaled from its source resolution to target_hw and stored |
| at target_hw (so intrinsics_size in the returned object == target_hw). |
| |
| If ``allow_dummy_geometry=True`` and ``geometry.npz`` / ``pointcloud.npz`` |
| are missing but ``bg_projection.mp4`` is present, identity poses + a tiny |
| PC are synthesized (for ``condition_source="mp4"`` only). |
| """ |
| root = Path(input_dir) |
| if not root.is_dir(): |
| raise FileNotFoundError(f"input-dir not found: {root}") |
|
|
| first_frame_path = root / "first_frame.png" |
| prompt_path = root / "prompt.txt" |
| geometry_path = root / "geometry.npz" |
| pointcloud_path = root / "pointcloud.npz" |
| fg_mask_path = root / "fg_mask_first.png" |
| bg_video_path = root / "bg_projection.mp4" |
| fg_video_path = root / "fg_projection.mp4" |
|
|
| for p in (first_frame_path, prompt_path): |
| if not p.exists(): |
| raise FileNotFoundError(f"Required input missing: {p}") |
|
|
| missing_geom = (not geometry_path.exists()) or (not pointcloud_path.exists()) |
| if missing_geom and not (allow_dummy_geometry and bg_video_path.exists()): |
| for p in (geometry_path, pointcloud_path): |
| if not p.exists(): |
| raise FileNotFoundError(f"Required input missing: {p}") |
|
|
| first_frame_raw = _load_image_rgb(first_frame_path) |
| src_hw = first_frame_raw.shape[:2] |
| first_frame = _maybe_resize_image(first_frame_raw, target_hw) |
| first_frame_pil = Image.fromarray(first_frame) |
|
|
| prompt = prompt_path.read_text(encoding="utf-8").strip() |
| if not prompt: |
| raise ValueError(f"Empty prompt: {prompt_path}") |
|
|
| |
| |
| scene_proj_frames: Optional[np.ndarray] = None |
| fg_proj_frames: Optional[np.ndarray] = None |
| if bg_video_path.exists() or fg_video_path.exists(): |
| from .precomputed import read_video_frames |
| if bg_video_path.exists(): |
| scene_proj_frames = read_video_frames(bg_video_path, target_hw) |
| if fg_video_path.exists(): |
| fg_proj_frames = read_video_frames(fg_video_path, target_hw) |
|
|
| if missing_geom: |
| n = max(1, len(scene_proj_frames) if scene_proj_frames is not None else 1) |
| poses_c2w, K, points_world = make_dummy_geometry(n, target_hw) |
| print(f"[input] dummy geometry: poses={poses_c2w.shape}, " |
| f"points={points_world.shape} (mp4-only path)") |
| else: |
| geom = np.load(geometry_path) |
| if "poses_c2w" in geom.files: |
| poses_c2w = geom["poses_c2w"].astype(np.float32) |
| elif "poses" in geom.files: |
| poses_c2w = geom["poses"].astype(np.float32) |
| elif "c2w" in geom.files: |
| poses_c2w = geom["c2w"].astype(np.float32) |
| else: |
| raise KeyError(f"No poses_c2w/poses/c2w in {geometry_path}") |
|
|
| if "K" in geom.files: |
| K_raw = geom["K"].astype(np.float32) |
| elif "intrinsics" in geom.files: |
| K_raw = geom["intrinsics"].astype(np.float32) |
| else: |
| raise KeyError(f"No K/intrinsics in {geometry_path}") |
| if K_raw.shape != (3, 3): |
| raise ValueError(f"K must be (3, 3), got {K_raw.shape}") |
|
|
| if "intrinsics_size" in geom.files: |
| intr_src_hw = tuple(int(v) for v in geom["intrinsics_size"].tolist()) |
| if len(intr_src_hw) != 2: |
| raise ValueError(f"intrinsics_size must be (H, W), got {intr_src_hw}") |
| else: |
| intr_src_hw = src_hw |
|
|
| K = _scale_intrinsics(K_raw, intr_src_hw, target_hw) |
|
|
| pc = np.load(pointcloud_path) |
| if "points" not in pc.files: |
| raise KeyError(f"No 'points' in {pointcloud_path}") |
| points_world = pc["points"].astype(np.float32) |
| if points_world.ndim != 2 or points_world.shape[1] != 3: |
| raise ValueError(f"points must be (M, 3), got {points_world.shape}") |
|
|
| fg_mask: Optional[np.ndarray] = None |
| if fg_mask_path.exists(): |
| m_raw = cv2.imread(str(fg_mask_path), cv2.IMREAD_GRAYSCALE) |
| if m_raw is None: |
| raise RuntimeError(f"Failed to read fg_mask: {fg_mask_path}") |
| fg_mask = _maybe_resize_mask(m_raw > 0, target_hw) |
|
|
| return UserInputs( |
| first_frame=first_frame, |
| first_frame_pil=first_frame_pil, |
| prompt=prompt, |
| poses_c2w=poses_c2w, |
| K=K, |
| intrinsics_size=tuple(target_hw), |
| points_world=points_world, |
| fg_mask=fg_mask, |
| scene_proj_frames=scene_proj_frames, |
| fg_proj_frames=fg_proj_frames, |
| ) |
|
|