#!/usr/bin/env python3 """Create offline illustrations and single-view examples from completed OXT tasks. Inputs are opened read-only. The 15 fps MP4 is a presentation-only resampling of irregular recorded control rows; no training array or native recording is changed. These previews do not establish physical camera/force synchronization or calibration. """ from __future__ import annotations import argparse from datetime import datetime, timezone import json import os from pathlib import Path import subprocess import tempfile from typing import Any import cv2 import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import zarr TASKS = ("wipe_board", "hang_tape", "push_button", "insert_pen") CAMERAS = ( ("right_wrist_camera", "16478870", "Wrist camera"), ("camera_main", "36087771", "External camera"), ) FPS = 15 VIDEO_SECONDS = 8.0 VIDEO_FRAMES = 120 def scalar_text(value: Any) -> str: return value.decode("utf-8") if isinstance(value, bytes) else str(value) def nearest_rows(times: np.ndarray, targets: np.ndarray) -> np.ndarray: """Select existing rows nearest in control time; exact ties use earlier rows.""" times = np.asarray(times, dtype=np.float64) targets = np.asarray(targets, dtype=np.float64) if times.ndim != 1 or len(times) < 2 or not np.isfinite(times).all() or not np.all(np.diff(times) > 0): raise ValueError("An episode needs at least two finite, increasing control timestamps") if not np.isfinite(targets).all(): raise ValueError("Nonfinite preview target timestamp") later = np.clip(np.searchsorted(times, targets, side="left"), 0, len(times) - 1) earlier = np.maximum(later - 1, 0) choose_later = np.abs(times[later] - targets) < np.abs(times[earlier] - targets) return np.where(choose_later, later, earlier).astype(np.int64) def letterbox_rgb(frame: np.ndarray, size: int = 224) -> np.ndarray: """Resize an RGB image inside a square without cropping its field of view.""" frame = np.asarray(frame) if frame.dtype != np.uint8 or frame.ndim != 3 or frame.shape[2] != 3: raise ValueError("Expected an RGB uint8 HWC image") h, w = frame.shape[:2] if h <= 0 or w <= 0: raise ValueError("Empty RGB frame") scale = min(size / w, size / h) width, height = max(1, round(w * scale)), max(1, round(h * scale)) mode = cv2.INTER_AREA if scale <= 1 else cv2.INTER_LINEAR resized = cv2.resize(frame, (width, height), interpolation=mode) result = np.zeros((size, size, 3), dtype=np.uint8) x, y = (size - width) // 2, (size - height) // 2 result[y:y + height, x:x + width] = resized return result def temporary_path(destination: Path) -> Path: destination.parent.mkdir(parents=True, exist_ok=True) fd, name = tempfile.mkstemp(prefix="." + destination.stem + "-", suffix=destination.suffix, dir=destination.parent) os.close(fd) return Path(name) def atomic_json(destination: Path, document: dict) -> None: partial = temporary_path(destination) try: partial.write_text(json.dumps(document, ensure_ascii=False, indent=2) + "\n") partial.replace(destination) finally: partial.unlink(missing_ok=True) def camera_metadata(data: Any, role: str, serial: str, rows: np.ndarray) -> dict: # Both names are accepted so this tool also works with role aliases. time_key = next((k for k in ("camera_timestamp_unix_ns__" + serial, role + "_timestamp_ns") if k in data), None) index_key = next((k for k in ("camera_frame_index__" + serial, role + "_frame_index") if k in data), None) result = {"serial": serial, "rgb_key": role + "_rgb"} for target, source in (("source_image_unix_ns", time_key), ("source_svo_frame_index", index_key)): result[target] = [int(data[source][int(i)]) for i in rows] if source else None return result def save_inspection_png(destination: Path, task: str, episode_name: str, data: Any, times: np.ndarray, wrench: np.ndarray, rows: np.ndarray) -> dict: if wrench.shape != (len(times), 6) or not np.isfinite(wrench).all(): raise ValueError("Expected finite FT snapshots with shape (T,6)") fig = plt.figure(figsize=(16, 11.5), dpi=100, facecolor="#f7f8fa") grid = fig.add_gridspec(3, 6, height_ratios=[1, 1, 0.92], left=0.045, right=0.985, top=0.91, bottom=0.11, hspace=0.38, wspace=0.5) fig.suptitle(task.replace("_", " ").upper() + " | First recorded episode", x=0.045, y=0.975, ha="left", fontsize=20, fontweight="bold") fig.text(0.045, 0.942, episode_name + " | Samples selected by recorded control time", fontsize=11) camera_info = {} try: for camera_row, (role, serial, title) in enumerate(CAMERAS): camera_info[role] = camera_metadata(data, role, serial, rows) for col, row in enumerate(rows): ax = fig.add_subplot(grid[camera_row, col * 2:(col + 1) * 2]) frame = np.asarray(data[role + "_rgb"][int(row)]) if frame.dtype != np.uint8 or frame.ndim != 3 or frame.shape[-1] != 3: raise ValueError("Malformed RGB image in " + role) ax.imshow(frame) ax.set_axis_off() source_row = int(data["source_control_row"][int(row)]) ax.set_title(f"{title} | control {times[row]:.3f} s | row {source_row}", fontsize=10, pad=6) exact = camera_info[role]["source_image_unix_ns"] image_index = camera_info[role]["source_svo_frame_index"] details = f"SVO frame {image_index[col]}" if image_index else "SVO frame index unavailable" if exact: details += f" | image Unix ns {exact[col]}" ax.text(0.0, -0.08, details, transform=ax.transAxes, fontsize=7.5, color="#444444") colors = ("#148a86", "#d58b16", "#4b66bc") for panel, (start, title, unit, labels) in enumerate(( (0, "Force snapshots", "N", ("Fx", "Fy", "Fz")), (3, "Torque snapshots", "Nm", ("Mx", "My", "Mz")), )): ax = fig.add_subplot(grid[2, panel * 3:(panel + 1) * 3]) ax.set_title(title + f" ({unit}; configured device units)", fontsize=12, loc="left") for axis, (label, color) in enumerate(zip(labels, colors)): ax.plot(times, wrench[:, start + axis], color=color, linewidth=0.8, label=label) ax.scatter(times[rows], wrench[rows, start + axis], color=color, s=22, edgecolors="white", linewidths=0.5, zorder=4) for row in rows: ax.axvline(times[row], color="#777777", linewidth=0.7, linestyle="--", alpha=0.65) ax.set_xlim(float(times[0]), float(times[-1])) ax.set_xlabel("Recorded control time within episode (s)") ax.set_ylabel(unit) ax.grid(alpha=0.2) ax.legend(ncol=3, fontsize=9, loc="best") fig.text(0.045, 0.058, "FT: native sensor frame; device N/Nm units assumed, not independently confirmed. No added bias or gravity compensation.", fontsize=10) fig.text(0.045, 0.034, "Plots show all retained control-row FT snapshots. Images share control rows; physical camera/FT synchronization is not verified.", fontsize=9, color="#444444") partial = temporary_path(destination) try: fig.savefig(partial, dpi=100) partial.replace(destination) finally: partial.unlink(missing_ok=True) finally: plt.close(fig) return {"selected_episode_rows": rows.tolist(), "selected_source_control_rows": [int(data["source_control_row"][int(i)]) for i in rows], "selected_control_times_s": times[rows].tolist(), "cameras": camera_info, "ft_rows_plotted": len(times), "ft_channels": ["Fx", "Fy", "Fz", "Mx", "My", "Mz"]} def save_example_mp4(destination: Path, data: Any, times: np.ndarray, ffmpeg: str) -> dict: span = float(times[-1] - times[0]) if span <= 0: raise ValueError("A still/single-timestamp episode cannot provide a meaningful action preview") source_duration = min(VIDEO_SECONDS, span) source_start = float(times[0] + (span - source_duration) / 2) # Presentation intervals are [0,8), not 120 linspace samples including 8. output_times = np.arange(VIDEO_FRAMES, dtype=np.float64) / FPS playback_rate = source_duration / VIDEO_SECONDS target_times = source_start + output_times * playback_rate indices = nearest_rows(times, target_times) partial = temporary_path(destination) command = [ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pixel_format", "rgb24", "-video_size", "224x224", "-framerate", str(FPS), "-i", "pipe:0", "-an", "-frames:v", str(VIDEO_FRAMES), "-c:v", "libx264", "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p", "-threads", "2", "-movflags", "+faststart", str(partial)] process = None try: with tempfile.TemporaryFile() as errors: process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors) previous_row, previous_frame = None, None try: for row in indices: if previous_row != int(row): previous_frame = letterbox_rgb(np.asarray(data["camera_main_rgb"][int(row)])) previous_row = int(row) process.stdin.write(previous_frame.tobytes()) process.stdin.close() code = process.wait(timeout=60) except Exception: if process.poll() is None: process.kill() process.wait(timeout=10) errors.seek(0) detail = errors.read().decode("utf-8", errors="replace")[-4000:] if detail: raise RuntimeError("ffmpeg example encoding failed: " + detail) raise if code: errors.seek(0) raise RuntimeError("ffmpeg example encoding failed: " + errors.read().decode("utf-8", errors="replace")[-4000:]) if not partial.is_file() or partial.stat().st_size == 0: raise RuntimeError("ffmpeg produced an empty example") partial.replace(destination) finally: if process is not None and process.poll() is None: process.kill() process.wait(timeout=10) partial.unlink(missing_ok=True) sample_map = [] for i, row in enumerate(indices): sample_map.append({"output_frame": i, "output_time_s": float(output_times[i]), "target_control_time_s": float(target_times[i]), "episode_row": int(row), "source_control_row": int(data["source_control_row"][int(row)]), "recorded_control_time_s": float(times[row])}) return {"duration_s": VIDEO_SECONDS, "frames": VIDEO_FRAMES, "fps": FPS, "size_wh": [224, 224], "codec": "H264", "pixel_format": "yuv420p", "audio": False, "view": "camera_main_rgb; external camera 36087771, recorded rectified left eye", "image_transform": "aspect-preserving resize with black letterbox; no overlay and no crop", "source_window_start_s": source_start, "source_window_end_exclusive_s": source_start + source_duration, "source_seconds_per_output_second": playback_rate, "short_episode_slowdown": playback_rate < 1.0, "sampling": "nearest recorded control timestamp; ties choose earlier; repeated images are presentation-only", "max_control_sampling_error_s": float(np.max(np.abs(times[indices] - target_times))), "distinct_recorded_rows": int(len(np.unique(indices))), "selected_frames": sample_map, "camera": camera_metadata(data, "camera_main", "36087771", indices)} def preview_task(root: Path, task: str, ffmpeg: str = "ffmpeg") -> dict: group = zarr.open_group(str(root / "zarr" / (task + ".zarr")), mode="r") if not bool(group.attrs.get("complete", False)): raise ValueError(task + ": task export is not marked complete; do not preview a running export") data, meta = group["data"], group["meta"] ends = np.asarray(meta["episode_ends"][:]) if ends.ndim != 1 or not len(ends) or ends[0] < 2: raise ValueError(task + ": first episode is empty or too short") end = int(ends[0]) times = np.asarray(data["timestamps"][:end], dtype=np.float64) if times.shape != (end,): raise ValueError("Unexpected timestamp shape") targets = times[0] + np.asarray([0.2, 0.5, 0.8]) * (times[-1] - times[0]) rows = np.unique(nearest_rows(times, targets)) episode_name = scalar_text(meta["episode_names"][0]) png_path = root / "qc/previews" / (task + ".png") video_path = root / "examples" / (task + ".mp4") result = {"task": task, "episode_index": 0, "episode_id": scalar_text(meta["episode_ids"][0]), "episode_name": episode_name, "episode_rows": end, "episode_recorded_time_range_s": [float(times[0]), float(times[-1])], "inspection_png": str(png_path.relative_to(root)), "example_video": str(video_path.relative_to(root))} result["inspection"] = save_inspection_png(png_path, task, episode_name, data, times, np.asarray(data["ft_wrench"][:end]), rows) result["video"] = save_example_mp4(video_path, data, times, ffmpeg) result["png_bytes"] = png_path.stat().st_size result["video_bytes"] = video_path.stat().st_size return result def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", type=Path, required=True) parser.add_argument("--tasks", nargs="+", choices=TASKS, default=list(TASKS)) parser.add_argument("--ffmpeg", default="ffmpeg") args = parser.parse_args(argv) root = args.dataset_root.resolve() manifest_path = root / "metadata/preview_metadata.json" manifest = json.loads(manifest_path.read_text()) if manifest_path.is_file() else { "schema": "franka-ft-oxt-previews-v1", "dataset_root": str(root), "tasks": {}, "notes": ["All training arrays and native recordings remain unchanged.", "MP4s are 15 fps display resamplings, not the irregular training dataset timeline.", "FT values remain native sensor-frame snapshots in assumed configured N/Nm units.", "These illustrations do not verify physical synchronization, calibration, canonical pose alignment, or task success."]} if manifest.get("dataset_root") != str(root): raise ValueError("Existing preview manifest belongs to a different dataset root") for task in dict.fromkeys(args.tasks): record = preview_task(root, task, args.ffmpeg) manifest["tasks"][task] = record manifest["updated_at_utc"] = datetime.now(timezone.utc).isoformat() atomic_json(manifest_path, manifest) print(json.dumps({"task": task, "inspection_png": record["inspection_png"], "example_video": record["example_video"], "frames": VIDEO_FRAMES, "duration_s": VIDEO_SECONDS, "video_bytes": record["video_bytes"]}), flush=True) print(json.dumps({"preview_metadata": str(manifest_path), "tasks": list(manifest["tasks"])}), flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())