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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prepare EVAC inference inputs from RLBench-style episode data.
|
| 3 |
+
|
| 4 |
+
Input layout:
|
| 5 |
+
episodes_root/
|
| 6 |
+
├── episode_0/
|
| 7 |
+
│ ├── actions.npy # (T_act, 8), single-hand [xyz, quat_xyzw, gripper]
|
| 8 |
+
│ ├── view1/
|
| 9 |
+
│ │ ├── rgb/video.mp4
|
| 10 |
+
│ │ └── camera_params.json # {"<frame_id>": {"extrinsics":..., "intrinsics":...}}
|
| 11 |
+
│ └── view2/ ...
|
| 12 |
+
├── episode_1/
|
| 13 |
+
│ └── ...
|
| 14 |
+
|
| 15 |
+
Output layout:
|
| 16 |
+
<user-specified output_root>/
|
| 17 |
+
├── episode_0/
|
| 18 |
+
│ ├── <view1>/ # only FIXED-camera views
|
| 19 |
+
│ │ ├── frame.png # video frame at t_start (first frame gripper visible)
|
| 20 |
+
│ │ ├── actions.npy # (T + 3, 16), dual-hand, history-padded
|
| 21 |
+
│ │ ├── extrinsics.npy # (4, 4) c2w
|
| 22 |
+
│ │ └── intrinsics.npy # (3, 3) K (abs-valued fx, fy)
|
| 23 |
+
│ └── <view2>/ ...
|
| 24 |
+
└── ...
|
| 25 |
+
|
| 26 |
+
Pipeline:
|
| 27 |
+
1. Discover view folders (contain camera_params.json).
|
| 28 |
+
2. Filter: keep views whose extrinsics are identical across all recorded frames.
|
| 29 |
+
3. Map each video frame t -> action[round(t * T_action / T_video)] (handles
|
| 30 |
+
non-exact ratios like 41:163 or 41:164 by clamping at the tail).
|
| 31 |
+
4. Find t_start: first video frame where right-hand EEF projects inside
|
| 32 |
+
the image with positive depth (gripper enters camera view).
|
| 33 |
+
5. Slice: frames [t_start, T_video), actions aligned to those frames.
|
| 34 |
+
6. Convert 8D single-hand -> 16D dual-hand (real on right, placeholder on left).
|
| 35 |
+
7. Prepend (n_previous - 1) copies of first frame to align with EVAC's history slots.
|
| 36 |
+
8. Write frame.png from video at t_start; write actions.npy; write K and c2w.
|
| 37 |
+
|
| 38 |
+
Usage:
|
| 39 |
+
python prepare_evac_input.py -i /path/to/episodes_root -o /path/to/out
|
| 40 |
+
python prepare_evac_input.py -i ... -o ... --hand right
|
| 41 |
+
python prepare_evac_input.py -i ... -o ... --fix_tol 1e-6 --n_previous 4
|
| 42 |
+
python prepare_evac_input.py -i ... -o ... --episodes episode_0 episode_5
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
import argparse
|
| 46 |
+
import json
|
| 47 |
+
import os
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
|
| 50 |
+
import cv2
|
| 51 |
+
import numpy as np
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ---------------------------------------------------------------------------
|
| 55 |
+
# Action conversion
|
| 56 |
+
# ---------------------------------------------------------------------------
|
| 57 |
+
|
| 58 |
+
def single_to_dual(actions_8d: np.ndarray, hand: str = "right") -> np.ndarray:
|
| 59 |
+
"""[T, 8] -> [T, 16]. Real data on `hand`, placeholder on the other."""
|
| 60 |
+
assert actions_8d.ndim == 2 and actions_8d.shape[1] == 8
|
| 61 |
+
T = actions_8d.shape[0]
|
| 62 |
+
out = np.zeros((T, 16), dtype=np.float32)
|
| 63 |
+
|
| 64 |
+
if hand == "right":
|
| 65 |
+
out[:, 3:7] = np.array([0, 0, 0, 1], dtype=np.float32) # identity quat
|
| 66 |
+
out[:, 7] = 1.0 # gripper open
|
| 67 |
+
out[:, 8:11] = actions_8d[:, 0:3]
|
| 68 |
+
out[:, 11:15] = actions_8d[:, 3:7]
|
| 69 |
+
out[:, 15] = actions_8d[:, 7]
|
| 70 |
+
elif hand == "left":
|
| 71 |
+
out[:, 0:3] = actions_8d[:, 0:3]
|
| 72 |
+
out[:, 3:7] = actions_8d[:, 3:7]
|
| 73 |
+
out[:, 7] = actions_8d[:, 7]
|
| 74 |
+
out[:, 11:15] = np.array([0, 0, 0, 1], dtype=np.float32)
|
| 75 |
+
out[:, 15] = 1.0
|
| 76 |
+
else:
|
| 77 |
+
raise ValueError(f"hand must be 'left' or 'right', got {hand!r}")
|
| 78 |
+
return out
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def prepend_history_pad(actions_16d: np.ndarray, n_previous: int) -> np.ndarray:
|
| 82 |
+
"""Prepend (n_previous - 1) copies of the first frame."""
|
| 83 |
+
if n_previous <= 1:
|
| 84 |
+
return actions_16d
|
| 85 |
+
return np.concatenate([actions_16d[:1]] * (n_previous - 1) + [actions_16d], axis=0)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
# Camera handling
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
|
| 92 |
+
def load_camera_params(camera_params_path: Path):
|
| 93 |
+
"""Parse camera_params.json -> sorted frame_ids, (T, 4, 4) ext, (T, 3, 3) K."""
|
| 94 |
+
with open(camera_params_path, "r") as f:
|
| 95 |
+
data = json.load(f)
|
| 96 |
+
frame_ids = sorted(data.keys())
|
| 97 |
+
ext = np.stack([np.array(data[k]["extrinsics"], dtype=np.float64) for k in frame_ids])
|
| 98 |
+
K = np.stack([np.array(data[k]["intrinsics"], dtype=np.float64) for k in frame_ids])
|
| 99 |
+
return frame_ids, ext, K
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def is_fixed_camera(ext: np.ndarray, tol: float = 1e-6) -> bool:
|
| 103 |
+
"""True if extrinsics are identical across all frames (within tol)."""
|
| 104 |
+
if ext.shape[0] < 2:
|
| 105 |
+
return True
|
| 106 |
+
return np.abs(ext - ext[0:1]).max() < tol
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def normalize_intrinsic(K_3x3: np.ndarray) -> np.ndarray:
|
| 110 |
+
"""Fix RLBench/OpenGL-style negative fx/fy by taking absolute values."""
|
| 111 |
+
K_out = K_3x3.astype(np.float32).copy()
|
| 112 |
+
K_out[0, 0] = abs(K_out[0, 0])
|
| 113 |
+
K_out[1, 1] = abs(K_out[1, 1])
|
| 114 |
+
return K_out
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ---------------------------------------------------------------------------
|
| 118 |
+
# Gripper-in-view detection via projection
|
| 119 |
+
# ---------------------------------------------------------------------------
|
| 120 |
+
|
| 121 |
+
def project_points_world_to_pixel(points_world: np.ndarray,
|
| 122 |
+
c2w: np.ndarray,
|
| 123 |
+
K: np.ndarray):
|
| 124 |
+
"""
|
| 125 |
+
points_world: (N, 3) world-frame 3D points
|
| 126 |
+
c2w: (4, 4) camera-to-world; we invert to get world-to-camera
|
| 127 |
+
K: (3, 3) intrinsic
|
| 128 |
+
Returns: (N, 2) pixel coords (u, v), (N,) camera-frame z depth
|
| 129 |
+
"""
|
| 130 |
+
w2c = np.linalg.inv(c2w)
|
| 131 |
+
N = points_world.shape[0]
|
| 132 |
+
pts_h = np.concatenate([points_world, np.ones((N, 1))], axis=1) # (N, 4)
|
| 133 |
+
pts_cam = (w2c @ pts_h.T).T[:, :3] # (N, 3)
|
| 134 |
+
uv_h = (K @ pts_cam.T).T # (N, 3)
|
| 135 |
+
# Avoid divide by zero / behind camera
|
| 136 |
+
z = uv_h[:, 2]
|
| 137 |
+
uv = np.zeros((N, 2), dtype=np.float64)
|
| 138 |
+
valid = np.abs(z) > 1e-8
|
| 139 |
+
uv[valid] = uv_h[valid, :2] / z[valid, None]
|
| 140 |
+
return uv, pts_cam[:, 2]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def find_gripper_entry_frame(eef_world_per_video_frame: np.ndarray,
|
| 144 |
+
c2w: np.ndarray, K: np.ndarray,
|
| 145 |
+
H: int, W: int,
|
| 146 |
+
margin: int = 0) -> int:
|
| 147 |
+
"""
|
| 148 |
+
Find first t such that EEF at video-frame t projects inside [margin, W-margin) x
|
| 149 |
+
[margin, H-margin) with positive depth.
|
| 150 |
+
|
| 151 |
+
eef_world_per_video_frame: (T_video, 3)
|
| 152 |
+
Returns index in [0, T_video), or -1 if never visible.
|
| 153 |
+
"""
|
| 154 |
+
uv, z_cam = project_points_world_to_pixel(eef_world_per_video_frame, c2w, K)
|
| 155 |
+
u = uv[:, 0]
|
| 156 |
+
v = uv[:, 1]
|
| 157 |
+
in_view = (
|
| 158 |
+
(u >= margin) & (u < W - margin) &
|
| 159 |
+
(v >= margin) & (v < H - margin) &
|
| 160 |
+
(z_cam > 0.0)
|
| 161 |
+
)
|
| 162 |
+
idx = np.where(in_view)[0]
|
| 163 |
+
return int(idx[0]) if len(idx) > 0 else -1
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ---------------------------------------------------------------------------
|
| 167 |
+
# Video I/O
|
| 168 |
+
# ---------------------------------------------------------------------------
|
| 169 |
+
|
| 170 |
+
def read_video_frame(video_path: Path, frame_idx: int) -> np.ndarray:
|
| 171 |
+
"""Return a single frame (H, W, 3) in BGR order from an .mp4 at frame_idx."""
|
| 172 |
+
cap = cv2.VideoCapture(str(video_path))
|
| 173 |
+
if not cap.isOpened():
|
| 174 |
+
raise IOError(f"Cannot open video: {video_path}")
|
| 175 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
| 176 |
+
ok, frame = cap.read()
|
| 177 |
+
cap.release()
|
| 178 |
+
if not ok:
|
| 179 |
+
raise IOError(f"Cannot read frame {frame_idx} from {video_path}")
|
| 180 |
+
return frame # BGR
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def video_frame_count_and_size(video_path: Path):
|
| 184 |
+
cap = cv2.VideoCapture(str(video_path))
|
| 185 |
+
if not cap.isOpened():
|
| 186 |
+
raise IOError(f"Cannot open video: {video_path}")
|
| 187 |
+
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 188 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 189 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 190 |
+
cap.release()
|
| 191 |
+
return n, h, w
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# ---------------------------------------------------------------------------
|
| 195 |
+
# Action-to-video mapping
|
| 196 |
+
# ---------------------------------------------------------------------------
|
| 197 |
+
|
| 198 |
+
def frame_to_action_index(frame_idx: int, num_frames: int, num_actions: int) -> int:
|
| 199 |
+
"""
|
| 200 |
+
Map a video frame index to its corresponding action index.
|
| 201 |
+
|
| 202 |
+
Handles non-exact ratios (e.g. 41 video frames : 163 actions = 3.976:1)
|
| 203 |
+
by rounding and clamping to [0, num_actions - 1]. The last video frame
|
| 204 |
+
always maps to the last action, absorbing the ±1 ragged tail.
|
| 205 |
+
"""
|
| 206 |
+
if num_frames <= 1:
|
| 207 |
+
return 0
|
| 208 |
+
# Pin the last video frame to the last action.
|
| 209 |
+
if frame_idx >= num_frames - 1:
|
| 210 |
+
return num_actions - 1
|
| 211 |
+
ratio = num_actions / num_frames
|
| 212 |
+
act_idx = int(round(frame_idx * ratio))
|
| 213 |
+
return max(0, min(act_idx, num_actions - 1))
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def build_action_for_video_frames(actions_8d_full: np.ndarray,
|
| 217 |
+
n_video: int) -> np.ndarray:
|
| 218 |
+
"""Return (n_video, 8) by mapping each video frame idx -> action idx."""
|
| 219 |
+
T_act = actions_8d_full.shape[0]
|
| 220 |
+
idxs = np.array([frame_to_action_index(t, n_video, T_act)
|
| 221 |
+
for t in range(n_video)], dtype=np.int64)
|
| 222 |
+
return actions_8d_full[idxs]
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ---------------------------------------------------------------------------
|
| 226 |
+
# Per-episode per-view processing
|
| 227 |
+
# ---------------------------------------------------------------------------
|
| 228 |
+
|
| 229 |
+
def process_view(episode_dir: Path, view_dir: Path, out_view_dir: Path,
|
| 230 |
+
actions_8d_full: np.ndarray,
|
| 231 |
+
n_previous: int, hand: str,
|
| 232 |
+
fix_tol: float, margin: int, observation_offset: int,
|
| 233 |
+
verbose: bool = True):
|
| 234 |
+
"""Returns a status string for logging."""
|
| 235 |
+
cam_path = view_dir / "camera_params.json"
|
| 236 |
+
video_path = view_dir / "rgb" / "video.mp4"
|
| 237 |
+
|
| 238 |
+
if not cam_path.exists():
|
| 239 |
+
return f"SKIP (no camera_params.json)"
|
| 240 |
+
if not video_path.exists():
|
| 241 |
+
return f"SKIP (no rgb/video.mp4)"
|
| 242 |
+
|
| 243 |
+
# Camera params
|
| 244 |
+
frame_ids, ext, K_stack = load_camera_params(cam_path)
|
| 245 |
+
if not is_fixed_camera(ext, tol=fix_tol):
|
| 246 |
+
max_diff = float(np.abs(ext - ext[0:1]).max())
|
| 247 |
+
return f"SKIP (camera not fixed, max ext diff={max_diff:.4f})"
|
| 248 |
+
|
| 249 |
+
c2w = ext[0].astype(np.float32) # (4, 4)
|
| 250 |
+
K = normalize_intrinsic(K_stack[0]) # (3, 3)
|
| 251 |
+
|
| 252 |
+
# Video
|
| 253 |
+
n_video, H, W = video_frame_count_and_size(video_path)
|
| 254 |
+
if n_video < 2:
|
| 255 |
+
return f"SKIP (video has {n_video} frame(s))"
|
| 256 |
+
|
| 257 |
+
# Align actions to video frames via ratio mapping.
|
| 258 |
+
# For each video frame t in [0, n_video), pick action[round(t * T_act / n_video)].
|
| 259 |
+
# This handles non-exact ratios (e.g. 163:41 or 164:41) by clamping at the tail.
|
| 260 |
+
T_act_full = actions_8d_full.shape[0]
|
| 261 |
+
actions_video_rate = build_action_for_video_frames(actions_8d_full, n_video) # (n_video, 8)
|
| 262 |
+
|
| 263 |
+
# Detect gripper entry frame using right-hand EEF xyz (cols 0:3 in the 8D layout).
|
| 264 |
+
eef_world_seq = actions_video_rate[:, 0:3].astype(np.float32) # (n_video, 3)
|
| 265 |
+
t_entry = find_gripper_entry_frame(eef_world_seq, c2w, K,
|
| 266 |
+
H=H, W=W, margin=margin)
|
| 267 |
+
if t_entry < 0:
|
| 268 |
+
return f"SKIP (gripper never projects into view; video={n_video})"
|
| 269 |
+
|
| 270 |
+
# Apply observation offset: start a few frames AFTER entry so the gripper
|
| 271 |
+
# is meaningfully inside the frame, not just clipping the edge.
|
| 272 |
+
t_start = t_entry + observation_offset
|
| 273 |
+
if t_start >= n_video - 1:
|
| 274 |
+
return (f"SKIP (t_start={t_start} (entry={t_entry} + offset={observation_offset}) "
|
| 275 |
+
f">= n_video={n_video})")
|
| 276 |
+
|
| 277 |
+
# Slice from t_start
|
| 278 |
+
actions_sliced_8d = actions_video_rate[t_start:] # (T_out, 8)
|
| 279 |
+
T_out = actions_sliced_8d.shape[0]
|
| 280 |
+
|
| 281 |
+
# Convert to dual-hand + history pad
|
| 282 |
+
a16 = single_to_dual(actions_sliced_8d, hand=hand)
|
| 283 |
+
a16 = prepend_history_pad(a16, n_previous=n_previous) # (T_out + 3, 16)
|
| 284 |
+
|
| 285 |
+
# Grab video frame at t_start (BGR); save as PNG
|
| 286 |
+
frame_bgr = read_video_frame(video_path, t_start)
|
| 287 |
+
|
| 288 |
+
# Write outputs
|
| 289 |
+
out_view_dir.mkdir(parents=True, exist_ok=True)
|
| 290 |
+
cv2.imwrite(str(out_view_dir / "frame.png"), frame_bgr)
|
| 291 |
+
np.save(out_view_dir / "actions.npy", a16)
|
| 292 |
+
np.save(out_view_dir / "extrinsics.npy", c2w)
|
| 293 |
+
np.save(out_view_dir / "intrinsics.npy", K)
|
| 294 |
+
|
| 295 |
+
return (f"OK (entry={t_entry}, t_start={t_start}, T_out={T_out}, padded={a16.shape[0]}, "
|
| 296 |
+
f"video={n_video}x{H}x{W}, actions={T_act_full}, ratio={T_act_full/n_video:.3f})")
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# ---------------------------------------------------------------------------
|
| 300 |
+
# Top-level walker
|
| 301 |
+
# ---------------------------------------------------------------------------
|
| 302 |
+
|
| 303 |
+
def process_episode(ep_dir: Path, out_ep_dir: Path,
|
| 304 |
+
n_previous: int, hand: str,
|
| 305 |
+
fix_tol: float, margin: int, observation_offset: int,
|
| 306 |
+
verbose: bool = True):
|
| 307 |
+
actions_path = ep_dir / "actions.npy"
|
| 308 |
+
if not actions_path.exists():
|
| 309 |
+
print(f"[{ep_dir.name}] SKIP: no actions.npy")
|
| 310 |
+
return
|
| 311 |
+
|
| 312 |
+
actions_8d_full = np.load(actions_path)
|
| 313 |
+
if actions_8d_full.ndim != 2 or actions_8d_full.shape[1] != 8:
|
| 314 |
+
print(f"[{ep_dir.name}] SKIP: actions.npy shape {actions_8d_full.shape} != (T, 8)")
|
| 315 |
+
return
|
| 316 |
+
|
| 317 |
+
view_dirs = [d for d in sorted(ep_dir.iterdir())
|
| 318 |
+
if d.is_dir() and (d / "camera_params.json").exists()]
|
| 319 |
+
if not view_dirs:
|
| 320 |
+
print(f"[{ep_dir.name}] SKIP: no view folders with camera_params.json")
|
| 321 |
+
return
|
| 322 |
+
|
| 323 |
+
for view_dir in view_dirs:
|
| 324 |
+
out_view_dir = out_ep_dir / view_dir.name
|
| 325 |
+
status = process_view(
|
| 326 |
+
episode_dir=ep_dir, view_dir=view_dir, out_view_dir=out_view_dir,
|
| 327 |
+
actions_8d_full=actions_8d_full,
|
| 328 |
+
n_previous=n_previous, hand=hand,
|
| 329 |
+
fix_tol=fix_tol, margin=margin,
|
| 330 |
+
observation_offset=observation_offset,
|
| 331 |
+
verbose=verbose,
|
| 332 |
+
)
|
| 333 |
+
print(f"[{ep_dir.name}/{view_dir.name}] {status}")
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def main():
|
| 337 |
+
p = argparse.ArgumentParser(
|
| 338 |
+
formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__
|
| 339 |
+
)
|
| 340 |
+
p.add_argument("-i", "--input_root", required=True, type=Path,
|
| 341 |
+
help="Root folder containing episode_* subfolders")
|
| 342 |
+
p.add_argument("-o", "--output_root", required=True, type=Path,
|
| 343 |
+
help="Output folder (will be created)")
|
| 344 |
+
p.add_argument("--episodes", nargs="*", default=None,
|
| 345 |
+
help="Only process these episode subfolder names (default: all)")
|
| 346 |
+
p.add_argument("--n_previous", type=int, default=4,
|
| 347 |
+
help="EVAC history length to pad (default 4)")
|
| 348 |
+
p.add_argument("--hand", choices=["left", "right"], default="right",
|
| 349 |
+
help="Which side of the 16D layout gets the real data")
|
| 350 |
+
p.add_argument("--fix_tol", type=float, default=1e-6,
|
| 351 |
+
help="Max per-element extrinsics diff to count as 'fixed camera'")
|
| 352 |
+
p.add_argument("--margin", type=int, default=0,
|
| 353 |
+
help="Pixel margin for gripper-in-view check (default 0)")
|
| 354 |
+
p.add_argument("--observation_offset", type=int, default=3,
|
| 355 |
+
help="Number of video frames to advance past the gripper-entry "
|
| 356 |
+
"frame before taking observation (default 2)")
|
| 357 |
+
args = p.parse_args()
|
| 358 |
+
|
| 359 |
+
if not args.input_root.exists():
|
| 360 |
+
raise FileNotFoundError(args.input_root)
|
| 361 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 362 |
+
|
| 363 |
+
# Discover episode folders
|
| 364 |
+
ep_dirs = sorted([d for d in args.input_root.iterdir() if d.is_dir()])
|
| 365 |
+
if args.episodes:
|
| 366 |
+
wanted = set(args.episodes)
|
| 367 |
+
ep_dirs = [d for d in ep_dirs if d.name in wanted]
|
| 368 |
+
|
| 369 |
+
print(f"Found {len(ep_dirs)} episode(s) to process in {args.input_root}")
|
| 370 |
+
print(f"Output -> {args.output_root}")
|
| 371 |
+
print(f"Params: n_previous={args.n_previous}, hand={args.hand}, "
|
| 372 |
+
f"fix_tol={args.fix_tol}, margin={args.margin}, "
|
| 373 |
+
f"observation_offset={args.observation_offset}")
|
| 374 |
+
print("-" * 70)
|
| 375 |
+
|
| 376 |
+
for ep_dir in ep_dirs:
|
| 377 |
+
out_ep_dir = args.output_root / ep_dir.name
|
| 378 |
+
process_episode(
|
| 379 |
+
ep_dir=ep_dir, out_ep_dir=out_ep_dir,
|
| 380 |
+
n_previous=args.n_previous,
|
| 381 |
+
hand=args.hand, fix_tol=args.fix_tol, margin=args.margin,
|
| 382 |
+
observation_offset=args.observation_offset,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
if __name__ == "__main__":
|
| 387 |
+
main()
|