File size: 5,509 Bytes
d94c87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Filter a LeRobot v3.0 dataset down to upper-body joints + 3 cameras.

Usage: filter_upper.py [SRC] [DST]

SRC must already be v3.0. A v2.1 dataset (e.g. Isaac-GR00T_1.7/dataset_13) has to be
converted first:
    python -m lerobot.datasets.v30.convert_dataset_v21_to_v30 \
        --repo-id=<abs path to a copy> --push-to-hub=false
"""
import json
import os
import shutil
import sys
from pathlib import Path

import numpy as np
import pandas as pd

SRC = Path(sys.argv[1] if len(sys.argv) > 1 else "/mnt/drive2/vla_traning_ws/pi0/dataset_13")
DST = Path(sys.argv[2] if len(sys.argv) > 2 else "/mnt/drive2/vla_traning_ws/pi0/smoth_data_1200_upper")

UPPER_JOINTS = [
    "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint",
    "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint",
    "left_hand_index_0_joint", "left_hand_index_1_joint",
    "left_hand_middle_0_joint", "left_hand_middle_1_joint",
    "left_hand_thumb_0_joint", "left_hand_thumb_1_joint", "left_hand_thumb_2_joint",
    "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint",
    "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint",
    "right_hand_index_0_joint", "right_hand_index_1_joint",
    "right_hand_middle_0_joint", "right_hand_middle_1_joint",
    "right_hand_thumb_0_joint", "right_hand_thumb_1_joint", "right_hand_thumb_2_joint",
]

SLICE_KEYS = ["observation.state", "action"]
DROP_KEYS = [
    "observation.eef_state",
    "action.eef",
    "observation.img_state_delta",
    "teleop.navigate_command",
    "teleop.base_height_command",
]

# ---------------------------------------------------------------- resolve indices
info = json.load(open(SRC / "meta" / "info.json"))
sel = {}
for key in SLICE_KEYS:
    names = info["features"][key]["names"]
    missing = [j for j in UPPER_JOINTS if j not in names]
    if missing:
        raise SystemExit(f"{key}: joints not present in dataset: {missing}")
    sel[key] = [names.index(j) for j in UPPER_JOINTS]
    print(f"{key}: {len(names)} -> {len(sel[key])} dims, indices {sel[key][0]}..{sel[key][-1]}")

if DST.exists():
    shutil.rmtree(DST)
(DST / "meta").mkdir(parents=True)

# ---------------------------------------------------------------- data parquet
for src_file in sorted((SRC / "data").rglob("file-*.parquet")):
    rel = src_file.relative_to(SRC)
    out = DST / rel
    out.parent.mkdir(parents=True, exist_ok=True)
    df = pd.read_parquet(src_file)
    n_before = len(df.columns)
    for key, take in sel.items():
        take_np = np.asarray(take)
        df[key] = [np.asarray(v, dtype=np.float64)[take_np] for v in df[key]]
    df = df.drop(columns=[c for c in DROP_KEYS if c in df.columns])
    df.to_parquet(out, index=False)
    print(f"data: {rel}  rows={len(df)}  cols {n_before} -> {len(df.columns)}")

# ---------------------------------------------------------------- videos (hardlink)
if (SRC / "videos").is_dir():
    shutil.copytree(SRC / "videos", DST / "videos", copy_function=os.link)
    print("videos: hardlinked (no extra disk used)")

# ---------------------------------------------------------------- meta/info.json
for key, take in sel.items():
    info["features"][key]["shape"] = [len(take)]
    info["features"][key]["names"] = list(UPPER_JOINTS)
for key in DROP_KEYS:
    info["features"].pop(key, None)
json.dump(info, open(DST / "meta" / "info.json", "w"), indent=4)
print("meta/info.json: features ->", list(info["features"]))

# ---------------------------------------------------------------- meta/stats.json
stats = json.load(open(SRC / "meta" / "stats.json"))
for key, take in sel.items():
    n_orig = len(json.load(open(SRC / "meta" / "info.json"))["features"][key]["names"])
    for stat_name, vals in list(stats[key].items()):
        arr = np.asarray(vals, dtype=np.float64)
        # Per-dimension stats (min/max/mean/std) are length-n_orig; `count` is scalar-ish.
        if arr.shape == (n_orig,):
            stats[key][stat_name] = arr[np.asarray(take)].tolist()
            print(f"  stats {key}/{stat_name}: {n_orig} -> {len(take)}")
        else:
            print(f"  stats {key}/{stat_name}: left as-is (shape {arr.shape})")
for key in DROP_KEYS:
    stats.pop(key, None)
json.dump(stats, open(DST / "meta" / "stats.json", "w"), indent=4)
print("meta/stats.json: keys ->", sorted(stats))

# ---------------------------------------------------------------- meta/episodes parquet
for src_file in sorted((SRC / "meta" / "episodes").rglob("file-*.parquet")):
    rel = src_file.relative_to(SRC)
    out = DST / rel
    out.parent.mkdir(parents=True, exist_ok=True)
    df = pd.read_parquet(src_file)
    for key, take in sel.items():
        take_np = np.asarray(take)
        for stat_name in ("min", "max", "mean", "std"):
            col = f"stats/{key}/{stat_name}"
            if col in df.columns:
                df[col] = [np.asarray(v, dtype=np.float64)[take_np] for v in df[col]]
    drop_cols = [c for c in df.columns if any(c.startswith(f"stats/{k}/") for k in DROP_KEYS)]
    df = df.drop(columns=drop_cols)
    df.to_parquet(out, index=False)
    print(f"episodes meta: {rel}  rows={len(df)}  dropped {len(drop_cols)} stat cols")

# ---------------------------------------------------------------- meta/tasks.parquet
shutil.copy2(SRC / "meta" / "tasks.parquet", DST / "meta" / "tasks.parquet")
print("meta/tasks.parquet: copied")
print("DONE ->", DST)