File size: 8,509 Bytes
3819e2d | 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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | """
Build inference-format samples from pairs of (first_frame, last_frame) paths.
Usage:
python build_inference_sample.py --dataset_root /path/to/dataset \
--input frames.json --output inference_data.json
Input JSON format (list of frame pairs):
[
["task_.../cam_.../images/frame_000020.png", "task_.../cam_.../images/frame_000100.png"],
["task_.../cam_.../images/frame_000150.png", "task_.../cam_.../images/frame_000230.png"]
]
Or simply a list of single first-frame paths (last frame auto-computed as first + 80):
[
"task_.../cam_.../images/frame_000020.png"
]
Output matches the training data format:
{id, image_0, image_1, eef_state, action, camera_pose}
"""
import os
import re
import sys
import json
import argparse
import numpy as np
from scipy.spatial.transform import Rotation as R
STEP = 5
ACTION_SEQ_LEN = 16
WINDOW = STEP * ACTION_SEQ_LEN # 80
# βββ helpers (from process_idm_data_haoyu.py) βββ
def get_eef_state_from_pose7d(pose7d):
pose7d = np.asarray(pose7d, dtype=float)
xyz = pose7d[:3]
quat = pose7d[3:]
rpy = R.from_quat(quat).as_euler("xyz", degrees=False)
return np.concatenate([xyz, rpy]).astype(float).tolist()
def normalize_tcp_stream(tcp_stream):
if isinstance(tcp_stream, list):
return tcp_stream
if isinstance(tcp_stream, dict):
keys = sorted(tcp_stream.keys(), key=lambda x: int(x))
out = []
for k in keys:
v = tcp_stream[k]
if isinstance(v, dict):
item = dict(v)
if "timestamp" not in item:
item["timestamp"] = int(k)
out.append(item)
else:
raise ValueError("Unsupported tcp stream dict value format.")
return out
raise ValueError(f"Unsupported tcp stream format: {type(tcp_stream)}")
def normalize_gripper_stream(grip_stream):
if isinstance(grip_stream, dict):
return {int(k): v for k, v in grip_stream.items()}
if isinstance(grip_stream, list):
return {int(item["timestamp"]): item for item in grip_stream}
raise ValueError(f"Unsupported gripper stream format: {type(grip_stream)}")
def get_gripper_value(grip_dict, timestamp):
if timestamp not in grip_dict:
return 0.0
g = grip_dict[timestamp]
if isinstance(g, dict):
for key in ["gripper_info", "gripper_command", "gripper"]:
if key in g:
val = g[key]
if isinstance(val, (list, tuple, np.ndarray)) and len(val) > 0:
return float(val[0])
return float(val)
if isinstance(g, (list, tuple, np.ndarray)):
return float(g[0])
return float(g)
# βββ cache βββ
_tcp_cache = {}
_grip_cache = {}
def load_task_data(task_dir):
if task_dir in _tcp_cache:
return _tcp_cache[task_dir], _grip_cache[task_dir]
transform_dir = os.path.join(task_dir, "transformed")
tcp_path = os.path.join(transform_dir, "tcp.npy")
grip_path = os.path.join(transform_dir, "gripper.npy")
if not os.path.exists(tcp_path) or not os.path.exists(grip_path):
raise FileNotFoundError(f"Missing tcp.npy or gripper.npy in {transform_dir}")
tcp_all = np.load(tcp_path, allow_pickle=True).item()
grip_all = np.load(grip_path, allow_pickle=True).item()
_tcp_cache[task_dir] = tcp_all
_grip_cache[task_dir] = grip_all
return tcp_all, grip_all
# βββ frame path parsing βββ
def parse_frame_path(frame_path):
"""
Parse a frame path like:
task_0090_.../cam_037522062165/images/frame_000020.png
Returns (task_id, cam_id, frame_idx).
"""
# Extract frame index
match = re.search(r"frame_(\d+)\.png$", frame_path)
if not match:
raise ValueError(f"Cannot parse frame index from: {frame_path}")
frame_idx = int(match.group(1))
# Extract cam_id: the part after "cam_"
cam_match = re.search(r"cam_(\w+)/images", frame_path)
if not cam_match:
raise ValueError(f"Cannot parse cam_id from: {frame_path}")
cam_id = cam_match.group(1)
# Extract task_id: everything before /cam_
task_id = frame_path.split(f"/cam_{cam_id}")[0]
return task_id, cam_id, frame_idx
def build_sample(first_frame, last_frame, dataset_root):
"""
Build one sample dict from a pair of frame paths.
"""
task_id, cam_id, start_idx = parse_frame_path(first_frame)
_, _, end_idx = parse_frame_path(last_frame)
# Validate consistency
task_id_2, cam_id_2, _ = parse_frame_path(last_frame)
assert task_id == task_id_2, f"Task mismatch: {task_id} vs {task_id_2}"
assert cam_id == cam_id_2, f"Cam mismatch: {cam_id} vs {cam_id_2}"
# Compute the actual step for this pair
total_span = end_idx - start_idx
actual_step = total_span / ACTION_SEQ_LEN
if actual_step != int(actual_step):
print(f" WARNING: span {total_span} not divisible by {ACTION_SEQ_LEN}, "
f"using step={STEP} (default)")
actual_step = STEP
else:
actual_step = int(actual_step)
# Build ID: task_id/cam_id/start_idx (matching training format)
sample_id = f"{task_id}/{cam_id}/{start_idx:06d}"
# Load robot data
task_dir = os.path.join(dataset_root, task_id)
tcp_all, grip_all = load_task_data(task_dir)
if cam_id not in tcp_all:
raise KeyError(f"cam_id {cam_id} not in tcp_all for {task_id}")
tcp_list = normalize_tcp_stream(tcp_all[cam_id])
grip_dict = normalize_gripper_stream(grip_all[cam_id])
# eef_state at start frame
if start_idx >= len(tcp_list):
raise IndexError(f"start_idx={start_idx} out of range (tcp len={len(tcp_list)})")
pose_start = np.asarray(tcp_list[start_idx]["tcp"], dtype=float)
eef_state = get_eef_state_from_pose7d(pose_start)
# action: 16 absolute EEF states at start + step, start + 2*step, ..., start + 16*step
action_seq = []
for k in range(ACTION_SEQ_LEN):
idx_tp1 = start_idx + (k + 1) * actual_step
if idx_tp1 >= len(tcp_list):
raise IndexError(
f"idx_tp1={idx_tp1} out of range (tcp len={len(tcp_list)}) "
f"for sample {sample_id}"
)
pose_tp1 = np.asarray(tcp_list[idx_tp1]["tcp"], dtype=float)
ts_tp1 = int(tcp_list[idx_tp1]["timestamp"])
grip_value = get_gripper_value(grip_dict, ts_tp1)
eef_at_step = get_eef_state_from_pose7d(pose_tp1)
eef_at_step.append(grip_value)
action_seq.append(eef_at_step)
sample = {
"id": sample_id,
"image_0": first_frame,
"image_1": last_frame,
"camera_pose": [], # not used
"eef_state": eef_state,
"action": action_seq,
}
return sample
def main():
parser = argparse.ArgumentParser(
description="Build inference samples from frame path pairs"
)
parser.add_argument("--dataset_root", required=True,
help="Root directory of the RH20T dataset")
parser.add_argument("--input", required=True,
help="JSON file with frame paths (list of pairs or single paths)")
parser.add_argument("--output", required=True,
help="Output JSON file in training data format")
args = parser.parse_args()
with open(args.input, "r") as f:
inputs = json.load(f)
samples = []
errors = 0
for entry in inputs:
try:
# Support both single path and [first, last] pair
if isinstance(entry, str):
# Single path: auto-compute last frame as first + WINDOW
task_id, cam_id, start_idx = parse_frame_path(entry)
end_idx = start_idx + WINDOW
last_frame = f"{task_id}/cam_{cam_id}/images/frame_{end_idx:06d}.png"
first_frame = entry
elif isinstance(entry, list) and len(entry) == 2:
first_frame, last_frame = entry
else:
raise ValueError(f"Unsupported input format: {entry}")
sample = build_sample(first_frame, last_frame, args.dataset_root)
samples.append(sample)
except Exception as e:
print(f"ERROR: {e}")
errors += 1
print(f"\nBuilt {len(samples)} samples, {errors} errors.")
with open(args.output, "w") as f:
json.dump(samples, f, indent=2)
print(f"Saved to {args.output}")
if __name__ == "__main__":
main() |