Download debug/extract_rollout_figure_frames.py from lzhts1/ProWorld: direct link, hf CLI and curl.
- Browser
- Download file 9.5 kB
-
https://huggingface.co/datasets/lzhts1/ProWorld/resolve/main/debug/extract_rollout_figure_frames.py
- Command line
-
hf download hf://datasets/lzhts1/ProWorld/debug/extract_rollout_figure_frames.py
-
curl -L -o extract_rollout_figure_frames.py https://huggingface.co/datasets/lzhts1/ProWorld/resolve/main/debug/extract_rollout_figure_frames.py
9.5 kB
| #!/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() | |