File size: 10,780 Bytes
b565b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Eraser(xArm6, 100 에피소드) 9D 데이터 + MirrorAlign SPA 미러 데이터를 SimVLA 입력 형식으로 읽는다.

데이터: /home/ubuntu/workspace/Eraser_9d (eraser_tools/make_eraser_9d.py 로 만든 rot6d 판)
  state10  = [x, y, z (mm), r00, r01, r10, r11, r20, r21, gripper(429~800)]
  action10 = [dx, dy, dz (mm), d_rot6d 6, gripper_cmd(-1/+1)]   (다음 프레임 - 지금)
  카메라 image_1 = top(cam1_d435i), image_2 = wrist(cam2_d455), image_3 = front(cam3_l515), 640x480 15 fps

미러 (MirrorAlign, 대칭면 = 로봇 베이스 xz 평면):
  영상: 수평 flip 후 카메라별 SPA 호모그래피로 보정 (Mirror_homography code/spa/apply.py 의 spa_warp 와 같은 계산,
        640x480 원본 해상도에서 warp 한 뒤 384 로 줄인다)
  포즈: (x, y, z, roll, pitch, yaw) -> (x, -y, z, -roll, pitch, -yaw)  ⇔  R' = M R M, M = diag(1, -1, 1)
        rot6d [r00, r01, r10, r11, r20, r21] 의 부호 = [+, -, -, +, +, -]. 변화량 action 도 같은 부호(선형).
  그리퍼·지시문은 그대로.

- 캐시(build_cache, 호스트에서 한 번): mp4 를 풀어 프레임마다 JPEG(q95) 바이트 + 오프셋, state·action·에피소드 정보 .npy.
  미러 영상은 저장하지 않고 학습 때 바로 만든다 (variant 마다 다른 H 를 같은 캐시에 쓴다).
- 샘플 구성은 SimVLA 원본(libero_hdf5)·mf/data_goal.py 와 같다: 시작 프레임은 에피소드 끝 num_actions 프레임 제외,
  행동 청크 = 다음 num_actions 개(이번 학습 16), 뷰 슬롯 3개(top, wrist, front, 모두 사용), 384 bicubic, 학습 때 ColorJitter(0.2), ImageNet 정규화.
"""

from __future__ import annotations

import json
import pathlib
import sys

import cv2
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from torchvision.transforms import InterpolationMode

IMAGE_MEAN = (0.485, 0.456, 0.406)
IMAGE_STD = (0.229, 0.224, 0.225)
CAMS = ("image_1", "image_2", "image_3")
CAM_TO_SPA = {"image_1": "cam1_d435i", "image_2": "cam2_d455", "image_3": "cam3_l515"}   # top, wrist, front
# state10 / action10 미러 부호: x, y, z, r00, r01, r10, r11, r20, r21, gripper
MIRROR_SIGN = np.array([1, -1, 1, 1, -1, -1, 1, 1, -1, 1], dtype=np.float32)


# ----------------------------------------------------------------- SPA 워프 (Mirror_homography code/spa 와 같은 식)
def norm_matrix(W: int, H: int) -> np.ndarray:
    """픽셀 -> 정규화 좌표(grid_sample, align_corners=False) 변환 행렬 N. (spa/geometry.py 그대로)"""
    return np.array([[2.0 / W, 0.0, 1.0 / W - 1.0], [0.0, 2.0 / H, 1.0 / H - 1.0], [0.0, 0.0, 1.0]], dtype=np.float64)


def H_norm_to_pixel_dst2src(Hn: np.ndarray, W: int, H: int) -> np.ndarray:
    N = norm_matrix(W, H)
    M = np.linalg.inv(N) @ np.asarray(Hn, np.float64) @ N
    return M / M[2, 2]


def spa_warp(img: np.ndarray, H_norm: np.ndarray | None) -> np.ndarray:
    """수평 flip 후 SPA 보정 (spa/apply.py 의 spa_warp 와 같다: bilinear, border replicate)."""
    f = cv2.flip(img, 1)
    if H_norm is None:
        return f
    h, w = img.shape[:2]
    M = H_norm_to_pixel_dst2src(H_norm, w, h)
    return cv2.warpPerspective(f, M, (w, h), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REPLICATE)


def load_variant_H(spa_json: str) -> dict[str, np.ndarray]:
    """{"variant": .., "cameras": {cam1_d435i: {"H_norm": 3x3}, ...}} -> {image_1: H, image_2: H, image_3: H}"""
    d = json.loads(pathlib.Path(spa_json).read_text())
    return {c: np.asarray(d["cameras"][CAM_TO_SPA[c]]["H_norm"], np.float64) for c in CAMS}


# ----------------------------------------------------------------- 캐시
def _subset(src: str) -> str:
    """data/ 아래 과제 폴더 이름 (Eraser_9d 는 Eraser, xarm_stack_9d 는 StackCube). 하나여야 한다."""
    subs = [p.name for p in pathlib.Path(src, "data").iterdir() if p.is_dir()]
    assert len(subs) == 1, subs
    return subs[0]


def _episode(args):
    import av
    import pandas as pd
    src, f = args
    d = pd.read_parquet(f)
    ep = int(pathlib.Path(f).stem.split("_")[-1])
    out = {"n": len(d), "ep": ep, "state": np.stack(d["observation.state"].to_numpy()).astype(np.float32),
           "action": np.stack(d["action"].to_numpy()).astype(np.float32),
           "frame": d["frame_index"].to_numpy().astype(np.int32), "task": d["task_index"].to_numpy().astype(np.int32)}
    for cam in CAMS:
        c = av.open(f"{src}/videos/{_subset(src)}/observation.images.{cam}/episode_{ep:06d}.mp4")
        jpgs = []
        for fr in c.decode(video=0):
            ok, b = cv2.imencode(".jpg", cv2.cvtColor(fr.to_ndarray(format="rgb24"), cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 95])
            assert ok
            jpgs.append(b.ravel())
        c.close()
        assert len(jpgs) == len(d), (f, cam, len(jpgs), len(d))
        out[cam] = jpgs
    return out


def build_cache(src: str, out_dir: str, workers: int = 32):
    from multiprocessing import Pool
    out = pathlib.Path(out_dir)
    out.mkdir(parents=True, exist_ok=False)
    files = sorted(pathlib.Path(src, "data", _subset(src)).glob("episode_*.parquet"))
    with Pool(workers) as p:
        eps = sorted(p.map(_episode, [(src, str(f)) for f in files]), key=lambda e: e["ep"])
    for cam in CAMS:
        blobs = [b for e in eps for b in e[cam]]
        np.save(out / f"{cam}_bytes.npy", np.concatenate(blobs))
        np.save(out / f"{cam}_offsets.npy", np.concatenate([[0], np.cumsum([len(b) for b in blobs])]).astype(np.int64))
    np.save(out / "state.npy", np.concatenate([e["state"] for e in eps]))
    np.save(out / "actions.npy", np.concatenate([e["action"] for e in eps]))
    np.save(out / "episode_index.npy", np.concatenate([np.full(e["n"], e["ep"], np.int32) for e in eps]))
    np.save(out / "frame_index.npy", np.concatenate([e["frame"] for e in eps]))
    np.save(out / "task_index.npy", np.concatenate([e["task"] for e in eps]))
    tasks = {}
    for l in open(f"{src}/meta/tasks.jsonl"):
        r = json.loads(l)
        tasks.setdefault(int(r["task_index"]), r["task"])
    (out / "tasks.json").write_text(json.dumps(tasks, indent=1))
    print(f"cache: {len(eps)} episodes, {sum(e['n'] for e in eps)} frames -> {out}")


def compute_norm_stats(cache_dir: str, out_path: str, mirror_only: bool = False):
    """원본 + 미러(mirror_only 면 미러만) 프레임 전체로 SimVLA 형식({"norm_stats": {"state", "actions"}}) 평균·표준편차·분위수."""
    c = pathlib.Path(cache_dir)
    res = {}
    for key in ("state", "actions"):
        x = np.load(c / f"{key}.npy").astype(np.float64)
        x = x * MIRROR_SIGN.astype(np.float64) if mirror_only else np.concatenate([x, x * MIRROR_SIGN.astype(np.float64)])
        res[key] = {"mean": x.mean(0).tolist(), "std": x.std(0).tolist(),
                    "q01": np.quantile(x, 0.01, axis=0).tolist(), "q99": np.quantile(x, 0.99, axis=0).tolist()}
    meta = {"data": "SPA mirror of Eraser_9d 100 episodes only" if mirror_only else "Eraser_9d 100 episodes + SPA mirror 100 episodes", "state_dim": 10, "action_dim": 10,
            "state_layout": "xyz(mm) + rot6d(r00,r01,r10,r11,r20,r21) + gripper(429~800)",
            "action_layout": "delta xyz(mm) + delta rot6d + gripper_cmd(-1/+1)"}
    pathlib.Path(out_path).write_text(json.dumps({"norm_stats": res, "metadata": meta}, indent=1))
    print("norm stats ->", out_path)


# ----------------------------------------------------------------- 데이터셋
class EraserMirrorDataset(Dataset):
    """원본 샘플 + (H 가 있으면) 같은 프레임의 미러 샘플. 길이 = 원본 시작 프레임 수 × (1 또는 2)."""

    def __init__(self, cache_dir: str, H: dict[str, np.ndarray] | None, num_actions: int = 10, image_size: int = 384,
                 training: bool = True, episodes: list[int] | None = None, frame_stride: int = 1, with_original: bool = True):
        c = pathlib.Path(cache_dir)
        self.bytes = {k: np.load(c / f"{k}_bytes.npy", mmap_mode="r") for k in CAMS}
        self.offsets = {k: np.load(c / f"{k}_offsets.npy") for k in CAMS}
        self.state = np.load(c / "state.npy")
        self.actions = np.load(c / "actions.npy")
        ep = np.load(c / "episode_index.npy")
        fr = np.load(c / "frame_index.npy")
        self.task_index = np.load(c / "task_index.npy")
        self.tasks = {int(k): v for k, v in json.loads((c / "tasks.json").read_text()).items()}
        self.H, self.num_actions = H, num_actions
        ep_len = {e: int((ep == e).sum()) for e in np.unique(ep)}
        valid = np.array([fr[i] < ep_len[ep[i]] - num_actions for i in range(len(ep))])
        if episodes is not None:
            valid &= np.isin(ep, episodes)
        base = np.nonzero(valid)[0][::frame_stride]
        parts = ([np.c_[base, np.zeros_like(base)]] if with_original else []) + \
                ([np.c_[base, np.ones_like(base)]] if H is not None else [])
        self.index = np.concatenate(parts)
        tf = [transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC, antialias=True)]
        if training:
            tf.append(transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.0))
        tf += [transforms.ToTensor(), transforms.Normalize(IMAGE_MEAN, IMAGE_STD)]
        self.tf = transforms.Compose(tf)

    def __len__(self):
        return len(self.index)

    def image(self, cam: str, i: int, mirror: bool) -> np.ndarray:
        o = self.offsets[cam]
        bgr = cv2.imdecode(np.asarray(self.bytes[cam][o[i]:o[i + 1]]), cv2.IMREAD_COLOR)
        if mirror:
            bgr = spa_warp(bgr, self.H[cam])
        return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)

    def __getitem__(self, k):
        i, m = (int(x) for x in self.index[k])
        imgs = [self.tf(Image.fromarray(self.image(cam, i, bool(m)))) for cam in CAMS]
        s = self.state[i].copy()
        a = self.actions[i: i + self.num_actions].copy()
        if m:
            s, a = s * MIRROR_SIGN, a * MIRROR_SIGN
        return {
            "image_input": torch.stack(imgs),
            "image_mask": torch.ones(len(CAMS), dtype=torch.bool),
            "proprio": torch.from_numpy(s),
            "action": torch.from_numpy(a),
            "language_instruction": self.tasks[int(self.task_index[i])],
        }


def collate(items):
    out = {k: torch.stack([it[k] for it in items]) for k in ("image_input", "image_mask", "proprio", "action")}
    out["language_instruction"] = [it["language_instruction"] for it in items]
    return out


if __name__ == "__main__":
    # python data_eraser.py <Eraser_9d> <cache_dir> <norm_stats_out>
    src, cache, ns = sys.argv[1:4]
    build_cache(src, cache)
    compute_norm_stats(cache, ns)