Download scripts/visualize.py from catachiii/OneHundredStyle-G1: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/datasets/catachiii/OneHundredStyle-G1/resolve/main/scripts/visualize.py
- Command line
-
hf download hf://datasets/catachiii/OneHundredStyle-G1/scripts/visualize.py
-
curl -L -o visualize.py https://huggingface.co/datasets/catachiii/OneHundredStyle-G1/resolve/main/scripts/visualize.py
9.44 kB
| """Play OneHundredStyle-G1 clips on the Unitree G1 with MuJoCo. | |
| python scripts/visualize.py # browse all 810 clips | |
| python scripts/visualize.py --style Zombie # all takes of one style | |
| python scripts/visualize.py --take FW # forward walks of every style | |
| python scripts/visualize.py --clip Zombie_FW Chicken_FR # chosen clips | |
| python scripts/visualize.py --clip Zombie_FW --mirror # its left-right mirror image | |
| python scripts/visualize.py --clip Zombie_FW --seconds 6 --record zombie.mp4 # offscreen video | |
| Keys: SPACE pause | RIGHT/N next clip | LEFT/B previous clip | R restart | |
| UP/DOWN playback speed | close the window to quit | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import time | |
| from pathlib import Path | |
| import mujoco | |
| import numpy as np | |
| from style100 import FPS, JOINT_NAMES, ROOT, TAKES, load_clip, load_metadata | |
| KEY_SPACE, KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP = 32, 262, 263, 264, 265 # GLFW key codes | |
| END_PAUSE_S = 0.5 # hold on the last frame before a clip loops | |
| class Player: | |
| """Holds the playlist and writes one frame of the current clip into ``data``.""" | |
| def __init__(self, model, data, clips, root: Path, mirrored: bool = False): | |
| self.model, self.data, self.clips, self.root, self.mirrored = model, data, clips, root, mirrored | |
| self.qadr = [model.joint(name).qposadr[0] for name in JOINT_NAMES] | |
| self.index = self.frame = 0 | |
| self.paused, self.speed = False, 1.0 | |
| self.keys: list[int] = [] | |
| self._hold_until = 0.0 | |
| self.load(0) | |
| def load(self, index: int): | |
| self.index = index % len(self.clips) | |
| self.row = self.clips[self.index] | |
| clip = load_clip(self.root / self.row["file"], mirrored=self.mirrored) | |
| self.qpos = np.zeros((len(clip), self.model.nq)) | |
| self.qpos[:, 0:3], self.qpos[:, 3:7], self.qpos[:, self.qadr] = clip.root_pos, clip.root_quat, clip.joint_pos | |
| w, x, y, z = clip.root_quat[0] | |
| self.yaw_deg = float(np.degrees(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))) | |
| self.frame, self._hold_until = 0, 0.0 | |
| self.apply() | |
| print(f"[{self.index + 1}/{len(self.clips)}] {self.row['id']}{' (mirrored)' if self.mirrored else ''} " | |
| f"{self.row['motion']} {self.row['n_frames']} frames ({self.row['duration_s']} s) " | |
| f"{self.row['description']}") | |
| def apply(self): | |
| self.data.qpos[:] = self.qpos[self.frame] | |
| mujoco.mj_forward(self.model, self.data) | |
| def step(self): | |
| """Advance one frame; loop the clip after a short hold on its last frame.""" | |
| now = time.monotonic() | |
| if self.paused or now < self._hold_until: | |
| return | |
| self.frame += 1 | |
| if self.frame >= len(self.qpos): | |
| self.frame, self._hold_until = 0, now + END_PAUSE_S | |
| def label(self) -> tuple[str, str]: | |
| r = self.row | |
| return (f"{r['id']}{' (mirrored)' if self.mirrored else ''} {r['motion']}\nframe {self.frame} / {r['n_frames'] - 1}", | |
| f"{self.index + 1} of {len(self.clips)}\nx{self.speed:.2f}") | |
| def handle_keys(self) -> bool: | |
| """Apply queued key presses; returns True when the clip changed.""" | |
| before = self.index | |
| while self.keys: | |
| key = self.keys.pop(0) | |
| if key == KEY_SPACE: | |
| self.paused = not self.paused | |
| elif key in (KEY_RIGHT, ord("N")): | |
| self.load(self.index + 1) | |
| elif key in (KEY_LEFT, ord("B")): | |
| self.load(self.index - 1) | |
| elif key == ord("R"): | |
| self.frame = 0 | |
| elif key == KEY_UP: | |
| self.speed = min(self.speed * 1.5, 8.0) | |
| elif key == KEY_DOWN: | |
| self.speed = max(self.speed / 1.5, 0.125) | |
| return self.index != before | |
| def aim(cam, model, player: Player, args): | |
| """Track the pelvis from a fixed angle relative to the robot's heading in the first frame.""" | |
| cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING | |
| cam.trackbodyid = model.body("pelvis").id | |
| cam.distance, cam.elevation = args.distance, args.elevation | |
| cam.azimuth = player.yaw_deg + args.azimuth | |
| def play(model, data, player: Player, args): | |
| import mujoco.viewer | |
| player.speed = args.speed | |
| with mujoco.viewer.launch_passive(model, data, key_callback=player.keys.append, | |
| show_left_ui=False, show_right_ui=False) as viewer: | |
| aim(viewer.cam, model, player, args) | |
| while viewer.is_running(): | |
| tic = time.perf_counter() | |
| with viewer.lock(): | |
| if player.handle_keys(): | |
| aim(viewer.cam, model, player, args) | |
| player.step() | |
| player.apply() | |
| if hasattr(viewer, "set_texts"): # mujoco >= 3.2 | |
| viewer.set_texts((None, None, *player.label())) | |
| viewer.sync() | |
| time.sleep(max(0.0, 1.0 / (FPS * player.speed) - (time.perf_counter() - tic))) | |
| def record(model, data, player: Player, args): | |
| """Render the playlist offscreen; ``--speed`` only changes the output frame rate.""" | |
| import imageio | |
| model.vis.global_.offwidth = max(model.vis.global_.offwidth, args.width) | |
| model.vis.global_.offheight = max(model.vis.global_.offheight, args.height) | |
| fps = FPS * args.speed / args.every | |
| is_gif = args.record.suffix.lower() == ".gif" | |
| options = {"duration": 1000.0 / fps, "loop": 0} if is_gif else {"fps": fps, "quality": 8} | |
| cam = mujoco.MjvCamera() | |
| with mujoco.Renderer(model, args.height, args.width) as renderer, \ | |
| imageio.get_writer(args.record, **options) as writer: | |
| for index in range(len(player.clips)): | |
| player.load(index) | |
| aim(cam, model, player, args) | |
| first = min(int(round(args.start * FPS)), len(player.qpos) - 1) | |
| last = len(player.qpos) if args.seconds is None else min(len(player.qpos), first + int(round(args.seconds * FPS))) | |
| for frame in range(first, last, args.every): | |
| player.frame = frame | |
| player.apply() | |
| renderer.update_scene(data, cam) | |
| writer.append_data(renderer.render()) | |
| print(f"wrote {args.record} ({len(player.clips)} clips, {fps:g} fps)") | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--root", type=Path, default=ROOT, help="dataset folder (default: the one this script is in)") | |
| ap.add_argument("--scene", type=Path, default=None, help="MuJoCo XML (default: robot/scene.xml)") | |
| ap.add_argument("--clip", nargs="+", metavar="ID", help="play only these clips, e.g. Zombie_FW") | |
| ap.add_argument("--style", nargs="+", metavar="STYLE", help="play only these styles, e.g. Zombie Chicken") | |
| ap.add_argument("--take", nargs="+", choices=list(TAKES), help="play only these takes, e.g. FW FR") | |
| ap.add_argument("--mirror", action="store_true", help="play the left-right mirror image of every clip") | |
| ap.add_argument("--speed", type=float, default=1.0, help="playback speed factor (default 1.0)") | |
| ap.add_argument("--azimuth", type=float, default=135.0, help="camera yaw relative to the initial heading [deg]") | |
| ap.add_argument("--elevation", type=float, default=-15.0, help="camera elevation [deg]") | |
| ap.add_argument("--distance", type=float, default=3.2, help="camera distance to the pelvis [m]") | |
| ap.add_argument("--record", type=Path, metavar="FILE", help="render to FILE (.mp4 or .gif) instead of opening a window") | |
| ap.add_argument("--start", type=float, default=0.0, help="when recording, start this many seconds into each clip") | |
| ap.add_argument("--seconds", type=float, default=None, help="when recording, length to render per clip (default: all)") | |
| ap.add_argument("--every", type=int, default=1, help="when recording, keep every N-th frame (default 1)") | |
| ap.add_argument("--width", type=int, default=1280, help="recording width [px]") | |
| ap.add_argument("--height", type=int, default=720, help="recording height [px]") | |
| args = ap.parse_args() | |
| clips = load_metadata(args.root) | |
| if args.style: | |
| known = {c["style"] for c in clips} | |
| missing = [s for s in args.style if s not in known] | |
| if missing: | |
| raise SystemExit(f"no such style: {', '.join(missing)}") | |
| clips = [c for c in clips if c["style"] in args.style] | |
| if args.take: | |
| clips = [c for c in clips if c["take"] in args.take] | |
| if args.clip: | |
| by_id = {c["id"]: c for c in clips} | |
| missing = [i for i in args.clip if i not in by_id] | |
| if missing: | |
| raise SystemExit(f"no such clip in the selection: {', '.join(missing)}") | |
| clips = [by_id[i] for i in args.clip] | |
| if not clips: | |
| raise SystemExit("the selection is empty") | |
| if args.record and not (args.clip or args.style): | |
| raise SystemExit("--record needs the clips to render, e.g. --clip Zombie_FW") | |
| scene = args.scene or args.root / "robot" / "scene.xml" | |
| model = mujoco.MjModel.from_xml_path(str(scene)) | |
| data = mujoco.MjData(model) | |
| player = Player(model, data, clips, args.root, mirrored=args.mirror) | |
| (record if args.record else play)(model, data, player, args) | |
| if __name__ == "__main__": | |
| main() | |