playful / chess-sim /code /sim /lerobot_export.py
Ali-Uraish's picture
Add files using upload-large-folder tool
fad6045 verified
Raw History Blame Contribute Delete
4.5 kB
"""Write expert episodes as a LeRobot v3.0 dataset.
Per frame: the three policy cameras with the red source square and blue
destination square drawn on, joint state and next joint targets in LeRobot's
SO-101 units (arm joints in degrees as with use_degrees=True, gripper 0-100),
and the fixed instruction. Contact hulls (geom group 3) are hidden in every image.
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
from camera_effects import WebcamLook
from episode import FEATURE_NAMES, EpisodeRunner, Highlighter, Task
def features(cfg: dict) -> dict:
ds = cfg["dataset"]
shape = (ds["image_height"], ds["image_width"], 3)
out = {f"observation.images.{c}": {"dtype": "video", "shape": shape, "names": ["height", "width", "channels"]}
for c in ds["cameras"]}
out["observation.state"] = {"dtype": "float32", "shape": (6,), "names": FEATURE_NAMES}
out["action"] = {"dtype": "float32", "shape": (6,), "names": FEATURE_NAMES}
return out
def video_settings(cfg: dict) -> tuple[int, str]:
"""(crf, pix_fmt) the dataset videos are encoded with; LeRobot's defaults unless set."""
ds = cfg["dataset"]
return int(ds.get("video_crf", 30)), ds.get("video_pix_fmt", "yuv420p")
def use_video_settings(cfg: dict):
"""LeRobot 0.4.4 always encodes episodes at its defaults (CRF 30, 4:2:0), which wash
out the small red and blue squares. Its episode encoder calls encode_video_frames
through the lerobot_dataset module, so rebinding that name sets the quality."""
import functools
import lerobot.datasets.lerobot_dataset as lds
from lerobot.datasets.video_utils import encode_video_frames
crf, pix_fmt = video_settings(cfg)
lds.encode_video_frames = functools.partial(encode_video_frames, crf=crf, pix_fmt=pix_fmt)
def create_dataset(cfg: dict, repo_id: str, root: Path):
from lerobot.datasets.lerobot_dataset import LeRobotDataset
use_video_settings(cfg)
ds = cfg["dataset"]
return LeRobotDataset.create(repo_id=repo_id, fps=ds["fps"], features=features(cfg), root=root,
robot_type="so101_follower", use_videos=True, vcodec=ds["vcodec"],
image_writer_threads=4)
class Recorder:
"""Feeds frames to a LeRobotDataset (or keeps them in memory with dataset=None)."""
def __init__(self, cfg: dict, dataset=None):
self.cfg = cfg
self.dataset = dataset
self.cameras = cfg["dataset"]["cameras"]
self.instruction = cfg["dataset"]["instruction"]
self.frames = []
def begin(self, runner: EpisodeRunner, task: Task, rng):
self.highlight = Highlighter(runner, task, rng)
self.looks = {c: WebcamLook.sample(rng, self.cfg) for c in self.cameras}
runner.episode_info["webcam"] = {c: look.describe() for c, look in self.looks.items()}
self.rng = rng
self.frames = []
def observe(self, runner: EpisodeRunner, name: str):
"""What camera `name` delivers: the render, through the webcam, with the squares."""
return self.highlight.apply(runner, name, self.looks[name].apply(runner.render(name), self.rng))
def frame(self, runner: EpisodeRunner, task: Task, action_q6):
f = {f"observation.images.{c}": self.observe(runner, c) for c in self.cameras}
f["observation.state"] = runner.to_lerobot(runner.d.qpos[runner.qadr])
f["action"] = runner.to_lerobot(action_q6)
f["task"] = self.instruction
if self.dataset is not None:
self.dataset.add_frame(f)
else:
self.frames.append(f)
def discard(self):
"""Drop a buffered episode, including the temporary frames of video features."""
if self.dataset is None:
self.frames = []
return
ds = self.dataset
if ds.image_writer is not None:
ds._wait_image_writer()
idx = ds.episode_buffer["episode_index"]
for key in ds.meta.camera_keys:
d = ds._get_image_file_dir(idx, key)
if d.is_dir():
for p in d.iterdir():
p.unlink()
d.rmdir()
ds.clear_episode_buffer(delete_images=False)
def append_jsonl(path: Path, record: dict):
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a") as f:
f.write(json.dumps(record, default=lambda o: o.tolist() if isinstance(o, np.ndarray) else str(o)) + "\n")