File size: 12,312 Bytes
d615d4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""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            # (H, W, 3) uint8 at target_hw
    first_frame_pil: Image.Image       # PIL image at target_hw
    prompt: str
    poses_c2w: np.ndarray              # (N, 4, 4) float32
    K: np.ndarray                      # (3, 3) float32 at intrinsics_size
    intrinsics_size: Tuple[int, int]   # (H, W) of K's reference resolution
    points_world: np.ndarray           # (M, 3) float32
    fg_mask: Optional[np.ndarray]      # (H, W) bool at target_hw, or None
    # Precomputed projection videos (condition_source="mp4"). Each is
    # (T, H, W, 3) uint8 at target_hw, or None if the file was absent.
    scene_proj_frames: Optional[np.ndarray] = None   # from bg_projection.mp4
    fg_proj_frames: Optional[np.ndarray] = None       # from fg_projection.mp4


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)
    # Mild wide-ish pinhole covering the frame; unused under mp4 conditioning.
    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)
    # One point in front of the camera so IoU / coloring never hit empty arrays.
    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}")

    # Precomputed projection videos (optional; required when
    # condition_source="mp4"). Loaded early so dummy-geometry length can match.
    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  # assume K is at first_frame's source resolution

        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,
    )