File size: 9,503 Bytes
567e51a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Extract context and prediction panels from a four-grid rollout mp4.

The eval videos produced by eval.py/eval_hyperbolic.py use this layout:

    top-left:     model-controlled rollout frame
    bottom-left:  dataset/reference real trajectory frame
    top-right:    goal frame
    bottom-right: goal frame

This script crops the left panels and saves them with explicit context vs.
open-loop-prediction names so paper figures do not mix the two groups.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path


def parse_steps(value: str) -> list[int]:
    steps = []
    for item in str(value).split(","):
        item = item.strip()
        if not item:
            continue
        steps.append(int(item))
    if not steps:
        raise argparse.ArgumentTypeError("Expected at least one comma-separated step.")
    return steps


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--video", required=True, type=Path, help="Path to rollout_*.mp4.")
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Default: <video_parent>/<video_stem>_figure_frames",
    )
    parser.add_argument("--context-steps", type=parse_steps, default=parse_steps("0,5,10"))
    parser.add_argument(
        "--prediction-steps",
        type=parse_steps,
        default=parse_steps("15,20,25,30,35"),
    )
    parser.add_argument(
        "--imagined-label",
        default="imagined",
        help="Name used for the model rollout row. Use 'rollout' if you want stricter wording.",
    )
    parser.add_argument(
        "--save-composite",
        action=argparse.BooleanOptionalAction,
        default=False,
        help="Also save a paper-style composite grid.",
    )
    parser.add_argument("--composite-name", default="context_vs_prediction_grid.png")
    parser.add_argument("--dpi", type=int, default=220)
    return parser.parse_args()


def read_frame(reader, index: int) -> np.ndarray:
    import numpy as np

    try:
        frame = reader.get_data(index)
    except IndexError as exc:
        raise IndexError(f"Video does not contain frame index {index}.") from exc
    frame = np.asarray(frame)
    if frame.ndim != 3 or frame.shape[-1] < 3:
        raise ValueError(f"Unexpected video frame shape at index {index}: {frame.shape}")
    return frame[..., :3].astype(np.uint8, copy=False)


def crop_left_panels(frame: np.ndarray) -> dict[str, np.ndarray]:
    height, width = frame.shape[:2]
    if height < 2 or width < 2:
        raise ValueError(f"Frame is too small to crop: {frame.shape}")
    mid_h = height // 2
    mid_w = width // 2
    return {
        "rollout": frame[:mid_h, :mid_w],
        "real": frame[mid_h : 2 * mid_h, :mid_w],
    }


def save_png(path: Path, frame: np.ndarray) -> None:
    from PIL import Image

    path.parent.mkdir(parents=True, exist_ok=True)
    Image.fromarray(frame).save(path)


def extract_frames(args: argparse.Namespace) -> tuple[Path, dict]:
    video_path = args.video.expanduser().resolve()
    if not video_path.is_file():
        raise FileNotFoundError(f"Video not found: {video_path}")

    output_dir = (
        args.output_dir.expanduser().resolve()
        if args.output_dir is not None
        else video_path.parent / f"{video_path.stem}_figure_frames"
    )
    context_dir = output_dir / "context_input"
    prediction_dir = output_dir / "open_loop_prediction"

    manifest = {
        "video": str(video_path),
        "layout": {
            "source": "four-grid eval mp4",
            "real_panel": "bottom-left",
            "imagined_panel": "top-left",
        },
        "context_steps": list(args.context_steps),
        "prediction_steps": list(args.prediction_steps),
        "frames": [],
    }

    import imageio

    reader = imageio.get_reader(video_path)
    try:
        groups = [
            ("context_input", context_dir, args.context_steps),
            ("open_loop_prediction", prediction_dir, args.prediction_steps),
        ]
        for group_name, group_dir, steps in groups:
            for local_index, step in enumerate(steps, start=1):
                frame = read_frame(reader, int(step))
                panels = crop_left_panels(frame)
                entries = [
                    ("real", panels["real"]),
                    (str(args.imagined_label), panels["rollout"]),
                ]
                for row_name, panel in entries:
                    filename = f"{group_name}_{local_index:02d}_{row_name}_t{int(step):03d}.png"
                    out_path = group_dir / row_name / filename
                    save_png(out_path, panel)
                    manifest["frames"].append(
                        {
                            "group": group_name,
                            "index": int(local_index),
                            "row": row_name,
                            "step": int(step),
                            "path": str(out_path),
                        }
                    )
    finally:
        reader.close()

    output_dir.mkdir(parents=True, exist_ok=True)
    with (output_dir / "manifest.json").open("w") as handle:
        json.dump(manifest, handle, indent=2)

    return output_dir, manifest


def _load_manifest_image(frame_entry: dict) -> np.ndarray:
    import numpy as np
    from PIL import Image

    return np.asarray(Image.open(frame_entry["path"]).convert("RGB"))


def save_composite(output_dir: Path, manifest: dict, composite_name: str, dpi: int) -> Path:
    import matplotlib.pyplot as plt

    context_steps = list(manifest["context_steps"])
    prediction_steps = list(manifest["prediction_steps"])
    all_steps = context_steps + prediction_steps
    n_context = len(context_steps)
    n_prediction = len(prediction_steps)
    n_total = len(all_steps)
    gap_units = 0.45

    by_key = {
        (entry["group"], entry["row"], int(entry["index"])): entry
        for entry in manifest["frames"]
    }
    imagined_rows = sorted(
        {
            entry["row"]
            for entry in manifest["frames"]
            if entry["row"] != "real"
        }
    )
    imagined_row = imagined_rows[0] if imagined_rows else "imagined"

    sample = _load_manifest_image(manifest["frames"][0])
    aspect = sample.shape[1] / sample.shape[0]
    tile_h = 1.0
    tile_w = aspect
    fig_w = max(8.0, n_total * 1.35 * aspect + 2.2)
    fig_h = 3.8

    fig = plt.figure(figsize=(fig_w, fig_h))
    left_margin = 0.10
    right_margin = 0.02
    top_margin = 0.20
    bottom_margin = 0.18
    row_gap = 0.055
    available_w = 1.0 - left_margin - right_margin
    available_h = 1.0 - top_margin - bottom_margin
    unit_w = available_w / (n_total + gap_units)
    axis_w = unit_w
    axis_h = (available_h - row_gap) / 2.0

    def x_for_column(column: int) -> float:
        extra_gap = gap_units if column >= n_context else 0.0
        return left_margin + (column + extra_gap) * unit_w

    row_y = {
        "real": bottom_margin + axis_h + row_gap,
        imagined_row: bottom_margin,
    }

    context_entries = [("context_input", i + 1, step) for i, step in enumerate(context_steps)]
    prediction_entries = [
        ("open_loop_prediction", i + 1, step)
        for i, step in enumerate(prediction_steps)
    ]
    column_entries = context_entries + prediction_entries

    for col, (group_name, local_index, step) in enumerate(column_entries):
        for row_name in ("real", imagined_row):
            entry = by_key[(group_name, row_name, local_index)]
            ax = fig.add_axes([x_for_column(col), row_y[row_name], axis_w, axis_h])
            ax.imshow(_load_manifest_image(entry))
            ax.set_xticks([])
            ax.set_yticks([])
            for spine in ax.spines.values():
                spine.set_linewidth(1.2)
                spine.set_color("black")
            if row_name == imagined_row:
                label = f"T = {step}" if col == 0 else f"{step}"
                ax.set_xlabel(label, fontsize=15, labelpad=6)

    context_center = (
        x_for_column(0) + x_for_column(n_context - 1) + axis_w
    ) / 2.0
    prediction_center = (
        x_for_column(n_context) + x_for_column(n_total - 1) + axis_w
    ) / 2.0
    fig.text(context_center, 0.95, "Context Input", ha="center", va="top", fontsize=19)
    fig.text(
        prediction_center,
        0.95,
        "Open Loop Prediction",
        ha="center",
        va="top",
        fontsize=19,
    )
    fig.text(0.045, row_y["real"] + axis_h / 2, "Real", rotation=90, ha="center", va="center", fontsize=17)
    fig.text(
        0.045,
        row_y[imagined_row] + axis_h / 2,
        imagined_row.capitalize(),
        rotation=90,
        ha="center",
        va="center",
        fontsize=17,
    )

    composite_path = output_dir / composite_name
    fig.savefig(composite_path, dpi=dpi, bbox_inches="tight", pad_inches=0.06)
    plt.close(fig)
    return composite_path


def main() -> None:
    args = parse_args()
    output_dir, manifest = extract_frames(args)
    print(f"[extract] wrote frames to {output_dir}", flush=True)
    if args.save_composite:
        composite_path = save_composite(
            output_dir,
            manifest,
            args.composite_name,
            int(args.dpi),
        )
        print(f"[extract] wrote composite figure to {composite_path}", flush=True)


if __name__ == "__main__":
    main()