""" 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()