CRIA / scripts /visualize.py
Joringell's picture
Upload folder using huggingface_hub (part 3)
eb6b1ec verified
Raw History Blame Contribute Delete
45.5 kB
#!/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"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CRIA Dataset Explorer</title>
<style>
:root {
--bg: #f3f5f8;
--panel: #ffffff;
--border: #e4e9f0;
--text: #17202a;
--muted: #66788c;
--truth: #2563eb;
--pred: #f97316;
--shadow: 0 5px 18px rgba(21, 40, 71, 0.06);
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", sans-serif;
}
.top-bar {
position: sticky;
top: 0;
z-index: 20;
background: linear-gradient(180deg, #ffffff, #fbfdff);
box-shadow: 0 2px 14px rgba(20, 40, 80, 0.06);
}
header {
position: relative;
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 5px;
padding: 5px 32px;
background: transparent;
border-bottom: 0;
}
.brand {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 700;
font-size: 12px;
margin-right: 6px;
letter-spacing: .2px;
color: var(--text);
position: static;
transform: none;
white-space: nowrap;
grid-column: 1;
}
.brand svg {
width: 20px;
height: 20px;
color: #fff;
background: linear-gradient(135deg, #3b82f6, #1d4ed8);
padding: 4px;
border-radius: 8px;
box-shadow: 0 3px 8px rgba(37, 99, 235, .30);
}
.spacer { flex: 1 1 auto; }
header > .spacer { display: none; }
#load, #playPause {
width: 88px;
justify-content: center;
flex: 0 0 88px;
}
header > #load { grid-column: 3; }
/* Selection set: a cohesive pill container holding the pickers */
.control-group {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 4px;
justify-self: start;
grid-column: 2;
background: linear-gradient(180deg, #eef3fa, #e6ecf5);
border: 1px solid var(--border);
border-radius: 11px;
box-shadow: inset 0 1px 2px rgba(30, 47, 75, 0.05);
}
.field {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 6px 3px 7px;
border-radius: 8px;
background: #ffffff;
border: 1px solid transparent;
transition: border-color .15s ease, box-shadow .15s ease, background .15s ease;
}
.field + .field { margin-left: 2px; }
.field:hover { border-color: #c8d6ea; }
.field:focus-within {
border-color: var(--truth);
box-shadow: 0 0 0 3px rgba(37, 99, 235, .12);
background: #fff;
}
.field label {
color: var(--muted);
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .6px;
white-space: nowrap;
}
select, input[type="number"] {
height: 26px;
border: 0;
border-radius: 5px;
background: transparent;
color: var(--text);
font-size: 12px;
font-weight: 600;
padding: 0 4px;
outline: none;
min-width: 52px;
}
select {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
padding-right: 18px;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path fill='none' stroke='%2366788c' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round' d='M2 3.8l3 3 3-3'/></svg>");
background-repeat: no-repeat;
background-position: right 2px center;
cursor: pointer;
}
#category, #task { min-width: 82px; }
#source, #result { min-width: 64px; }
#episode { min-width: 88px; }
input[type="number"] { width: 52px; text-align: left; -moz-appearance: textfield; }
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 32px;
cursor: pointer;
border: 0;
border-radius: 9px;
background: linear-gradient(180deg, #3b82f6, #2563eb);
color: #fff;
font-size: 12px;
font-weight: 600;
padding: 0 15px;
outline: none;
box-shadow: 0 2px 6px rgba(37, 99, 235, .25), inset 0 1px 0 rgba(255, 255, 255, .22);
transition: background .15s ease, box-shadow .15s ease, transform .08s ease, filter .15s ease;
}
button svg { width: 14px; height: 14px; flex: 0 0 auto; }
button:hover:not(:disabled) {
background: linear-gradient(180deg, #2563eb, #1d4ed8);
transform: translateY(-1px);
box-shadow: 0 6px 16px rgba(37, 99, 235, .32), inset 0 1px 0 rgba(255, 255, 255, .22);
filter: saturate(1.05);
}
button:active:not(:disabled) { transform: translateY(0); box-shadow: 0 2px 6px rgba(37, 99, 235, .22), inset 0 1px 0 rgba(255, 255, 255, .22); }
button:focus-visible { box-shadow: 0 0 0 3px rgba(37, 99, 235, .28), 0 2px 6px rgba(37, 99, 235, .25); }
button.secondary {
background: linear-gradient(180deg, #ffffff, #eef2f7);
color: #26364a;
box-shadow: 0 2px 6px rgba(30, 47, 75, .08), inset 0 1px 0 rgba(255, 255, 255, .6);
}
button.secondary:hover:not(:disabled) {
background: linear-gradient(180deg, #ffffff, #e2e8f0);
color: #17202a;
box-shadow: 0 5px 12px rgba(30, 47, 75, .12), inset 0 1px 0 rgba(255, 255, 255, .6);
}
button:disabled { opacity: .5; cursor: not-allowed; transform: none; box-shadow: none; }
.grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
padding: 10px 32px 18px;
max-width: 1200px;
margin: 0 auto;
}
.top-bar > header, .progress-row {
max-width: 1200px;
margin-left: auto;
margin-right: auto;
}
.top-bar > header { width: 100%; }
.progress-row { width: 100%; }
.control-group { max-width: 100%; overflow: hidden; }
.field { min-width: 0; flex: 0 1 auto; }
.panel {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
overflow: hidden;
min-width: 0;
}
.panel-title {
height: 23px;
display: flex;
align-items: center;
gap: 7px;
padding: 0 10px;
border-bottom: 1px solid var(--border);
font-size: 12px;
font-weight: 700;
color: var(--muted);
background: #fbfcfe;
}
.dot { width: 8px; height: 8px; border-radius: 50%; background: #cbd5e1; }
.video-panel video { display: block; width: 100%; height: auto; aspect-ratio: 4 / 3; object-fit: contain; background: #0b1220; }
.grid { font-family: "Times New Roman", Times, serif; }
.video-panel .panel-title { justify-content: flex-start; }
canvas.chart { display: block; width: 100%; height: 108px; }
.wide { grid-column: 1 / -1; }
.wide canvas.chart { height: 132px; }
.pair-row {
grid-column: 1 / -1;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.pair-row canvas.chart { height: 132px; }
.playbar {
display: flex;
align-items: center;
gap: 8px;
padding: 5px 9px;
border-top: 1px solid var(--border);
background: #fbfcfe;
}
input[type="range"] {
flex: 1;
-webkit-appearance: none;
appearance: none;
height: 6px;
border-radius: 999px;
background: linear-gradient(
to right,
#2563eb var(--range-progress, 0%),
#dbe3ef var(--range-progress, 0%)
);
cursor: pointer;
outline: none;
box-shadow: inset 0 1px 2px rgba(30, 47, 75, 0.10);
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: #ffffff;
border: 3px solid #2563eb;
box-shadow: 0 2px 6px rgba(37, 99, 235, .30);
transition: transform .12s ease, box-shadow .12s ease;
}
input[type="range"]:hover::-webkit-slider-thumb { transform: scale(1.18); box-shadow: 0 3px 9px rgba(37, 99, 235, .38); }
input[type="range"]:active::-webkit-slider-thumb { transform: scale(1.06); }
input[type="range"]::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: #ffffff;
border: 3px solid #2563eb;
box-shadow: 0 2px 6px rgba(37, 99, 235, .30);
}
.legend {
display: inline-flex;
align-items: center;
gap: 10px;
padding: 5px 12px;
border-radius: 999px;
background: #f1f5fb;
border: 1px solid var(--border);
font-size: 11px;
color: var(--muted);
}
.legend span { display: inline-flex; align-items: center; gap: 6px; }
.legend i { width: 16px; height: 3px; border-radius: 2px; display: inline-block; box-shadow: 0 1px 2px rgba(0,0,0,.06); }
.source-badge {
display: inline-flex;
align-items: center;
height: 24px;
padding: 0 9px;
border-radius: 999px;
font-size: 10px;
font-weight: 700;
letter-spacing: .2px;
border: 1px solid var(--border);
white-space: nowrap;
}
.source-badge.synthetic { color: #9a6b00; background: #fff7db; }
.source-badge.episode_records { color: #047857; background: #e8f9f0; }
.source-badge.predicted_values\.json { color: #0369a1; background: #e8f5ff; }
.progress-row {
display: flex;
align-items: center;
gap: 8px;
padding: 5px 32px;
background: transparent;
border-bottom: 1px solid var(--border);
}
#time-label {
min-width: 96px;
text-align: center;
color: #26364a;
background: #eef2f7;
border: 1px solid var(--border);
border-radius: 7px;
padding: 3px 10px;
font-size: 11px;
font-weight: 600;
font-variant-numeric: tabular-nums;
box-shadow: inset 0 1px 1px rgba(30, 47, 75, 0.04);
}
@media (max-width: 900px) {
.grid { grid-template-columns: 1fr; padding: 12px 16px 20px; }
.pair-row { grid-template-columns: 1fr; }
header { flex-wrap: wrap; padding: 10px 16px; }
.progress-row { padding: 6px 16px; }
}
</style>
</head>
<body>
<div class="top-bar">
<header>
<div class="brand">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M4 17l5-5 4 3 7-8" />
<path d="M15 7h5v5" />
</svg>
<span>CRIA Dataset Explorer</span>
</div>
<div class="control-group">
<div class="field">
<label for="category">Category</label>
<select id="category"></select>
</div>
<div class="field">
<label for="task">Task</label>
<select id="task"></select>
</div>
<div class="field">
<label for="source">Source</label>
<select id="source"><option value="all">all</option><option value="human">human</option><option value="pi05_joint">pi05_joint</option></select>
</div>
<div class="field">
<label for="result">Result</label>
<select id="result"><option value="all">all</option><option value="success">success</option><option value="failure">failure</option></select>
</div>
<div class="field">
<label for="episode">Episode</label>
<select id="episode"></select>
</div>
</div>
<button id="load">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M20 11a8 8 0 1 0-2.34 5.66" />
<path d="M20 5v6h-6" />
</svg>
Load
</button>
<div class="spacer"></div>
</header>
<div class="progress-row">
<div class="legend">
<span><i style="background:#2563eb"></i>measured signals</span>
<span><i style="background:#f97316"></i>interaction onset</span>
<span><i style="background:#fecaca;height:12px"></i>anomaly</span>
</div>
<input id="timeline" type="range" min="0" max="1000" step="0.01" value="0">
<span id="time-label">frame 0 / 0</span>
<button id="playPause" class="secondary" disabled>
<svg id="play-icon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M7 5l12 7-12 7z" /></svg>
<svg id="pause-icon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style="display:none"><rect x="6" y="5" width="4" height="14" rx="1" /><rect x="14" y="5" width="4" height="14" rx="1" /></svg>
<span id="playPauseText">Play</span>
</button>
</div>
</div>
<main class="grid">
<section class="panel video-panel">
<div class="panel-title">wrist</div>
<video id="video-0" muted playsinline preload="auto"></video>
</section>
<section class="panel video-panel">
<div class="panel-title">side_1</div>
<video id="video-1" muted playsinline preload="auto"></video>
</section>
<section class="panel video-panel">
<div class="panel-title">side_2</div>
<video id="video-2" muted playsinline preload="auto"></video>
</section>
<section class="panel">
<div class="panel-title">F_x</div>
<canvas id="chart-0" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">F_y</div>
<canvas id="chart-1" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">F_z</div>
<canvas id="chart-2" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">τ_x</div>
<canvas id="chart-3" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">τ_y</div>
<canvas id="chart-4" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">τ_z</div>
<canvas id="chart-5" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">p_x</div>
<canvas id="chart-pose-0" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">p_y</div>
<canvas id="chart-pose-1" class="chart"></canvas>
</section>
<section class="panel">
<div class="panel-title">p_z</div>
<canvas id="chart-pose-2" class="chart"></canvas>
</section>
</main>
<script>
const $ = (id) => document.getElementById(id);
const TRUTH = '#2563eb';
const views = ['wrist', 'side_1', 'side_2'];
const forceNames = ['F_x','F_y','F_z','tau_x','tau_y','tau_z'];
const poseNames = ['p_x', 'p_y', 'p_z'];
const videos = views.map((_, i) => $('video-' + i));
const forceCharts = forceNames.map((_, i) => $('chart-' + i));
const poseCharts = poseNames.map((_, i) => $('chart-pose-' + i));
const playPause = $('playPause');
const playPauseText = $('playPauseText');
const playIcon = $('play-icon');
const pauseIcon = $('pause-icon');
const timeline = $('timeline');
const timeLabel = $('time-label');
const sourceSelect = $('source');
const resultSelect = $('result');
let data = null;
let currentFrame = 0;
let playing = false;
let rafId = null;
const ONSET_COLOR = '#f97316';
function niceNum(range, round) {
const exp = Math.floor(Math.log10(range));
const fraction = range / Math.pow(10, exp);
let nf;
if (round) {
if (fraction < 1.5) nf = 1;
else if (fraction < 2.25) nf = 2;
else if (fraction < 3.5) nf = 2.5;
else if (fraction < 7) nf = 5;
else nf = 10;
} else {
if (fraction <= 1) nf = 1;
else if (fraction <= 2) nf = 2;
else if (fraction <= 2.5) nf = 2.5;
else if (fraction <= 5) nf = 5;
else nf = 10;
}
return nf * Math.pow(10, exp);
}
function niceTicks(min, max, targetTicks) {
if (!isFinite(min) || !isFinite(max) || min === max) { min = 0; max = 1; }
const range = niceNum(max - min, false);
const step = niceNum(range / Math.max(1, targetTicks - 1), true);
const niceMin = Math.floor(min / step) * step;
const niceMax = Math.ceil(max / step) * step;
return { min: niceMin, max: niceMax, step: step };
}
function tickDecimals(step) {
if (step >= 1) return 0;
let d = 0;
while (d < 6 && Math.abs(step * Math.pow(10, d) - Math.round(step * Math.pow(10, d))) > 1e-9) d++;
return d;
}
function drawLineChart(canvas, truth, pred, frameIndex, title, yRange) {
const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const width = Math.max(200, rect.width);
const height = Math.max(120, rect.height);
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
const ctx = canvas.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const margin = { left: 46, right: 12, top: 14, bottom: 26 };
const plotW = width - margin.left - margin.right;
const plotH = height - margin.top - margin.bottom;
if (plotW <= 10 || plotH <= 10) return;
let minY, maxY, step;
if (yRange) {
minY = yRange.min; maxY = yRange.max; step = yRange.step;
} else {
let lo = Infinity, hi = -Infinity;
for (let i = 0; i < truth.length; i++) {
lo = Math.min(lo, truth[i], pred[i]);
hi = Math.max(hi, truth[i], pred[i]);
}
if (!Number.isFinite(lo) || !Number.isFinite(hi)) { lo = 0; hi = 1; }
const r = niceTicks(lo, hi, 5);
minY = r.min; maxY = r.max; step = r.step;
}
if (maxY === minY) maxY = minY + 1;
const frameCount = data.frame_count;
function xAt(i) { return margin.left + (i / Math.max(1, frameCount - 1)) * plotW; }
function yAt(v) { return margin.top + (1 - (v - minY) / (maxY - minY)) * plotH; }
// Shade frames whose frame_label is 0 (failure/anomaly).
ctx.fillStyle = 'rgba(248, 113, 113, 0.16)';
let failureStart = null;
const visibleEnd = Math.min(frameCount, frameIndex + 1);
for (let i = 0; i <= visibleEnd; i++) {
const failure = i < visibleEnd && Number(data.frame_label[i]) === 0;
if (failure && failureStart === null) failureStart = i;
if ((!failure || i === frameCount) && failureStart !== null) {
const end = i - 1;
ctx.fillRect(xAt(failureStart), margin.top, Math.max(1, xAt(end) - xAt(failureStart)), plotH);
failureStart = null;
}
}
ctx.strokeStyle = '#e5eaf0';
ctx.lineWidth = 1;
ctx.font = '11px "Times New Roman", Times, serif';
ctx.fillStyle = '#7b8a9a';
const decimals = tickDecimals(step);
const tickCount = Math.round((maxY - minY) / step) + 1;
for (let k = 0; k < tickCount; k++) {
const v = minY + k * step;
const y = yAt(v);
ctx.beginPath(); ctx.moveTo(margin.left, y); ctx.lineTo(width - margin.right, y); ctx.stroke();
ctx.textAlign = 'right';
ctx.fillText(v.toFixed(decimals), margin.left - 8, y + 4);
}
// X-axis: horizontal baseline + ticks every 100 frames
const axisY = margin.top + plotH;
const axisColor = '#c3ccd9';
ctx.strokeStyle = axisColor;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(margin.left, axisY);
ctx.lineTo(width - margin.right, axisY);
ctx.stroke();
// Clean open arrowhead on the horizontal axis.
ctx.beginPath();
ctx.moveTo(width - margin.right, axisY);
ctx.lineTo(width - margin.right - 7, axisY - 4);
ctx.moveTo(width - margin.right, axisY);
ctx.lineTo(width - margin.right - 7, axisY + 4);
ctx.stroke();
// Vertical axis with an upward arrow.
ctx.beginPath();
ctx.moveTo(margin.left, axisY);
ctx.lineTo(margin.left, margin.top);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(margin.left, margin.top);
ctx.lineTo(margin.left - 4, margin.top + 7);
ctx.moveTo(margin.left, margin.top);
ctx.lineTo(margin.left + 4, margin.top + 7);
ctx.stroke();
ctx.fillStyle = '#7b8a9a';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
const lastFrame = frameCount - 1;
for (let f = 0; f <= lastFrame; f += 100) {
const x = xAt(f);
ctx.beginPath();
ctx.moveTo(x, axisY);
ctx.lineTo(x, axisY + 4);
ctx.strokeStyle = '#c3ccd9';
ctx.stroke();
ctx.fillText(String(f), x, axisY + 6);
}
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
function drawSeries(values, color) {
ctx.beginPath();
for (let i = 0; i <= frameIndex; i++) {
const x = xAt(i);
const y = yAt(values[i]);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.stroke();
}
drawSeries(truth, TRUTH);
// Interaction onset vertical line (shown once playback passes it)
if (data.interaction_onset != null && frameIndex >= data.interaction_onset) {
const ox = xAt(data.interaction_onset);
ctx.beginPath();
ctx.moveTo(ox, margin.top);
ctx.lineTo(ox, axisY);
ctx.strokeStyle = ONSET_COLOR;
ctx.setLineDash([5, 4]);
ctx.lineWidth = 1.6;
ctx.stroke();
ctx.setLineDash([]);
}
const cx = xAt(frameIndex);
ctx.beginPath();
ctx.moveTo(cx, margin.top);
ctx.lineTo(cx, margin.top + plotH);
ctx.strokeStyle = '#cbd5e1';
ctx.setLineDash([4, 4]);
ctx.lineWidth = 1;
ctx.stroke();
ctx.setLineDash([]);
}
let cachedRanges = null;
function computeSharedRange(indices) {
let lo = Infinity, hi = -Infinity;
for (const i of indices) {
for (const v of data.force_truth[i]) { lo = Math.min(lo, v); hi = Math.max(hi, v); }
}
return niceTicks(lo, hi, 5);
}
function getRanges() {
if (cachedRanges) return cachedRanges;
cachedRanges = {
force: computeSharedRange([0, 1, 2]),
torque: computeSharedRange([3, 4, 5]),
label: { min: 0, max: 1, step: 0.25 },
};
return cachedRanges;
}
function renderCharts(frameIndex) {
if (!data) return;
currentFrame = Math.max(0, Math.min(frameIndex, data.frame_count - 1));
const ranges = getRanges();
for (let i = 0; i < forceCharts.length; i++) {
const r = i < 3 ? ranges.force : ranges.torque;
drawLineChart(forceCharts[i], data.force_truth[i], data.force_truth[i], currentFrame, forceNames[i], r);
}
for (let i = 0; i < poseCharts.length; i++) {
drawLineChart(poseCharts[i], data.position[i], data.position[i], currentFrame, poseNames[i], null);
}
// Invert ground truth for display: success(1)->0, failure(0)->1.
// The public CRIA viewer displays dataset signals only; no model predictions are loaded.
}
function syncVideos() {
const master = videos[0];
if (!master || master.readyState < 1) return;
for (let i = 1; i < videos.length; i++) {
const v = videos[i];
if (v.readyState < 1) continue;
if (Math.abs(v.currentTime - master.currentTime) > 0.08) {
v.currentTime = master.currentTime;
}
}
}
function loop() {
if (!playing) return;
const master = videos[0];
if (master && master.readyState >= 1) {
const frame = Math.floor(master.currentTime * data.fps);
if (frame !== currentFrame) renderCharts(frame);
syncVideos();
updateTimelineFromVideo();
}
rafId = requestAnimationFrame(loop);
}
function playAll() {
for (const v of videos) {
const p = v.play();
if (p && p.catch) p.catch(() => {});
}
playing = true;
playPauseText.textContent = 'Pause';
playIcon.style.display = 'none';
pauseIcon.style.display = 'block';
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(loop);
}
function pauseAll() {
playing = false;
cancelAnimationFrame(rafId);
for (const v of videos) v.pause();
playPauseText.textContent = 'Play';
playIcon.style.display = 'block';
pauseIcon.style.display = 'none';
}
function formatFramesLabel(currentFrameIdx, totalFrames) {
return `frame ${currentFrameIdx} / ${totalFrames}`;
}
function updateTimelineFromVideo() {
const master = videos[0];
if (!master || master.readyState < 1 || !Number.isFinite(master.duration)) return;
if (document.activeElement !== timeline) {
timeline.value = master.currentTime;
}
const progress = master.duration ? (master.currentTime / master.duration) * 100 : 0;
timeline.style.setProperty('--range-progress', `${progress}%`);
const cur = Math.max(0, Math.min(Math.floor(master.currentTime * data.fps), data.frame_count - 1));
timeLabel.textContent = formatFramesLabel(cur, data.frame_count - 1);
}
function seekTo(value) {
if (!data) return;
const master = videos[0];
const t = Math.max(0, Math.min(Number(value), master.duration || value));
for (const v of videos) {
if (v.readyState >= 1) v.currentTime = t;
}
const progress = master.duration ? (t / master.duration) * 100 : 0;
timeline.style.setProperty('--range-progress', `${progress}%`);
const frameIdx = Math.max(0, Math.min(Math.floor(t * data.fps), data.frame_count - 1));
renderCharts(frameIdx);
timeLabel.textContent = formatFramesLabel(frameIdx, data.frame_count - 1);
}
async function loadOptions() {
const resp = await fetch('/api/options');
const payload = await resp.json();
const category = $('category');
category.innerHTML = '';
for (const item of payload.categories) {
const opt = document.createElement('option');
opt.value = item.name;
opt.textContent = item.name;
category.appendChild(opt);
}
updateTasks();
}
function updateTasks() {
const category = $('category').value;
const task = $('task');
task.innerHTML = '';
// The next call to /api/options is intentionally simple and cheap.
fetch('/api/options').then((r) => r.json()).then((payload) => {
const item = payload.categories.find((c) => c.name === category);
if (!item) return;
for (const name of item.tasks) {
const opt = document.createElement('option');
opt.value = name;
opt.textContent = name;
task.appendChild(opt);
}
updateEpisodes();
});
}
let episodeRecords = [];
function updateEpisodes() {
const category = $('category').value;
const task = $('task').value;
const episodeSelect = $('episode');
episodeSelect.innerHTML = '';
episodeRecords = [];
if (!task) return;
const source = sourceSelect.value;
const result = resultSelect.value;
fetch(`/api/episodes?category=${encodeURIComponent(category)}&task=${encodeURIComponent(task)}&source=${encodeURIComponent(source)}&result=${encodeURIComponent(result)}`)
.then((r) => r.json())
.then((payload) => {
episodeRecords = Array.isArray(payload.episodes) ? payload.episodes : [];
episodeRecords.forEach((record) => {
const opt = document.createElement('option');
opt.value = String(record.episode_index);
opt.textContent = `${record.source || 'unknown'}_${Number(record.episode_label) === 1 ? 'success' : 'failure'}_${String(record.episode_index).padStart(6, '0')}`;
episodeSelect.appendChild(opt);
});
if (episodeRecords.length) loadData();
})
.catch(() => {});
}
async function loadData() {
pauseAll();
const category = $('category').value;
const task = $('task').value;
const episode = $('episode').value;
const resp = await fetch(`/api/data?category=${encodeURIComponent(category)}&task=${encodeURIComponent(task)}&episode=${encodeURIComponent(episode)}`);
if (!resp.ok) {
alert(await resp.text());
return;
}
data = await resp.json();
cachedRanges = null;
currentFrame = 0;
for (let i = 0; i < views.length; i++) {
videos[i].src = data.videos[views[i]];
videos[i].load();
}
videos[0].addEventListener('loadedmetadata', () => {
timeline.max = videos[0].duration || 0;
renderCharts(0);
playPause.disabled = false;
}, { once: true });
renderCharts(0);
timeline.value = 0;
timeline.style.setProperty('--range-progress', '0%');
timeLabel.textContent = formatFramesLabel(0, data.frame_count - 1);
playPause.disabled = false;
}
$('category').addEventListener('change', updateTasks);
$('task').addEventListener('change', updateEpisodes);
sourceSelect.addEventListener('change', updateEpisodes);
resultSelect.addEventListener('change', updateEpisodes);
$('load').addEventListener('click', loadData);
playPause.addEventListener('click', () => playing ? pauseAll() : playAll());
timeline.addEventListener('input', () => seekTo(timeline.value));
document.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
loadData();
} else if (event.code === 'Space' && !['SELECT', 'INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) {
event.preventDefault();
playing ? pauseAll() : playAll();
}
});
window.addEventListener('resize', () => renderCharts(currentFrame));
loadOptions();
</script>
</body>
</html>
"""
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()