File size: 6,151 Bytes
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A shot: camera track, static environment, entities (skeleton + motion track + identity slot). Renders the
condition video exactly in the BOSSV2V encoding, plus a preview grid, a first-frame overlay and a validation report,
and can run the stage-1 video model on it.

    scene = Scene(frames=121, fps=30, camera=Camera.look_at(...), env=ground_env())
    boss = scene.add("boss", skeleton, slot=2, root=(x, y, None), yaw=...)
    boss.gait(...); boss.throw_weapon(...)
    scene.render("out/", first_frame="first.png")
"""
import json, os, subprocess, sys
from pathlib import Path
import numpy as np
from PIL import Image
from .geometry import Camera
from .motion import Track
from .render import Renderer, VideoWriter, ReadableWriter, readable_rgb8
from . import validate as V

RUNS = "/data/yuzhewu/runs"


def ground_env(radius_cm=6000.0, z_cm=0.0, boxes=()):
    """Flat round arena at z with the sea far below (so the horizon stays dark red like the dataset) plus boxes."""
    return {"platform": {"radius_cm": float(radius_cm), "z_cm": float(z_cm)}, "sea_z_cm": -730.0, "boxes": list(boxes)}


def box(center, size, yaw_deg=0.0, label=2):
    return {"center_cm": [float(v) for v in center], "size_cm": [float(v) for v in size], "yaw_degrees": float(yaw_deg), "label": int(label)}


class Scene:
    def __init__(self, frames=121, fps=30, camera=None, env=None, width=1280, height=720):
        assert (frames - 1) % 8 == 0, "frames must be 8k+1 for the video VAE"
        self.frames, self.fps, self.w, self.h = frames, fps, width, height
        self.env = env or ground_env()
        self.cameras = [camera or Camera.look_at([0, -900, 220], [0, 0, 150])] * frames
        self.entities = {}

    # ---------------------------------------------------------------- building
    def add(self, name, skeleton, slot, root=(0, 0, None), yaw=0.0):
        assert 1 <= slot <= 7 and all(e["slot"] != slot for e in self.entities.values()), "slots must be unique 1..7"
        tr = Track(skeleton, self.frames, root, yaw)
        self.entities[name] = {"skeleton": skeleton, "slot": slot, "track": tr}
        return tr

    def camera_at(self, t):
        return self.cameras[t]

    def set_camera_track(self, fn):
        """fn(t) -> Camera for every frame."""
        self.cameras = [fn(t) for t in range(self.frames)]

    # ---------------------------------------------------------------- outputs
    def capsules(self, t):
        caps = []
        for ent in self.entities.values():
            w = ent["track"].weapon[t] if ent["track"].weapon is not None else None
            caps += ent["skeleton"].capsules(ent["track"].poses[t], ent["slot"], w)
        return caps

    def check(self, **kw):
        return V.check(self, floor_z=self.env["platform"]["z_cm"], **kw)

    def render(self, out, first_frame=None, device=None, train_scale=(1024, 576), overlay=False):
        """Writes readable.mp4 (colour-coded stick figures for people), cond.mp4 (1024x576 model input), shot.npz and
        report.json. overlay=True with first_frame also writes overlay_first_frame.png (for the agent's own alignment
        check; not a deliverable)."""
        out = Path(out); out.mkdir(parents=True, exist_ok=True)
        device = device if device is not None else int(os.environ.get("EGL_DEVICE", 4))
        report = self.check()
        rnd = Renderer(self.env, self.w, self.h, device)
        readable = ReadableWriter(out / "readable.mp4", self.w, self.h, self.fps)
        train = VideoWriter(out / "cond.mp4", self.w, self.h, self.fps, scale_to=train_scale)
        clipped, frame0 = 0, None
        try:
            for t in range(self.frames):
                rgb, stats = rnd.render(self.camera_at(t), self.capsules(t))
                clipped += stats["actor_depth_clipped"]
                readable.write(readable_rgb8(rgb)); train.write(rgb)
                if t == 0:
                    frame0 = rgb
        finally:
            readable.close(); train.close(); rnd.close()
        report["actor_depth_clipped_pixels"] = clipped
        if first_frame is not None:
            img = Image.open(first_frame).convert("RGB").resize((self.w, self.h))
            img.resize(train_scale).save(out / "first_frame.png")
            if overlay:
                cond = Image.fromarray(readable_rgb8(frame0))
                mask = Image.fromarray(((frame0[..., 1] > 0) * 255).astype(np.uint8))          # actors only
                over = img.copy(); over.paste(cond, (0, 0), mask)
                over.save(out / "overlay_first_frame.png")
        np.savez_compressed(out / "shot.npz", cameras=np.stack([c.transform() for c in self.cameras]),
                            **{f"{n}_poses": e["track"].poses for n, e in self.entities.items()},
                            **{f"{n}_weapon": e["track"].weapon for n, e in self.entities.items() if e["track"].weapon is not None})
        json.dump(report, open(out / "report.json", "w"), indent=1)
        return report

    def generate(self, out, prompt, lora=f"{RUNS}/ltx25_bossv2v121/checkpoints/lora_weights_step_06000.safetensors", gpu=4,
                 first_frame=True):
        """Run the stage-1 video model (1024x576@30, 121 frames) on out/cond.mp4. Returns the generated mp4 path."""
        out = Path(out)
        cmd = [f"/data/yuzhewu/venv_ltx/bin/python", f"{RUNS}/infer_v2v.py", "--config", f"{RUNS}/ltx25_bossv2v121.yaml",
               "--lora", lora, "--whitebox", str(out / "cond.mp4"), "--prompt", prompt, "--width", "1024", "--height", "576",
               "--frames", str(self.frames), "--fps", str(self.fps), "--out-dir", str(out / "gen")]
        if first_frame and (out / "first_frame.png").exists():
            cmd += ["--first-frame", str(out / "first_frame.png")]
        env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu))
        with open(out / "generate.log", "w") as log:
            subprocess.run(cmd, cwd="/data/yuzhewu/LTX-2/packages/ltx-trainer", env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
        vids = sorted((out / "gen" / "samples").glob("*.mp4"))
        assert vids, "generation produced no video"
        return vids[-1]