File size: 4,475 Bytes
c1a4584
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Play the physical G1 + table + object env and write an MP4.

This does **not** load DexYCB, HaWoR, or ``isaaclab_replay.npz``. The scene is
procedural Isaac Lab: Nucleus G1 (minimal USD), a cuboid table, a cuboid object.
Actions are zeros (or ``--random``) unless you pass a later checkpoint.

  ./play.sh --headless --steps 300
  # MP4: simulation/runs/rl/play/g1_table_object.mp4
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from isaaclab.app import AppLauncher

parser = argparse.ArgumentParser(description="Play V2D-G1-TableObject and record MP4.")
parser.add_argument("--task", type=str, default="V2D-G1-TableObject-Play-v0")
parser.add_argument("--num_envs", type=int, default=1)
parser.add_argument("--steps", type=int, default=300)
parser.add_argument("--random", action="store_true")
parser.add_argument(
    "--output",
    type=Path,
    default=None,
    help="MP4 path (default: $RUNS_DIR/rl/play/g1_table_object.mp4)",
)
parser.add_argument("--fps", type=float, default=30.0)
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
args_cli.enable_cameras = True

app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app

import gymnasium as gym  # noqa: E402
import numpy as np  # noqa: E402
import torch  # noqa: E402
from isaaclab_tasks.utils import parse_env_cfg  # noqa: E402

import v2d_sim  # noqa: E402, F401


def _as_uint8_rgb(img) -> np.ndarray | None:
    if img is None:
        return None
    if hasattr(img, "cpu"):
        img = img.detach().cpu().numpy()
    img = np.asarray(img)
    if img.ndim == 4:
        img = img[0]
    img = img[..., :3]
    if img.dtype != np.uint8:
        scale = 255.0 if float(np.nanmax(img)) <= 1.5 else 1.0
        img = np.clip(img * scale, 0, 255).astype(np.uint8)
    h, w = img.shape[:2]
    return img[: h - (h % 2), : w - (w % 2)]


def _write_mp4(path: Path, frames: list[np.ndarray], fps: float) -> None:
    if not frames:
        raise RuntimeError("no frames captured")
    path.parent.mkdir(parents=True, exist_ok=True)
    try:
        import imageio.v2 as imageio

        imageio.mimsave(str(path), frames, fps=float(fps), codec="libx264", pixelformat="yuv420p")
        return
    except Exception as exc:
        print(f"[v2d-rl] imageio h264 failed ({exc}); trying OpenCV", flush=True)
    import cv2

    h, w = frames[0].shape[:2]
    writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h))
    if not writer.isOpened():
        raise RuntimeError(f"could not open VideoWriter for {path}")
    for fr in frames:
        writer.write(cv2.cvtColor(fr, cv2.COLOR_RGB2BGR))
    writer.release()


def main() -> None:
    runs = Path(os.environ.get("RUNS_DIR", Path.cwd() / "runs"))
    out_mp4 = (args_cli.output or (runs / "rl" / "play" / "g1_table_object.mp4")).resolve()
    env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs)
    env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array")
    env.reset()
    print("[v2d-rl] play uses procedural Isaac assets (not DexYCB / isaaclab_replay.npz)", flush=True)
    print("  robot: Unitree G1 (G1_MINIMAL_CFG), gravity on, floating base", flush=True)
    print("  table: kinematic cuboid   object: dynamic cuboid", flush=True)
    print(f"  actions: {'random' if args_cli.random else 'zeros'}  steps={args_cli.steps}", flush=True)
    print(f"  mp4 {out_mp4}", flush=True)

    frames: list[np.ndarray] = []
    for i in range(args_cli.steps):
        if not simulation_app.is_running():
            break
        if args_cli.random:
            action = torch.as_tensor(env.action_space.sample(), device=env.unwrapped.device)
        else:
            action = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device)
        _obs, rew, _term, _trunc, _info = env.step(action)
        rgb = _as_uint8_rgb(env.unwrapped.render())
        if rgb is not None:
            frames.append(rgb)
        if i % 50 == 0:
            r = rew.mean().item() if hasattr(rew, "mean") else float(rew)
            print(f"  step {i}  reward_mean={r:.3f}  frames={len(frames)}", flush=True)

    _write_mp4(out_mp4, frames, args_cli.fps)
    print(f"[v2d-rl] wrote {out_mp4} ({len(frames)} frames)", flush=True)
    env.close()


if __name__ == "__main__":
    try:
        main()
    finally:
        simulation_app.close()
        sys.exit(0)