File size: 11,917 Bytes
1d15e3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
310
311
312
313
314
315
316
317
318
"""Build identical reference-only conditions for overlap-supervised Voyager training and sampling."""

import argparse
from contextlib import contextmanager
from functools import wraps
import gzip
import hashlib
import json
from pathlib import Path
from unittest.mock import patch

import cv2
import numpy as np
from PIL import Image

from full_coverage_windows import crop_matrix, source_arrays, warp
from prepare_cave_completion import domains, first_view, view_matrices
from prepare_scene_assets import digest
from scene_training_data import norm, ranges

PROMPT = "Documentary footage inside an underground construction tunnel."


def ref_caption(rgb, captions):
    value = captions.get(digest(rgb), PROMPT)
    if not isinstance(value, str) or not value.strip():
        raise ValueError(
            "Reference captions must be non-empty strings keyed by reference pixel digest"
        )
    return value.strip()


def rows_at(path):
    with gzip.open(path, "rt") as f:
        return [json.loads(line) for line in f]


def semantic_photo(rgb):
    # Padding the full RGB field makes the CLIP center crop retain both ceiling and floor.
    image = Image.fromarray(rgb) if isinstance(rgb, np.ndarray) else rgb.convert("RGB")
    side = max(image.size)
    canvas = Image.new("RGB", (side, side), (123, 117, 104))
    canvas.paste(image, ((side - image.width) // 2, (side - image.height) // 2))
    return canvas


def semantic_training_rgb(ref):
    # Voyager normalizes the image, then converts the packed float plane back
    # to uint8 before calling LLaVA. Match its truncation at byte boundaries.
    normalized = (ref.astype(np.float32) / 255.0 - 0.5) / 0.5
    image = ((np.clip(normalized, -1, 1) + 1) * 0.5 * 255).astype(np.uint8)
    return semantic_photo(image)


@contextmanager
def inference_semantics():
    from voyager.diffusion.pipelines.pipeline_hunyuan_video import HunyuanVideoPipeline

    original = HunyuanVideoPipeline.encode_prompt

    @wraps(original)
    def encode(pipeline, *args, **kwargs):
        packed = kwargs.get("semantic_images")
        if packed is not None:
            inputs = []
            for image in packed:
                w, total = image.size
                h = (total - 16) // 2
                if h <= 0 or h % 16 or total != 2 * h + 16:
                    raise ValueError(f"Unexpected Voyager RGB-D layout {image.size}")
                inputs.append(semantic_photo(image.crop((0, 0, w, h))))
            kwargs["semantic_images"] = inputs
        return original(pipeline, *args, **kwargs)

    with patch.object(HunyuanVideoPipeline, "encode_prompt", encode):
        yield


def prepare_depth(base, rows, directory, model_path, device):
    import torch
    from moge.model.v1 import MoGeModel

    directory.mkdir(parents=True, exist_ok=True)
    model = MoGeModel.from_pretrained(str(model_path)).to(device).eval()
    used = set()
    with torch.inference_mode():
        for r in rows:
            if r["kind"] != "viewport" or (r["source"], r["start"]) in used:
                continue
            used.add((r["source"], r["start"]))
            ref = first_view(base, r)
            path = directory / (digest(ref) + ".npy")
            if path.is_file():
                continue
            x = torch.from_numpy(ref.copy()).to(device).permute(2, 0, 1).float() / 255
            z = (
                model.infer(x, resolution_level=5, force_projection=False)["depth"]
                .cpu()
                .float()
                .numpy()
            )
            good = np.isfinite(z) & (z > 0)
            inv = np.divide(1.0, z, out=np.full_like(z, np.nan), where=good)
            ranges(inv)
            tmp = path.with_suffix(".part")
            with tmp.open("wb") as f:
                np.save(f, inv)
            tmp.replace(path)
    return len(used)


def arrays(base, depth_dir, row):
    if row["kind"] == "still_pair":
        path = depth_dir / "arrays" / (row["id"] + ".npz")
        with path.open("rb") as fp:
            if hashlib.file_digest(fp, "sha256").hexdigest() != row["arrays_sha256"]:
                raise ValueError(f"Cross-photo supervision changed for {row['id']}")
        with np.load(path, allow_pickle=False) as archive:
            return {key: archive[key] for key in archive.files}
    w, h, n = row["width"], row["height"], row["length"]
    sid, start = row["source"], row["start"]
    meta, images, depths = source_arrays(base, sid)
    limits = np.load(base / "sources" / sid / "ranges.npy", mmap_mode="r")

    def physical(i):
        lo, hi = limits[i]
        return depths[i].astype(np.float32) * (hi - lo) + lo

    A = crop_matrix(w, h) if row["kind"] == "viewport" else None
    full = physical(start)
    ref = first_view(base, row)
    support = None
    if row.get("source_box") is not None:
        from cave_reference_support import ReferenceSupport, content_box

        box = content_box(ref, meta, row["kind"])
        if list(box) != row["source_box"] or A is not None:
            raise ValueError(
                f"Reference source support disagrees with the recorded endpoint {row['id']}"
            )
        support = ReferenceSupport(ref, box)
        ref = support.image
    rinv = full.copy() if A is None else np.load(depth_dir / (digest(ref) + ".npy"))
    lo, hi = ranges(rinv)
    if A is not None:
        # Reconcile two monocular scales on overlapping rays for labels only.
        common = warp(full, A, w, h)
        ok = np.isfinite(common) & (common > 0) & np.isfinite(rinv) & (rinv > 0)
        if ok.sum() < 64:
            raise ValueError("Insufficient depth overlap")
        q = np.percentile(common[ok], [15, 85])
        p = np.percentile(rinv[ok], [15, 85])
        scale = np.clip((p[1] - p[0]) / max(1e-6, q[1] - q[0]), 0.25, 4)
        full = full * scale + np.median(rinv[ok] - common[ok] * scale)
    yy, xx = np.indices((h, w), dtype=np.float32)
    values = {
        k: []
        for k in (
            "cond",
            "cond_depth",
            "known",
            "target",
            "depth",
            "dvalid",
            "valid",
            "novel",
            "alpha",
        )
    }
    for j, H in enumerate(view_matrices(row)):
        known, valid, novel = domains(H, A, w, h)
        if support is not None:
            known = support.project_mask(H, known)
            valid = valid & (support.valid > 0)
            novel = valid & (
                cv2.distanceTransform((~known).astype(np.uint8), cv2.DIST_L2, 5) > 2
            )
        ref_zratio = H[2, 0] * xx + H[2, 1] * yy + H[2, 2]
        rd = warp(norm(rinv / np.maximum(ref_zratio, 1e-5), lo, hi), H, w, h) * known
        if A is None:
            idx = row["indices"][j]
            truth = np.asarray(images[idx])
            target_inv = physical(idx)
            if support is not None:
                truth = support.extend(truth)
                target_inv = support.extend(target_inv)
            # Normalize real per-view monocular predictions in the projected reference scale.
            good = (
                known
                & np.isfinite(target_inv)
                & (target_inv > 0)
                & (rd > 0.04)
                & (rd < 0.96)
            )
            if good.sum() >= 64:
                a, b = np.percentile(target_inv[good], [15, 85])
                c, d = np.percentile(rd[good] * (hi - lo) + lo, [15, 85])
                gain = np.clip((d - c) / max(b - a, 1e-6), 0.25, 4)
                target_inv = target_inv * gain + np.median(
                    rd[good] * (hi - lo) + lo - gain * target_inv[good]
                )
        else:
            G = H @ A
            truth = warp(images[start], G, w, h)
            full_zratio = np.maximum(G[2, 0] * xx + G[2, 1] * yy + G[2, 2], 1e-5)
            target_inv = warp(full / full_zratio, G, w, h)
        cond = warp(ref, H, w, h)
        cond[~known] = 0
        values["cond"].append(cond)
        values["cond_depth"].append(rd)
        values["known"].append(known)
        values["target"].append(truth)
        values["depth"].append(norm(target_inv, lo, hi))
        values["dvalid"].append(valid & np.isfinite(target_inv) & (target_inv > 0))
        values["valid"].append(valid)
        values["novel"].append(novel)
        values["alpha"].append(
            cv2.distanceTransform(known.astype(np.uint8), cv2.DIST_L2, 5)
        )
    if n != len(values["target"]) or not values["novel"][-1].any():
        raise ValueError("Unusable target sequence")
    return dict(
        ref=ref,
        ref_depth=norm(rinv, lo, hi),
        **{k: np.stack(v) for k, v in values.items()},
    )


def export_case(base, depth_dir, row, root, captions=None):
    import pyexr

    value = arrays(base, depth_dir, row)
    dest = root / "cases" / row["id"]
    cond = dest / "video_input"
    labels = dest / "target"
    cond.mkdir(parents=True, exist_ok=True)
    labels.mkdir(exist_ok=True)
    Image.fromarray(value["ref"]).save(dest / "ref_image.png")
    from cave_reference_support import content_box

    metadata = json.loads(
        (base / "sources" / row["source"] / "source.json").read_text()
    )
    box = row.get("source_box") or content_box(value["ref"], metadata, row["kind"])
    (dest / "reference_support.json").write_text(json.dumps({"xyxy": list(box)}) + "\n")
    pyexr.write(str(dest / "ref_depth.exr"), value["ref_depth"].astype(np.float32))
    for j in range(row["length"]):
        stem = f"{j:04d}"
        Image.fromarray(value["cond"][j]).save(cond / f"render_{stem}.png")
        Image.fromarray(value["known"][j].astype(np.uint8) * 255).save(
            cond / f"mask_{stem}.png"
        )
        pyexr.write(
            str(cond / f"depth_{stem}.exr"), value["cond_depth"][j].astype(np.float32)
        )
        Image.fromarray(value["target"][j]).save(labels / f"rgb_{stem}.png")
        for key in ("valid", "novel"):
            Image.fromarray(value[key][j].astype(np.uint8) * 255).save(
                labels / f"{key}_{stem}.png"
            )
    (dest / "path.json").write_text(
        json.dumps(dict(homographies=[H.tolist() for H in view_matrices(row)]))
    )
    return dict(
        case=row["id"],
        source=row["source"],
        kind=row["kind"],
        height=row["height"],
        width=row["width"],
        frames=row["length"],
        fps=8,
        prompt=ref_caption(value["ref"], captions or {}),
        seeds=[0, 42, 123],
    )


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("mode", choices=["depth", "cases"])
    for k in ("base", "manifest", "depth-dir"):
        p.add_argument("--" + k, type=Path, required=True)
    p.add_argument("--model", type=Path)
    p.add_argument("--device", default="cuda:0")
    p.add_argument("--output", type=Path)
    p.add_argument("--ids", nargs="+")
    p.add_argument(
        "--ref-captions",
        type=Path,
        help="Reviewed prompts keyed by exact reference pixel digest",
    )
    args = p.parse_args()
    rows = rows_at(args.manifest)
    if args.mode == "depth":
        if not args.model:
            p.error("--model is required for depth")
        print(
            "unique cropped reference frames",
            prepare_depth(args.base, rows, args.depth_dir, args.model, args.device),
        )
    else:
        if not args.ids or not args.output:
            p.error("--ids and --output are required for cases")
        lookup = {r["id"]: r for r in rows}
        captions = (
            json.loads(args.ref_captions.read_text()) if args.ref_captions else {}
        )
        panel = [
            export_case(args.base, args.depth_dir, lookup[i], args.output, captions)
            for i in args.ids
        ]
        (args.output / "cases/panel.json").write_text(
            json.dumps(panel, indent=2) + "\n"
        )


if __name__ == "__main__":
    main()