Joocjun commited on
Commit
a213560
·
verified ·
1 Parent(s): 2bf3fac

Upload convert_hand_actions.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_hand_actions.py +147 -0
convert_hand_actions.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert binary hand actions to next-state continuous actions.
3
+
4
+ For each timestep t, replaces:
5
+ action[t][7:13] (left_hand) <- observation.state[t+1][7:13]
6
+ action[t][29:35] (right_hand) <- observation.state[t+1][29:35]
7
+
8
+ For the last timestep of each episode, repeats the current state.
9
+
10
+ Creates new datasets with suffix '_nextstate' and symlinks videos to save space.
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import shutil
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ from tqdm import tqdm
22
+
23
+
24
+ LEFT_HAND_SLICE = slice(7, 13)
25
+ RIGHT_HAND_SLICE = slice(29, 35)
26
+
27
+
28
+ def convert_episode_parquet(src_path: str, dst_path: str) -> int:
29
+ """Convert a single episode parquet file. Returns number of frames."""
30
+ df = pd.read_parquet(src_path)
31
+
32
+ actions = np.array(df["action"].tolist())
33
+ states = np.array(df["observation.state"].tolist())
34
+
35
+ n = len(df)
36
+
37
+ # Replace hand actions with next state (shift by 1)
38
+ # For t=0..n-2: action[t] = state[t+1]
39
+ actions[: n - 1, LEFT_HAND_SLICE] = states[1:n, LEFT_HAND_SLICE]
40
+ actions[: n - 1, RIGHT_HAND_SLICE] = states[1:n, RIGHT_HAND_SLICE]
41
+
42
+ # For last timestep: repeat current state
43
+ actions[n - 1, LEFT_HAND_SLICE] = states[n - 1, LEFT_HAND_SLICE]
44
+ actions[n - 1, RIGHT_HAND_SLICE] = states[n - 1, RIGHT_HAND_SLICE]
45
+
46
+ # Write back
47
+ df["action"] = actions.tolist()
48
+ os.makedirs(os.path.dirname(dst_path), exist_ok=True)
49
+ df.to_parquet(dst_path, index=False)
50
+ return n
51
+
52
+
53
+ def convert_dataset(src_dir: str, dst_dir: str):
54
+ src = Path(src_dir)
55
+ dst = Path(dst_dir)
56
+
57
+ if dst.exists():
58
+ print(f"Destination {dst} already exists, skipping. Delete it first to reconvert.")
59
+ return
60
+
61
+ dst.mkdir(parents=True)
62
+
63
+ # 1. Symlink videos directory (saves huge disk space)
64
+ src_videos = src / "videos"
65
+ dst_videos = dst / "videos"
66
+ if src_videos.exists():
67
+ os.symlink(src_videos.resolve(), dst_videos)
68
+ print(f" Symlinked videos: {dst_videos} -> {src_videos.resolve()}")
69
+
70
+ # 2. Copy meta directory (small)
71
+ src_meta = src / "meta"
72
+ dst_meta = dst / "meta"
73
+ shutil.copytree(src_meta, dst_meta)
74
+ print(f" Copied meta/")
75
+
76
+ # 3. Remove stats.json so training auto-regenerates it
77
+ stats_path = dst_meta / "stats.json"
78
+ if stats_path.exists():
79
+ stats_path.unlink()
80
+ print(f" Removed stats.json (will be auto-regenerated)")
81
+
82
+ relative_stats = dst_meta / "relative_stats.json"
83
+ if relative_stats.exists():
84
+ relative_stats.unlink()
85
+ print(f" Removed relative_stats.json")
86
+
87
+ # 4. Convert parquet files
88
+ src_data = src / "data"
89
+ dst_data = dst / "data"
90
+ parquet_files = sorted(src_data.rglob("*.parquet"))
91
+ print(f" Converting {len(parquet_files)} parquet files...")
92
+
93
+ total_frames = 0
94
+ for pf in tqdm(parquet_files, desc=f" {src.name}"):
95
+ rel = pf.relative_to(src_data)
96
+ dst_pf = dst_data / rel
97
+ n = convert_episode_parquet(str(pf), str(dst_pf))
98
+ total_frames += n
99
+
100
+ print(f" Done: {len(parquet_files)} episodes, {total_frames} frames converted")
101
+
102
+ # 5. Copy README with note about modification
103
+ readme_src = src / "README.md"
104
+ if readme_src.exists():
105
+ readme_text = readme_src.read_text()
106
+ note = (
107
+ "\n\n## Modification: Next-State Hand Actions\n\n"
108
+ "Hand action channels (left_hand indices 7-12, right_hand indices 29-34) "
109
+ "have been replaced with next-state values:\n"
110
+ "- `action[t][7:13] = observation.state[t+1][7:13]`\n"
111
+ "- `action[t][29:35] = observation.state[t+1][29:35]`\n"
112
+ "- Last timestep repeats current state.\n"
113
+ "- `stats.json` removed so training auto-regenerates normalization stats.\n"
114
+ )
115
+ (dst / "README.md").write_text(readme_text + note)
116
+
117
+
118
+ def main():
119
+ parser = argparse.ArgumentParser(description="Convert binary hand actions to next-state")
120
+ parser.add_argument(
121
+ "--src-dirs",
122
+ nargs="+",
123
+ default=[
124
+ "datasets/gr1_100x24",
125
+ "datasets/gr1_300x24",
126
+ "datasets/gr1_1000x24",
127
+ ],
128
+ help="Source dataset directories",
129
+ )
130
+ parser.add_argument(
131
+ "--suffix",
132
+ default="_nextstate",
133
+ help="Suffix for output directories (default: _nextstate)",
134
+ )
135
+ args = parser.parse_args()
136
+
137
+ for src_dir in args.src_dirs:
138
+ src = Path(src_dir)
139
+ dst = src.parent / (src.name + args.suffix)
140
+ print(f"\nConverting {src} -> {dst}")
141
+ convert_dataset(str(src), str(dst))
142
+
143
+ print("\nAll done!")
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()