#!/usr/bin/env python3 """Local web UI for synchronized robot views and sensor/label curves.""" from __future__ import annotations import argparse import json import math import mimetypes import os import subprocess import tempfile import threading import webbrowser from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any, Dict, List from urllib.parse import parse_qs, unquote, urlparse import numpy as np import pyarrow.parquet as pq os.environ.setdefault( "MPLCONFIGDIR", str(Path(tempfile.gettempdir()) / "mplconfig-ui"), ) DATA_ROOT = Path(__file__).resolve().parent.parent VIEWS = ["wrist", "side_1", "side_2"] FORCE_NAMES = ["Fx", "Fy", "Fz", "Tx", "Ty", "Tz"] FORCE_COLUMN = "observation.state.wrench_filtered_chunk" VALID_LEN_COLUMN = "observation.state.wrench_chunk_valid_len" # The method and real UIs enable this for browser-compatible playback of the # original mp4v videos. Originals are never modified; converted files live in # a process-local temporary directory and are removed when the UI exits. VIDEO_TRANSCODE = True VIDEO_CACHE_TEMP: tempfile.TemporaryDirectory | None = None VIDEO_CACHE_ROOT: Path | None = None VIDEO_TRANSCODE_LOCK = threading.Lock() VERBOSE = False def find_one_file(task_dir: Path, pattern: str, description: str) -> Path: matches = sorted(task_dir.glob(pattern)) if not matches: raise FileNotFoundError(f"Could not find {description}: {pattern}") return matches[0] def smooth_series(values: np.ndarray, window: int) -> np.ndarray: if window <= 1 or len(values) == 0: return np.asarray(values, dtype=np.float64).copy() window = min(window, len(values)) kernel = np.ones(window, dtype=np.float64) / window left = window // 2 right = window - 1 - left padded = np.pad(values, (left, right), mode="edge") return np.convolve(padded, kernel, mode="valid") def interpolate_missing(values: np.ndarray) -> np.ndarray: """Fill missing 1D values without smoothing the observed values.""" values = np.asarray(values, dtype=np.float64).copy() if values.ndim != 1: raise ValueError("values must be a 1D array") valid = np.isfinite(values) if valid.all() or not valid.any(): return values indices = np.arange(len(values)) return np.interp(indices, indices[valid], values[valid]) def load_interaction_onset(task_dir: Path, episode: int) -> int | None: annotation_path = task_dir / "meta" / "annotation.json" if not annotation_path.exists(): return None try: annotation = json.loads(annotation_path.read_text(encoding="utf-8")) record = annotation.get("episodes", {}).get(f"{episode:06d}", {}) except (json.JSONDecodeError, OSError): return None interaction = record.get("interaction", {}) manual = interaction.get("manual", {}) if isinstance(manual.get("onset_frame_index"), (int, float)): return int(manual["onset_frame_index"]) auto = interaction.get("auto", {}) if isinstance(auto.get("onset_frame_index"), (int, float)): return int(auto["onset_frame_index"]) return None def extract_force_channels(df: Any) -> np.ndarray: raw = df[FORCE_COLUMN].to_numpy() # LeRobot stores this feature as an object array of 4 x 6 numpy arrays. stacked = np.stack([np.stack(list(item), axis=0) for item in raw], axis=0) valid = df[VALID_LEN_COLUMN].to_numpy(dtype=np.int64) result = np.zeros((len(stacked), len(FORCE_NAMES)), dtype=np.float64) for i, (chunk, length) in enumerate(zip(stacked, valid)): index = max(0, int(length) - 1) result[i] = chunk[index] return result def load_episode_data(category: str, task: str, episode: int) -> Dict[str, Any]: task_dir = DATA_ROOT / category / task if not task_dir.is_dir(): raise FileNotFoundError(f"Task directory does not exist: {task_dir}") episode_key = f"{episode:06d}" parquet_path = find_one_file( task_dir, f"data/chunk-*/episode_{episode_key}.parquet", "episode parquet", ) table = pq.read_table(parquet_path) df = table.to_pandas() if "frame_index" in df.columns: frame_indices = df["frame_index"].to_numpy(dtype=np.int64) else: frame_indices = np.arange(len(df), dtype=np.int64) frame_label = smooth_series(df["frame_label"].to_numpy(dtype=np.float64), 15) force = extract_force_channels(df) force_smooth = np.column_stack( [smooth_series(force[:, i], 15) for i in range(len(FORCE_NAMES))] ) force_norm_truth = np.sqrt( np.sum(np.square(force_smooth[:, :3]), axis=1) ) ee_pose = np.stack(df["observation.state.ee_pose"].to_numpy(), axis=0) position = np.column_stack( [smooth_series(ee_pose[:, i].astype(np.float64), 15) for i in range(3)] ) videos: Dict[str, str] = {} for view in VIEWS: video_path = find_one_file( task_dir, f"videos/{view}/chunk-*/episode_{episode_key}.mp4", f"video for view {view!r}", ) relative = video_path.relative_to(DATA_ROOT).as_posix() videos[view] = f"/videos/{relative}" interaction_onset = load_interaction_onset(task_dir, episode) return { "category": category, "task": task, "episode": episode, "fps": 30.0, "frame_count": len(frame_indices), "frame_indices": frame_indices.tolist(), "frame_label": frame_label.tolist(), "force_names": FORCE_NAMES, "force_truth": force_smooth.T.tolist(), "force_norm_truth": force_norm_truth.tolist(), "position": position.T.tolist(), "interaction_onset": interaction_onset, "videos": videos, } def list_categories_and_tasks() -> Dict[str, Any]: categories: List[Dict[str, Any]] = [] for category_dir in sorted(DATA_ROOT.iterdir()): if not category_dir.is_dir() or category_dir.name.startswith("."): continue tasks = [ task_dir.name for task_dir in sorted(category_dir.iterdir()) if task_dir.is_dir() and (task_dir / "meta" / "info.json").exists() ] if tasks: categories.append({"name": category_dir.name, "tasks": tasks}) return {"categories": categories} def list_episode_records(category: str, task: str) -> List[Dict[str, Any]]: path = DATA_ROOT / category / task / "meta" / "episodes.jsonl" records: List[Dict[str, Any]] = [] with path.open(encoding="utf-8") as handle: for line in handle: if line.strip(): records.append(json.loads(line)) return records class UIRequestHandler(BaseHTTPRequestHandler): server_version = "CRIAExplorerUI/1.0" def log_message(self, fmt: str, *args: Any) -> None: if VERBOSE: print(f"[ui] {self.address_string()} - {fmt % args}") def _send_json(self, payload: Any, status: int = 200) -> None: body = json.dumps(payload, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def _send_error(self, status: int, message: str) -> None: self._send_json({"error": message}, status=status) @staticmethod def _browser_video_path(path: Path) -> Path: if not VIDEO_TRANSCODE or path.suffix.lower() != ".mp4": return path global VIDEO_CACHE_TEMP, VIDEO_CACHE_ROOT if VIDEO_CACHE_TEMP is None: VIDEO_CACHE_TEMP = tempfile.TemporaryDirectory(prefix="forcewm_video_") VIDEO_CACHE_ROOT = Path(VIDEO_CACHE_TEMP.name) assert VIDEO_CACHE_ROOT is not None relative = path.resolve().relative_to(DATA_ROOT.resolve()) cached = VIDEO_CACHE_ROOT / relative if cached.is_file(): return cached # Multiple video elements can request the same file concurrently. # Keep conversion atomic so no request sees a partially written MP4. with VIDEO_TRANSCODE_LOCK: if cached.is_file(): return cached cached.parent.mkdir(parents=True, exist_ok=True) temporary = cached.with_suffix(".tmp.mp4") command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(path), "-map", "0:v:0", "-map", "0:a?", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-c:a", "aac", "-b:a", "128k", str(temporary), ] try: subprocess.run(command, check=True, stdout=subprocess.DEVNULL) temporary.replace(cached) except (OSError, subprocess.CalledProcessError) as exc: temporary.unlink(missing_ok=True) raise RuntimeError(f"ffmpeg transcode failed for {path}: {exc}") from exc return cached def _send_file_range(self, path: Path) -> None: resolved = path.resolve() if not resolved.is_relative_to(DATA_ROOT.resolve()): self._send_error(403, "forbidden path") return if not resolved.is_file(): self._send_error(404, "file not found") return try: resolved = self._browser_video_path(resolved) except RuntimeError as exc: self._send_error(500, str(exc)) return size = resolved.stat().st_size range_header = self.headers.get("Range") start = 0 end = size - 1 if range_header and range_header.startswith("bytes="): try: start_text, end_text = range_header[6:].split("-", 1) start = int(start_text) if start_text else start end = int(end_text) if end_text else end except ValueError: self._send_error(416, "invalid range") return start = max(0, min(start, size - 1)) end = max(start, min(end, size - 1)) status = 206 else: status = 200 content_length = end - start + 1 content_type = mimetypes.guess_type(resolved.name)[0] or "application/octet-stream" self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Accept-Ranges", "bytes") self.send_header("Content-Length", str(content_length)) if status == 206: self.send_header("Content-Range", f"bytes {start}-{end}/{size}") self.end_headers() with resolved.open("rb") as handle: handle.seek(start) remaining = content_length while remaining > 0: chunk = handle.read(min(1024 * 1024, remaining)) if not chunk: break self.wfile.write(chunk) remaining -= len(chunk) def do_GET(self) -> None: parsed = urlparse(self.path) path = unquote(parsed.path) if path == "/api/options": self._send_json(list_categories_and_tasks()) return if path == "/api/data": query = parse_qs(parsed.query) try: category = query.get("category", [""])[0] task = query.get("task", [""])[0] episode = int(query.get("episode", [""])[0]) data = load_episode_data(category, task, episode) self._send_json(data) except (KeyError, TypeError, ValueError, FileNotFoundError) as exc: self._send_error(400, str(exc)) return if path == "/api/episodes": query = parse_qs(parsed.query) try: records = list_episode_records(query.get("category", [""])[0], query.get("task", [""])[0]) source = query.get("source", ["all"])[0] result = query.get("result", ["all"])[0] if source != "all": records = [r for r in records if r.get("source") == source] if result != "all": label = 1 if result == "success" else 0 records = [r for r in records if int(r.get("episode_label", -1)) == label] self._send_json({"episodes": records}) except (KeyError, TypeError, ValueError, FileNotFoundError, json.JSONDecodeError) as exc: self._send_error(400, str(exc)) return if path.startswith("/videos/"): relative = path[len("/videos/") :] self._send_file_range(DATA_ROOT / relative) return if path == "/" or path == "/index.html": body = INDEX_HTML_BYTES self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return self._send_error(404, "not found") INDEX_HTML = r""" CRIA Dataset Explorer
CRIA Dataset Explorer
measured signals interaction onset anomaly
frame 0 / 0
wrist
side_1
side_2
F_x
F_y
F_z
τ_x
τ_y
τ_z
p_x
p_y
p_z
""" INDEX_HTML_BYTES = INDEX_HTML.encode("utf-8") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Serve the CRIA dataset explorer UI") parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8765) parser.add_argument( "--root", type=Path, default=Path(__file__).resolve().parent.parent, help="Path to the CRIA dataset root", ) parser.add_argument( "--verbose", action="store_true", help="Enable HTTP access logs", ) parser.add_argument("--no-browser", action="store_true") return parser.parse_args() def main() -> None: args = parse_args() global DATA_ROOT, VERBOSE DATA_ROOT = args.root.expanduser().resolve() VERBOSE = args.verbose server = ThreadingHTTPServer((args.host, args.port), UIRequestHandler) url = f"http://{args.host}:{args.port}/" print(f"CRIA root: {DATA_ROOT}") print(f"UI server running at {url}") if not args.no_browser: threading.Timer(0.8, lambda: webbrowser.open(url)).start() try: server.serve_forever() except KeyboardInterrupt: print("\nshutting down") finally: server.server_close() global VIDEO_CACHE_TEMP if VIDEO_CACHE_TEMP is not None: VIDEO_CACHE_TEMP.cleanup() VIDEO_CACHE_TEMP = None if __name__ == "__main__": main()