File size: 4,498 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
fad6045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
 
 
fad6045
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
33c14d6
 
9ffd3e8
 
 
 
33c14d6
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")