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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
LeRobot Dataset Visualizer — Web Dashboard
|
| 4 |
+
运行: python visualize_dataset.py -d <dataset_folder>
|
| 5 |
+
浏览器访问 http://localhost:7777
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import sys, json, argparse, base64, threading, webbrowser, time
|
| 9 |
+
from urllib.parse import urlparse, parse_qs
|
| 10 |
+
from http.server import HTTPServer, BaseHTTPRequestHandler
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from scipy.ndimage import median_filter as _scipy_medfilt
|
| 14 |
+
from scipy.ndimage import gaussian_filter as _scipy_gauss
|
| 15 |
+
_HAS_SCIPY = True
|
| 16 |
+
except ImportError:
|
| 17 |
+
_HAS_SCIPY = False
|
| 18 |
+
|
| 19 |
+
def _filter_tactile(vals, shape):
|
| 20 |
+
"""
|
| 21 |
+
两步滤波:
|
| 22 |
+
1. 两遍 3×3 中值滤波:彻底消除孤立单点和双点噪声(数学保证:孤立点被邻域中值替换)。
|
| 23 |
+
2. 轻度高斯平滑(sigma=0.7)。
|
| 24 |
+
"""
|
| 25 |
+
if not _HAS_SCIPY or not vals:
|
| 26 |
+
return vals
|
| 27 |
+
try:
|
| 28 |
+
arr = np.array(vals, dtype=np.float32).reshape(shape)
|
| 29 |
+
# 两遍中值滤波:第一遍消单点,第二遍消残余双点
|
| 30 |
+
arr = _scipy_medfilt(arr, size=3, mode='nearest')
|
| 31 |
+
arr = _scipy_medfilt(arr, size=3, mode='nearest')
|
| 32 |
+
# 高斯平滑
|
| 33 |
+
arr = _scipy_gauss(arr, sigma=0.7, mode='nearest')
|
| 34 |
+
return arr.flatten().tolist()
|
| 35 |
+
except Exception:
|
| 36 |
+
return vals
|
| 37 |
+
from pathlib import Path
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
import pyarrow as pa
|
| 42 |
+
import pyarrow.parquet as pq
|
| 43 |
+
except ImportError:
|
| 44 |
+
sys.exit("缺少 pyarrow")
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
import cv2
|
| 48 |
+
_HAS_CV2 = True
|
| 49 |
+
except ImportError:
|
| 50 |
+
_HAS_CV2 = False
|
| 51 |
+
|
| 52 |
+
PORT = 7777
|
| 53 |
+
_DS = None
|
| 54 |
+
|
| 55 |
+
# 触觉传感器分组(基于 id 映射表)
|
| 56 |
+
# 拇指 3 片(0-2);食/中/无名/小指各 4 片(指尖→中→尾→掌内关节);掌心 1 片(19)
|
| 57 |
+
SENSOR_GROUPS = [
|
| 58 |
+
{"id":"thumb", "label":"拇指", "color":"#ff6b6b", "type":"finger",
|
| 59 |
+
"sensors":["tactile_0","tactile_1","tactile_2"]},
|
| 60 |
+
{"id":"index", "label":"食指", "color":"#ffd93d", "type":"finger",
|
| 61 |
+
"sensors":["tactile_3","tactile_4","tactile_5","tactile_6"]},
|
| 62 |
+
{"id":"middle", "label":"中指", "color":"#6bcb77", "type":"finger",
|
| 63 |
+
"sensors":["tactile_7","tactile_8","tactile_9","tactile_10"]},
|
| 64 |
+
{"id":"ring", "label":"无名", "color":"#4d96ff", "type":"finger",
|
| 65 |
+
"sensors":["tactile_11","tactile_12","tactile_13","tactile_14"]},
|
| 66 |
+
{"id":"pinky", "label":"小指", "color":"#c77dff", "type":"finger",
|
| 67 |
+
"sensors":["tactile_15","tactile_16","tactile_17","tactile_18"]},
|
| 68 |
+
{"id":"palm", "label":"掌心", "color":"#9ecbff", "type":"palm",
|
| 69 |
+
"sensors":["tactile_19"]},
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 74 |
+
class DataServer:
|
| 75 |
+
def __init__(self, root: str):
|
| 76 |
+
self.root = Path(root)
|
| 77 |
+
self._load_info(); self._load_episodes()
|
| 78 |
+
self._load_frames(); self._load_tasks(); self._load_cmap()
|
| 79 |
+
self._compute_tactile_baselines()
|
| 80 |
+
|
| 81 |
+
def _load_info(self):
|
| 82 |
+
with open(self.root/"meta"/"info.json", encoding="utf-8") as f:
|
| 83 |
+
self.info = json.load(f)
|
| 84 |
+
self.fps = self.info["fps"]
|
| 85 |
+
self.tactile_2d_shapes = self.info.get("tactile_2d_shapes", {})
|
| 86 |
+
print(f"OK {self.root.name} fps={self.fps} frames={self.info['total_frames']}")
|
| 87 |
+
|
| 88 |
+
def _load_episodes(self):
|
| 89 |
+
files = sorted((self.root/"meta"/"episodes").rglob("*.parquet"))
|
| 90 |
+
ep_dict = pa.concat_tables([pq.read_table(f) for f in files]).to_pydict()
|
| 91 |
+
n = len(ep_dict["episode_index"])
|
| 92 |
+
self.episodes = [{k: ep_dict[k][i] for k in ep_dict} for i in range(n)]
|
| 93 |
+
self.n_episodes = n
|
| 94 |
+
|
| 95 |
+
def _load_frames(self):
|
| 96 |
+
files = sorted((self.root/"data").rglob("*.parquet"))
|
| 97 |
+
fd = pa.concat_tables([pq.read_table(f) for f in files]).to_pydict()
|
| 98 |
+
self.frame_dict = fd
|
| 99 |
+
self._idx_map = {int(v): i for i, v in enumerate(fd["index"])}
|
| 100 |
+
|
| 101 |
+
def _load_tasks(self):
|
| 102 |
+
try:
|
| 103 |
+
tp = next((self.root/"meta").rglob("tasks.parquet"), None)
|
| 104 |
+
self.task_desc = pq.read_table(tp).to_pydict().get("task",["Unknown"])[0] if tp else "Unknown"
|
| 105 |
+
except Exception:
|
| 106 |
+
self.task_desc = "Unknown"
|
| 107 |
+
|
| 108 |
+
def _load_cmap(self):
|
| 109 |
+
cfg = (self.root.parent.parent /
|
| 110 |
+
"hand"/"Usb_API_stable_Tujian_"/"spliter"/"config_mapping_zyhand.json")
|
| 111 |
+
if cfg.exists():
|
| 112 |
+
with open(cfg, encoding='utf-8') as f:
|
| 113 |
+
data = json.load(f)
|
| 114 |
+
self.cmap_colors = [
|
| 115 |
+
f"#{int(c[0]*255):02x}{int(c[1]*255):02x}{int(c[2]*255):02x}"
|
| 116 |
+
for c in data["color_map"]]
|
| 117 |
+
else:
|
| 118 |
+
self.cmap_colors = [
|
| 119 |
+
"#262626","#0a2a5e","#0d4f8b","#0d7ab5","#18a0c8",
|
| 120 |
+
"#1dc9d0","#22e0be","#39e87d","#8aef3f","#d4e830",
|
| 121 |
+
"#f0c020","#f0901a","#e05015","#c02510","#8b0d08","#5e0505","#3d0202"]
|
| 122 |
+
|
| 123 |
+
def _compute_tactile_baselines(self):
|
| 124 |
+
"""每个 episode 前 10 帧取均值作为触觉零点基准。"""
|
| 125 |
+
self.tactile_baselines = {}
|
| 126 |
+
for ep_id, ep in enumerate(self.episodes):
|
| 127 |
+
start = int(ep["dataset_from_index"])
|
| 128 |
+
end = int(ep["dataset_to_index"]) - 1
|
| 129 |
+
sums, count = {}, 0
|
| 130 |
+
for fidx in range(start, min(start + 10, end + 1)):
|
| 131 |
+
i = self._idx_map.get(fidx)
|
| 132 |
+
if i is None:
|
| 133 |
+
continue
|
| 134 |
+
for key in self.tactile_2d_shapes:
|
| 135 |
+
raw = self.frame_dict.get(f"tactile_{key}")
|
| 136 |
+
if raw is None or i >= len(raw) or raw[i] is None:
|
| 137 |
+
continue
|
| 138 |
+
arr = [float(v) for v in raw[i]]
|
| 139 |
+
if key not in sums:
|
| 140 |
+
sums[key] = [0.0] * len(arr)
|
| 141 |
+
for j, v in enumerate(arr):
|
| 142 |
+
sums[key][j] += v
|
| 143 |
+
count += 1
|
| 144 |
+
self.tactile_baselines[ep_id] = (
|
| 145 |
+
{k: [v / count for v in sums[k]] for k in sums} if count else {}
|
| 146 |
+
)
|
| 147 |
+
print(f"触觉基准已计算 episodes={len(self.tactile_baselines)}")
|
| 148 |
+
|
| 149 |
+
def get_tactile_timeline(self, ep_id: int) -> dict:
|
| 150 |
+
ep = self.episodes[ep_id]
|
| 151 |
+
start = int(ep["dataset_from_index"])
|
| 152 |
+
end = int(ep["dataset_to_index"]) - 1
|
| 153 |
+
baseline = self.tactile_baselines.get(ep_id, {})
|
| 154 |
+
sensors_data = []
|
| 155 |
+
for grp in SENSOR_GROUPS:
|
| 156 |
+
for sensor_key in grp["sensors"]:
|
| 157 |
+
# parquet列名是 "tactile_tactile_0",sensor_key是 "tactile_0"
|
| 158 |
+
col_key = f"tactile_{sensor_key}"
|
| 159 |
+
sums = []
|
| 160 |
+
for fidx in range(start, end + 1):
|
| 161 |
+
i = self._idx_map.get(fidx)
|
| 162 |
+
if i is None:
|
| 163 |
+
sums.append(0.0); continue
|
| 164 |
+
raw_col = self.frame_dict.get(col_key)
|
| 165 |
+
if raw_col is None or i >= len(raw_col) or raw_col[i] is None:
|
| 166 |
+
sums.append(0.0); continue
|
| 167 |
+
base = baseline.get(sensor_key, [])
|
| 168 |
+
vals = [float(v) for v in raw_col[i]]
|
| 169 |
+
if base:
|
| 170 |
+
vals = [max(0.0, v - b) for v, b in zip(vals, base)]
|
| 171 |
+
shape = self.tactile_2d_shapes.get(sensor_key)
|
| 172 |
+
if shape:
|
| 173 |
+
vals = _filter_tactile(vals, shape)
|
| 174 |
+
sums.append(round(sum(vals), 2))
|
| 175 |
+
sensors_data.append({
|
| 176 |
+
"key": sensor_key,
|
| 177 |
+
"color": grp["color"],
|
| 178 |
+
"sums": sums,
|
| 179 |
+
})
|
| 180 |
+
return {"sensors": sensors_data, "n_frames": end - start + 1, "start": start}
|
| 181 |
+
|
| 182 |
+
def get_frame(self, idx: int) -> dict:
|
| 183 |
+
i = self._idx_map.get(idx, idx)
|
| 184 |
+
return {k: self.frame_dict[k][i] for k in self.frame_dict}
|
| 185 |
+
|
| 186 |
+
def get_video_frame_b64(self, ep_idx, frame_in_ep, stream):
|
| 187 |
+
if not _HAS_CV2: return None
|
| 188 |
+
ep = self.episodes[ep_idx]
|
| 189 |
+
vk = f"observation.images.{stream}"
|
| 190 |
+
chunk = int(ep.get(f"videos/{vk}/chunk_index", 0))
|
| 191 |
+
fidx = int(ep.get(f"videos/{vk}/file_index", 0))
|
| 192 |
+
from_ts = float(ep.get(f"videos/{vk}/from_timestamp", 0.0))
|
| 193 |
+
vpath = (self.root/f"videos/{vk}/chunk-{chunk:03d}/file-{fidx:04d}.mp4")
|
| 194 |
+
if not vpath.exists(): return None
|
| 195 |
+
cap = cv2.VideoCapture(str(vpath))
|
| 196 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(from_ts*self.fps)) + frame_in_ep)
|
| 197 |
+
ret, frame = cap.read(); cap.release()
|
| 198 |
+
if not ret: return None
|
| 199 |
+
if stream == "depth":
|
| 200 |
+
r, g, b = frame[:,:,2], frame[:,:,1], frame[:,:,0]
|
| 201 |
+
if np.abs(r.astype(int)-g.astype(int)).mean() < 4:
|
| 202 |
+
frame = cv2.applyColorMap(r, cv2.COLORMAP_TURBO)
|
| 203 |
+
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
|
| 204 |
+
return base64.b64encode(buf).decode()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 208 |
+
class Handler(BaseHTTPRequestHandler):
|
| 209 |
+
def log_message(self, *_): pass
|
| 210 |
+
|
| 211 |
+
def _json(self, data):
|
| 212 |
+
body = json.dumps(data, ensure_ascii=False).encode()
|
| 213 |
+
self.send_response(200)
|
| 214 |
+
self.send_header("Content-Type", "application/json")
|
| 215 |
+
self.send_header("Access-Control-Allow-Origin", "*")
|
| 216 |
+
self.end_headers()
|
| 217 |
+
self.wfile.write(body)
|
| 218 |
+
|
| 219 |
+
def _html(self, body):
|
| 220 |
+
enc = body.encode()
|
| 221 |
+
self.send_response(200)
|
| 222 |
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
| 223 |
+
self.end_headers()
|
| 224 |
+
self.wfile.write(enc)
|
| 225 |
+
|
| 226 |
+
def do_GET(self):
|
| 227 |
+
ds = _DS
|
| 228 |
+
url = urlparse(self.path)
|
| 229 |
+
qs = parse_qs(url.query)
|
| 230 |
+
|
| 231 |
+
if url.path == "/":
|
| 232 |
+
self._html(build_html(ds))
|
| 233 |
+
|
| 234 |
+
elif url.path == "/api/meta":
|
| 235 |
+
self._json({
|
| 236 |
+
"name": ds.root.name, "fps": ds.fps,
|
| 237 |
+
"n_episodes": ds.n_episodes, "task": ds.task_desc,
|
| 238 |
+
"tactile_2d_shapes": ds.tactile_2d_shapes,
|
| 239 |
+
"cmap_colors": ds.cmap_colors,
|
| 240 |
+
"sensor_groups": SENSOR_GROUPS,
|
| 241 |
+
"episodes": [{"start": int(ep["dataset_from_index"]),
|
| 242 |
+
"end": int(ep["dataset_to_index"]) - 1,
|
| 243 |
+
"length":int(ep["length"]),
|
| 244 |
+
"task": (ep.get("tasks") or ["—"])[0]}
|
| 245 |
+
for ep in ds.episodes],
|
| 246 |
+
})
|
| 247 |
+
|
| 248 |
+
elif url.path == "/api/frame":
|
| 249 |
+
n = int(qs.get("n", [0])[0])
|
| 250 |
+
ep = int(qs.get("ep", [0])[0])
|
| 251 |
+
d = ds.get_frame(n)
|
| 252 |
+
pos = d.get("observation_motion_positions", [])
|
| 253 |
+
quat = d.get("observation_motion_quaternions", [])
|
| 254 |
+
tactile = {}
|
| 255 |
+
baseline = ds.tactile_baselines.get(ep, {})
|
| 256 |
+
for key in ds.tactile_2d_shapes:
|
| 257 |
+
raw = d.get(f"tactile_{key}")
|
| 258 |
+
if raw is not None:
|
| 259 |
+
base = baseline.get(key, [])
|
| 260 |
+
if base:
|
| 261 |
+
vals = [max(0.0, float(v) - b) for v, b in zip(raw, base)]
|
| 262 |
+
else:
|
| 263 |
+
vals = [float(v) for v in raw]
|
| 264 |
+
tactile[key] = _filter_tactile(vals, ds.tactile_2d_shapes[key])
|
| 265 |
+
self._json({
|
| 266 |
+
"timestamp": float(d.get("timestamp", 0)),
|
| 267 |
+
"positions": [float(v) for v in pos] if pos else [],
|
| 268 |
+
"quaternions": [float(v) for v in quat] if quat else [],
|
| 269 |
+
"tactile": tactile,
|
| 270 |
+
})
|
| 271 |
+
|
| 272 |
+
elif url.path == "/api/tactile_timeline":
|
| 273 |
+
ep = int(qs.get("ep", [0])[0])
|
| 274 |
+
self._json(ds.get_tactile_timeline(ep))
|
| 275 |
+
|
| 276 |
+
elif url.path == "/api/image":
|
| 277 |
+
ep = int(qs.get("ep", [0])[0])
|
| 278 |
+
f = int(qs.get("f", [0])[0])
|
| 279 |
+
typ = qs.get("type", ["color"])[0]
|
| 280 |
+
self._json({"data": ds.get_video_frame_b64(ep, f, typ)})
|
| 281 |
+
|
| 282 |
+
else:
|
| 283 |
+
self.send_response(404); self.end_headers()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 287 |
+
def build_html(ds: DataServer) -> str:
|
| 288 |
+
return r"""<!DOCTYPE html>
|
| 289 |
+
<html lang="zh">
|
| 290 |
+
<head>
|
| 291 |
+
<meta charset="UTF-8">
|
| 292 |
+
<title>LeRobot Dataset Visualizer</title>
|
| 293 |
+
<style>
|
| 294 |
+
*{box-sizing:border-box;margin:0;padding:0}
|
| 295 |
+
:root{
|
| 296 |
+
--bg:#0d1117;--panel:#161b22;--border:#30363d;
|
| 297 |
+
--text:#e6edf3;--dim:#8b949e;--accent:#58a6ff;--hdr:#0e1520;
|
| 298 |
+
--r:10px;--gap:12px;
|
| 299 |
+
}
|
| 300 |
+
body{background:var(--bg);color:var(--text);
|
| 301 |
+
font-family:'Segoe UI',system-ui,sans-serif;font-size:13px;
|
| 302 |
+
height:100vh;display:flex;flex-direction:column;overflow:hidden}
|
| 303 |
+
|
| 304 |
+
/* ── Header ─────────────────────────────────────────────────────── */
|
| 305 |
+
#hdr{
|
| 306 |
+
background:var(--hdr);border-bottom:1px solid var(--border);
|
| 307 |
+
padding:0 18px;height:50px;display:flex;align-items:center;
|
| 308 |
+
gap:14px;flex-shrink:0;
|
| 309 |
+
}
|
| 310 |
+
.logo{font-size:12px;font-weight:700;color:var(--accent);
|
| 311 |
+
white-space:nowrap;letter-spacing:.04em}
|
| 312 |
+
#ep-ctrl{display:flex;align-items:center;gap:6px}
|
| 313 |
+
.ep-btn{
|
| 314 |
+
background:#21262d;border:1px solid var(--border);color:var(--text);
|
| 315 |
+
border-radius:6px;padding:3px 10px;cursor:pointer;font-size:13px;
|
| 316 |
+
line-height:1;transition:background .12s;
|
| 317 |
+
}
|
| 318 |
+
.ep-btn:hover{background:#2d333b}
|
| 319 |
+
#ep-select{
|
| 320 |
+
background:#21262d;border:1px solid var(--border);color:var(--text);
|
| 321 |
+
border-radius:6px;padding:3px 8px;font-size:12px;cursor:pointer;
|
| 322 |
+
outline:none;min-width:200px;
|
| 323 |
+
}
|
| 324 |
+
#ep-select:focus{border-color:var(--accent)}
|
| 325 |
+
.chip{
|
| 326 |
+
background:#161b22;border:1px solid var(--border);border-radius:20px;
|
| 327 |
+
padding:2px 10px;font-size:11px;color:var(--dim);white-space:nowrap;
|
| 328 |
+
}
|
| 329 |
+
.hdr-r{margin-left:auto;display:flex;align-items:center;gap:8px}
|
| 330 |
+
#play-btn{
|
| 331 |
+
background:var(--accent);color:#000;border:none;border-radius:6px;
|
| 332 |
+
padding:4px 13px;cursor:pointer;font-weight:700;font-size:12px;
|
| 333 |
+
}
|
| 334 |
+
#play-btn:hover{opacity:.85}
|
| 335 |
+
|
| 336 |
+
/* ── Main 2×2 ───────────────────────────────────────────────────── */
|
| 337 |
+
#main{
|
| 338 |
+
flex:1;display:grid;
|
| 339 |
+
grid-template-columns:1fr 1fr;
|
| 340 |
+
grid-template-rows:1fr 1fr;
|
| 341 |
+
gap:var(--gap);padding:var(--gap);min-height:0;
|
| 342 |
+
}
|
| 343 |
+
.panel{
|
| 344 |
+
background:var(--panel);border:1px solid var(--border);
|
| 345 |
+
border-radius:var(--r);display:flex;flex-direction:column;
|
| 346 |
+
overflow:hidden;min-height:0;
|
| 347 |
+
}
|
| 348 |
+
.ph{
|
| 349 |
+
padding:7px 13px;border-bottom:1px solid var(--border);
|
| 350 |
+
display:flex;align-items:center;gap:8px;flex-shrink:0;
|
| 351 |
+
}
|
| 352 |
+
.ph .pt{font-weight:600;font-size:11px;letter-spacing:.05em;text-transform:uppercase}
|
| 353 |
+
.ph .pd{font-size:10px;color:var(--dim);margin-left:auto}
|
| 354 |
+
.pb{flex:1;display:flex;align-items:center;justify-content:center;
|
| 355 |
+
overflow:hidden;position:relative;min-height:0}
|
| 356 |
+
.pb img{max-width:100%;max-height:100%;object-fit:contain}
|
| 357 |
+
|
| 358 |
+
/* ── Skeleton ────────────────────────────────────────────────────── */
|
| 359 |
+
#svg-skel{width:100%;height:100%}
|
| 360 |
+
|
| 361 |
+
/* ── Tactile ─────────────────────────────────────────────────────── */
|
| 362 |
+
#tac-scroll{
|
| 363 |
+
width:100%;height:100%;overflow:auto;
|
| 364 |
+
display:flex;align-items:center;justify-content:center;padding:10px 8px;
|
| 365 |
+
}
|
| 366 |
+
#tac-root{display:flex;flex-direction:column;align-items:center;gap:14px}
|
| 367 |
+
|
| 368 |
+
/* Fingers: bottom-aligned row */
|
| 369 |
+
#tac-fingers{
|
| 370 |
+
display:flex;flex-direction:row;
|
| 371 |
+
align-items:flex-end; /* 指根底部对齐 */
|
| 372 |
+
gap:18px;
|
| 373 |
+
}
|
| 374 |
+
.fg{display:flex;flex-direction:column;align-items:center;gap:0}
|
| 375 |
+
.fg-label{
|
| 376 |
+
font-size:9px;font-weight:700;text-transform:uppercase;
|
| 377 |
+
letter-spacing:.08em;margin-bottom:6px;opacity:.85;
|
| 378 |
+
}
|
| 379 |
+
.fg-sensors{display:flex;flex-direction:column;align-items:center;gap:3px}
|
| 380 |
+
|
| 381 |
+
/* Palm: horizontal row */
|
| 382 |
+
#tac-palm-wrap{display:flex;flex-direction:column;align-items:center;gap:6px}
|
| 383 |
+
#tac-palm-label{
|
| 384 |
+
font-size:9px;font-weight:700;text-transform:uppercase;
|
| 385 |
+
letter-spacing:.08em;color:#9ecbff;opacity:.85;
|
| 386 |
+
}
|
| 387 |
+
#tac-palm{display:flex;flex-direction:row;align-items:flex-end;gap:12px}
|
| 388 |
+
|
| 389 |
+
/* sensor card */
|
| 390 |
+
.sc{display:flex;flex-direction:column;align-items:center;gap:1px}
|
| 391 |
+
.sn{font-size:8px;color:var(--dim);line-height:1.2}
|
| 392 |
+
.ss{font-size:8px;color:var(--text);line-height:1.2}
|
| 393 |
+
canvas.tc{display:block;border-radius:2px}
|
| 394 |
+
|
| 395 |
+
/* section divider */
|
| 396 |
+
.sec-div{
|
| 397 |
+
width:100%;border-top:1px solid var(--border);
|
| 398 |
+
display:flex;align-items:center;gap:8px;
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
/* ── Task bar ────────────────────────────────────────────────────── */
|
| 402 |
+
#task-bar{
|
| 403 |
+
background:#0c1625;border-bottom:1px solid var(--border);
|
| 404 |
+
padding:0 18px;height:38px;display:flex;align-items:center;
|
| 405 |
+
gap:14px;flex-shrink:0;overflow:hidden;
|
| 406 |
+
}
|
| 407 |
+
#task-bar-ep{font-size:11px;color:var(--dim);white-space:nowrap;min-width:64px}
|
| 408 |
+
#task-bar-text{
|
| 409 |
+
font-size:15px;font-weight:600;color:#c77dff;
|
| 410 |
+
white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
/* ── Tactile timeline canvas ─────────────────────────────────────── */
|
| 414 |
+
#tl-pb{overflow:hidden}
|
| 415 |
+
#tac-timeline{display:block}
|
| 416 |
+
|
| 417 |
+
/* ── Footer ──────────────────────────────────────────────────────── */
|
| 418 |
+
#ftr{
|
| 419 |
+
background:var(--hdr);border-top:1px solid var(--border);
|
| 420 |
+
padding:7px 18px;display:flex;align-items:center;gap:12px;flex-shrink:0;
|
| 421 |
+
}
|
| 422 |
+
#slider{flex:1;accent-color:var(--accent);cursor:pointer}
|
| 423 |
+
#ts-lbl{color:var(--dim);font-size:11px;white-space:nowrap;min-width:90px}
|
| 424 |
+
#fr-lbl{color:var(--dim);font-size:11px;white-space:nowrap;min-width:110px;text-align:right}
|
| 425 |
+
</style>
|
| 426 |
+
</head>
|
| 427 |
+
<body>
|
| 428 |
+
|
| 429 |
+
<!-- Header -->
|
| 430 |
+
<div id="hdr">
|
| 431 |
+
<div class="logo">LeRobot Visualizer</div>
|
| 432 |
+
|
| 433 |
+
<div id="ep-ctrl">
|
| 434 |
+
<button class="ep-btn" id="btn-prev">◀</button>
|
| 435 |
+
<select id="ep-select"></select>
|
| 436 |
+
<button class="ep-btn" id="btn-next">▶</button>
|
| 437 |
+
</div>
|
| 438 |
+
|
| 439 |
+
<div class="hdr-r">
|
| 440 |
+
<span class="chip" id="c-ds">—</span>
|
| 441 |
+
<span class="chip" id="c-eps">—</span>
|
| 442 |
+
<span class="chip" id="c-fps">—</span>
|
| 443 |
+
<button id="play-btn">▶ Play</button>
|
| 444 |
+
</div>
|
| 445 |
+
</div>
|
| 446 |
+
|
| 447 |
+
<!-- Task bar -->
|
| 448 |
+
<div id="task-bar">
|
| 449 |
+
<span id="task-bar-ep">Ep 0</span>
|
| 450 |
+
<span style="font-size:11px;color:var(--dim);white-space:nowrap">Description:</span>
|
| 451 |
+
<span id="task-bar-text">—</span>
|
| 452 |
+
</div>
|
| 453 |
+
|
| 454 |
+
<!-- Main 2×2 -->
|
| 455 |
+
<div id="main">
|
| 456 |
+
<!-- TL: Color -->
|
| 457 |
+
<div class="panel">
|
| 458 |
+
<div class="ph">
|
| 459 |
+
<span class="pt" style="color:#9ecbff">Color</span>
|
| 460 |
+
<span class="pd" id="pd-color">—</span>
|
| 461 |
+
</div>
|
| 462 |
+
<div class="pb"><img id="img-color" alt=""></div>
|
| 463 |
+
</div>
|
| 464 |
+
|
| 465 |
+
<!-- TR: Skeleton -->
|
| 466 |
+
<div class="panel">
|
| 467 |
+
<div class="ph">
|
| 468 |
+
<span class="pt" style="color:#e6edf3">Motion Skeleton</span>
|
| 469 |
+
<span class="pd" id="pd-skel">20 markers · 5 fingers</span>
|
| 470 |
+
</div>
|
| 471 |
+
<div class="pb">
|
| 472 |
+
<svg id="svg-skel" viewBox="-200 -200 400 400"
|
| 473 |
+
xmlns="http://www.w3.org/2000/svg"></svg>
|
| 474 |
+
</div>
|
| 475 |
+
</div>
|
| 476 |
+
|
| 477 |
+
<!-- BL: Tactile Timeline -->
|
| 478 |
+
<div class="panel">
|
| 479 |
+
<div class="ph">
|
| 480 |
+
<span class="pt" style="color:#c77dff">Tactile Timeline</span>
|
| 481 |
+
<span class="pd" id="pd-timeline">—</span>
|
| 482 |
+
</div>
|
| 483 |
+
<div class="pb" id="tl-pb" style="display:block;padding:0">
|
| 484 |
+
<canvas id="tac-timeline" style="display:block"></canvas>
|
| 485 |
+
</div>
|
| 486 |
+
</div>
|
| 487 |
+
|
| 488 |
+
<!-- BR: Tactile -->
|
| 489 |
+
<div class="panel">
|
| 490 |
+
<div class="ph">
|
| 491 |
+
<span class="pt" style="color:#6bcb77">Tactile</span>
|
| 492 |
+
<span class="pd" id="pd-tac">—</span>
|
| 493 |
+
</div>
|
| 494 |
+
<div class="pb">
|
| 495 |
+
<div id="tac-scroll">
|
| 496 |
+
<div id="tac-root">
|
| 497 |
+
<!-- Fingers row -->
|
| 498 |
+
<div id="tac-fingers"></div>
|
| 499 |
+
<!-- divider -->
|
| 500 |
+
<div class="sec-div"></div>
|
| 501 |
+
<!-- Palm row -->
|
| 502 |
+
<div id="tac-palm-wrap">
|
| 503 |
+
<div id="tac-palm-label">Palm</div>
|
| 504 |
+
<div id="tac-palm"></div>
|
| 505 |
+
</div>
|
| 506 |
+
</div>
|
| 507 |
+
</div>
|
| 508 |
+
</div>
|
| 509 |
+
</div>
|
| 510 |
+
</div>
|
| 511 |
+
|
| 512 |
+
<!-- Footer -->
|
| 513 |
+
<div id="ftr">
|
| 514 |
+
<span id="ts-lbl">t = 0.000 s</span>
|
| 515 |
+
<input type="range" id="slider" min="0" max="0" value="0">
|
| 516 |
+
<span id="fr-lbl">Frame 0 / 0</span>
|
| 517 |
+
</div>
|
| 518 |
+
|
| 519 |
+
<script>
|
| 520 |
+
// ── State ──────────────────────────────────────────────────────────────────
|
| 521 |
+
let META=null, curEp=0, curFrame=0, playing=false, playTimer=null;
|
| 522 |
+
let skelScale=null, skelCenter=null; // fixed from first frame of each episode
|
| 523 |
+
let TIMELINE=null; // tactile timeline for current episode
|
| 524 |
+
|
| 525 |
+
// ── Colormap ───────────────────────────────────────────────────────────────
|
| 526 |
+
let CMAP=[];
|
| 527 |
+
function cmapRGB(t){
|
| 528 |
+
const n=CMAP.length-1, fi=t*n;
|
| 529 |
+
const lo=Math.floor(fi), hi=Math.min(lo+1,n), f=fi-lo;
|
| 530 |
+
const p=h=>[parseInt(h.slice(1,3),16),parseInt(h.slice(3,5),16),parseInt(h.slice(5,7),16)];
|
| 531 |
+
const [r0,g0,b0]=p(CMAP[lo]), [r1,g1,b1]=p(CMAP[hi]);
|
| 532 |
+
return [r0+(r1-r0)*f, g0+(g1-g0)*f, b0+(b1-b0)*f];
|
| 533 |
+
}
|
| 534 |
+
|
| 535 |
+
// ── Tactile canvas map ─────────────────────────────────────────────────────
|
| 536 |
+
const cvMap={}, sumMap={};
|
| 537 |
+
const PX=9; // pixels per tactile point (fixed → equal-sized squares)
|
| 538 |
+
|
| 539 |
+
const TAC_NAMES={
|
| 540 |
+
'tactile_0':'拇指尖','tactile_1':'拇指中','tactile_2':'拇指根',
|
| 541 |
+
'tactile_3':'食指尖','tactile_4':'食指中','tactile_5':'食指根','tactile_6':'食指掌',
|
| 542 |
+
'tactile_7':'中指尖','tactile_8':'中指中','tactile_9':'中指根','tactile_10':'中指掌',
|
| 543 |
+
'tactile_11':'无名尖','tactile_12':'无名中','tactile_13':'无名根','tactile_14':'无名掌',
|
| 544 |
+
'tactile_15':'小指尖','tactile_16':'小指中','tactile_17':'小指根','tactile_18':'小指掌',
|
| 545 |
+
'tactile_19':'掌心',
|
| 546 |
+
};
|
| 547 |
+
|
| 548 |
+
function buildTactile(shapes, groups){
|
| 549 |
+
const fingers=groups.filter(g=>g.type==='finger');
|
| 550 |
+
const palmGrp =groups.find(g=>g.type==='palm');
|
| 551 |
+
|
| 552 |
+
// ── Fingers section ──────────────────────────────────────
|
| 553 |
+
const fRow=document.getElementById('tac-fingers');
|
| 554 |
+
fRow.innerHTML='';
|
| 555 |
+
fingers.forEach(grp=>{
|
| 556 |
+
const col=document.createElement('div');
|
| 557 |
+
col.className='fg';
|
| 558 |
+
const lbl=document.createElement('div');
|
| 559 |
+
lbl.className='fg-label';
|
| 560 |
+
lbl.style.color=grp.color;
|
| 561 |
+
lbl.textContent=grp.label;
|
| 562 |
+
col.appendChild(lbl);
|
| 563 |
+
const sensors=document.createElement('div');
|
| 564 |
+
sensors.className='fg-sensors';
|
| 565 |
+
grp.sensors.forEach(key=>{
|
| 566 |
+
const sh=shapes[key]; if(!sh) return;
|
| 567 |
+
const [nr,nc]=sh;
|
| 568 |
+
sensors.appendChild(makeSensorCard(key,nr,nc,grp.color));
|
| 569 |
+
});
|
| 570 |
+
col.appendChild(sensors);
|
| 571 |
+
fRow.appendChild(col);
|
| 572 |
+
});
|
| 573 |
+
|
| 574 |
+
// ── Palm section ─────────────────────────────────────────
|
| 575 |
+
const pRow=document.getElementById('tac-palm');
|
| 576 |
+
pRow.innerHTML='';
|
| 577 |
+
if(palmGrp){
|
| 578 |
+
palmGrp.sensors.forEach(key=>{
|
| 579 |
+
const sh=shapes[key]; if(!sh) return;
|
| 580 |
+
const [nr,nc]=sh;
|
| 581 |
+
pRow.appendChild(makeSensorCard(key,nr,nc,palmGrp.color));
|
| 582 |
+
});
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
const total=Object.keys(shapes).length;
|
| 586 |
+
document.getElementById('pd-tac').textContent=`${total} sensors · ${PX}px/pt`;
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
function makeSensorCard(key,nr,nc,color){
|
| 590 |
+
const wrap=document.createElement('div'); wrap.className='sc';
|
| 591 |
+
const nm=document.createElement('div'); nm.className='sn';
|
| 592 |
+
nm.textContent=(TAC_NAMES[key]||key)+` [${nr}×${nc}]`;
|
| 593 |
+
wrap.appendChild(nm);
|
| 594 |
+
const cv=document.createElement('canvas');
|
| 595 |
+
cv.className='tc';
|
| 596 |
+
cv.width=nc*PX; cv.height=nr*PX;
|
| 597 |
+
cv.style.width=cv.width+'px'; cv.style.height=cv.height+'px';
|
| 598 |
+
cv.style.border=`1px solid ${color}40`;
|
| 599 |
+
cvMap[key]=cv; wrap.appendChild(cv);
|
| 600 |
+
const sm=document.createElement('div'); sm.className='ss';
|
| 601 |
+
sm.textContent='0.0'; sumMap[key]=sm; wrap.appendChild(sm);
|
| 602 |
+
return wrap;
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
// ── Draw heatmap ───────────────────────────────────────────────────────────
|
| 606 |
+
function drawHeatmap(key, data){
|
| 607 |
+
const cv=cvMap[key]; if(!cv) return;
|
| 608 |
+
const sh=META.tactile_2d_shapes[key]; if(!sh) return;
|
| 609 |
+
const [nr,nc]=sh;
|
| 610 |
+
const vmax=Math.max(...data,1e-6);
|
| 611 |
+
const ctx=cv.getContext('2d');
|
| 612 |
+
const id=ctx.createImageData(cv.width,cv.height);
|
| 613 |
+
const d32=id.data;
|
| 614 |
+
for(let r=0;r<nr;r++){
|
| 615 |
+
for(let c=0;c<nc;c++){
|
| 616 |
+
const v=Math.max(0,data[r*nc+c])/vmax;
|
| 617 |
+
const [R,G,B]=cmapRGB(Math.min(v,1));
|
| 618 |
+
const px_y=r*PX, px_x=c*PX;
|
| 619 |
+
for(let dy=0;dy<PX;dy++) for(let dx=0;dx<PX;dx++){
|
| 620 |
+
const i=((px_y+dy)*cv.width+(px_x+dx))*4;
|
| 621 |
+
d32[i]=R; d32[i+1]=G; d32[i+2]=B; d32[i+3]=255;
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
}
|
| 625 |
+
ctx.putImageData(id,0,0);
|
| 626 |
+
if(sumMap[key]) sumMap[key].textContent=
|
| 627 |
+
data.reduce((s,v)=>s+(v>0?v:0),0).toFixed(1);
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
// ── Quaternion utilities ───────────────────────────────────────────────────
|
| 631 |
+
function quatRotate(v, q){
|
| 632 |
+
// Rotate vector v=[x,y,z] by unit quaternion q=[w,x,y,z]
|
| 633 |
+
const [w,qx,qy,qz]=q, [vx,vy,vz]=v;
|
| 634 |
+
const tx=2*(qy*vz-qz*vy), ty=2*(qz*vx-qx*vz), tz=2*(qx*vy-qy*vx);
|
| 635 |
+
return [vx+w*tx+qy*tz-qz*ty, vy+w*ty+qz*tx-qx*tz, vz+w*tz+qx*ty-qy*tx];
|
| 636 |
+
}
|
| 637 |
+
function quatNorm(q){ const n=Math.hypot(...q); return q.map(v=>v/n); }
|
| 638 |
+
|
| 639 |
+
// ── Skeleton projection (draggable view) ──────────────────────────────────
|
| 640 |
+
const FC=['#ff6b6b','#ffd93d','#6bcb77','#4d96ff','#c77dff'];
|
| 641 |
+
const FIDX=[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15],[16,17,18,19]];
|
| 642 |
+
const PBASES=[0,4,8,12,16];
|
| 643 |
+
|
| 644 |
+
// Z-up 视角:方位角 + 仰角(垂直于重力的 XY 平面为地面)
|
| 645 |
+
let viewAZ=0.75, viewEL=0.45; // azimuth around Z-axis, elevation above XY-plane
|
| 646 |
+
|
| 647 |
+
function proj(pts3d){
|
| 648 |
+
// 1. 绕 Z 轴旋转方位角
|
| 649 |
+
// 2. 绕新 X 轴仰角倾斜
|
| 650 |
+
// 3. 正射投影,丢弃深度
|
| 651 |
+
const cA=Math.cos(viewAZ), sA=Math.sin(viewAZ);
|
| 652 |
+
const cE=Math.cos(viewEL), sE=Math.sin(viewEL);
|
| 653 |
+
return pts3d.map(([x,y,z])=>{
|
| 654 |
+
const xR = x*cA - y*sA; // rotate azimuth
|
| 655 |
+
const yR = x*sA + y*cA;
|
| 656 |
+
const yT = yR*cE + z*sE; // tilt elevation (this becomes screen-Y)
|
| 657 |
+
return [xR, -yT]; // flip so +Z is up on screen
|
| 658 |
+
});
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
// Last skeleton data — re-rendered on drag without network fetch
|
| 662 |
+
let lastSkelPos=null, lastSkelQuat=null;
|
| 663 |
+
|
| 664 |
+
function initSkelDrag(){
|
| 665 |
+
const svg=document.getElementById('svg-skel');
|
| 666 |
+
svg.style.cursor='grab';
|
| 667 |
+
let dragStart=null, az0, el0;
|
| 668 |
+
svg.addEventListener('mousedown',e=>{
|
| 669 |
+
dragStart={x:e.clientX,y:e.clientY}; az0=viewAZ; el0=viewEL;
|
| 670 |
+
svg.style.cursor='grabbing'; e.preventDefault();
|
| 671 |
+
});
|
| 672 |
+
window.addEventListener('mousemove',e=>{
|
| 673 |
+
if(!dragStart) return;
|
| 674 |
+
viewAZ=az0+(e.clientX-dragStart.x)*0.009;
|
| 675 |
+
viewEL=Math.max(0.05,Math.min(1.5, el0-(e.clientY-dragStart.y)*0.009));
|
| 676 |
+
if(lastSkelPos) drawSkeleton(lastSkelPos,lastSkelQuat);
|
| 677 |
+
});
|
| 678 |
+
window.addEventListener('mouseup',()=>{
|
| 679 |
+
dragStart=null; svg.style.cursor='grab';
|
| 680 |
+
});
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
function drawSkeleton(positions, quaternions){
|
| 684 |
+
lastSkelPos=positions; lastSkelQuat=quaternions;
|
| 685 |
+
const svg=document.getElementById('svg-skel');
|
| 686 |
+
svg.innerHTML='';
|
| 687 |
+
const noData = !positions || positions.length<60 ||
|
| 688 |
+
Math.max(...positions.map(Math.abs)) < 1e-6;
|
| 689 |
+
if(noData){
|
| 690 |
+
const t=mkel('text',{x:0,y:10,fill:'#8b949e','text-anchor':'middle','font-size':'13'});
|
| 691 |
+
t.textContent='Motion data unavailable'; svg.appendChild(t); return;
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
// Parse 20 world-space markers
|
| 695 |
+
let pts3d=[];
|
| 696 |
+
for(let i=0;i<20;i++) pts3d.push([positions[i*3],positions[i*3+1],positions[i*3+2]]);
|
| 697 |
+
|
| 698 |
+
// First frame: record centroid and scale
|
| 699 |
+
if(!skelCenter){
|
| 700 |
+
const cx3=pts3d.reduce((s,p)=>s+p[0],0)/20;
|
| 701 |
+
const cy3=pts3d.reduce((s,p)=>s+p[1],0)/20;
|
| 702 |
+
const cz3=pts3d.reduce((s,p)=>s+p[2],0)/20;
|
| 703 |
+
skelCenter=[cx3,cy3,cz3];
|
| 704 |
+
// Scale: based on hand span at first frame (orientation-invariant max-radius)
|
| 705 |
+
const rel0=pts3d.map(([x,y,z])=>[x-cx3,y-cy3,z-cz3]);
|
| 706 |
+
const maxR=Math.max(...rel0.map(([x,y,z])=>Math.sqrt(x*x+y*y+z*z)));
|
| 707 |
+
skelScale=90/Math.max(maxR,1e-6); // smaller scale leaves room for displacement
|
| 708 |
+
}
|
| 709 |
+
// Subtract fixed first-frame center → translation relative to start is preserved
|
| 710 |
+
pts3d=pts3d.map(([x,y,z])=>[x-skelCenter[0],y-skelCenter[1],z-skelCenter[2]]);
|
| 711 |
+
|
| 712 |
+
const spts=pts3d.map(([x,y,z])=>[x*skelScale,y*skelScale,z*skelScale]);
|
| 713 |
+
|
| 714 |
+
// Isometric projection
|
| 715 |
+
const proj2d=proj(spts);
|
| 716 |
+
const pts=proj2d; // already in pixel coords (centered at origin)
|
| 717 |
+
|
| 718 |
+
// Palm center (projected)
|
| 719 |
+
const pbS=PBASES.map(i=>spts[i]);
|
| 720 |
+
const pm=[pbS.reduce((s,p)=>s+p[0],0)/5, pbS.reduce((s,p)=>s+p[1],0)/5,
|
| 721 |
+
pbS.reduce((s,p)=>s+p[2],0)/5];
|
| 722 |
+
const [[pcx,pcy]]=proj([pm]);
|
| 723 |
+
|
| 724 |
+
// Ground grid: XY plane (Z=const, Z is vertical/gravity axis)
|
| 725 |
+
{
|
| 726 |
+
const GZ=-1.6*skelScale; // below hand (Z is up, gravity is -Z)
|
| 727 |
+
const GR=2.4*skelScale, GN=8, gStep=GR*2/GN;
|
| 728 |
+
for(let i=0;i<=GN;i++){
|
| 729 |
+
const t=-GR+i*gStep;
|
| 730 |
+
const isCenter=(i===GN/2);
|
| 731 |
+
const sc=isCenter?'#2e3d52':'#1e2a38', sw=isCenter?'1.0':'0.6';
|
| 732 |
+
// Lines parallel to X axis (vary X, Y=t, Z=ground)
|
| 733 |
+
const [[ax0,ay0]]=proj([[-GR,t,GZ]]);
|
| 734 |
+
const [[ax1,ay1]]=proj([[ GR,t,GZ]]);
|
| 735 |
+
svg.appendChild(mkel('line',{x1:ax0,y1:ay0,x2:ax1,y2:ay1,stroke:sc,strokeWidth:sw}));
|
| 736 |
+
// Lines parallel to Y axis (vary Y, X=t, Z=ground)
|
| 737 |
+
const [[bx0,by0]]=proj([[t,-GR,GZ]]);
|
| 738 |
+
const [[bx1,by1]]=proj([[t, GR,GZ]]);
|
| 739 |
+
svg.appendChild(mkel('line',{x1:bx0,y1:by0,x2:bx1,y2:by1,stroke:sc,strokeWidth:sw}));
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
// Palm dashed spokes
|
| 744 |
+
PBASES.forEach(bi=>{
|
| 745 |
+
const [x,y]=pts[bi];
|
| 746 |
+
svg.appendChild(mkel('line',{x1:pcx,y1:pcy,x2:x,y2:y,
|
| 747 |
+
stroke:'#444c56',strokeWidth:'1.2','stroke-dasharray':'4 3'}));
|
| 748 |
+
});
|
| 749 |
+
|
| 750 |
+
// Finger bones & joints
|
| 751 |
+
FIDX.forEach((idxs,fi)=>{
|
| 752 |
+
const col=FC[fi];
|
| 753 |
+
for(let k=0;k<idxs.length-1;k++){
|
| 754 |
+
const [x0,y0]=pts[idxs[k]], [x1,y1]=pts[idxs[k+1]];
|
| 755 |
+
svg.appendChild(mkel('line',{x1:x0,y1:y0,x2:x1,y2:y1,
|
| 756 |
+
stroke:col,strokeWidth:'2.8',strokeLinecap:'round'}));
|
| 757 |
+
}
|
| 758 |
+
idxs.forEach(i=>{
|
| 759 |
+
const [x,y]=pts[i];
|
| 760 |
+
svg.appendChild(mkel('circle',{cx:x,cy:y,r:'4.5',
|
| 761 |
+
fill:col,stroke:'#0d1117',strokeWidth:'1.2'}));
|
| 762 |
+
});
|
| 763 |
+
});
|
| 764 |
+
|
| 765 |
+
// Palm star
|
| 766 |
+
svg.appendChild(mkel('circle',{cx:pcx,cy:pcy,r:'8',
|
| 767 |
+
fill:'#ffffff18',stroke:'#ffffff88',strokeWidth:'1.5'}));
|
| 768 |
+
const star=mkel('text',{x:pcx,y:pcy+4.5,'text-anchor':'middle',
|
| 769 |
+
fill:'white','font-size':'11','font-weight':'bold'});
|
| 770 |
+
star.textContent='★'; svg.appendChild(star);
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
function mkel(tag,attrs){
|
| 774 |
+
const el=document.createElementNS('http://www.w3.org/2000/svg',tag);
|
| 775 |
+
for(const[k,v] of Object.entries(attrs)) el.setAttribute(k,v);
|
| 776 |
+
return el;
|
| 777 |
+
}
|
| 778 |
+
|
| 779 |
+
// ── Tactile Timeline ───────────────────────────────────────────────────────
|
| 780 |
+
async function fetchTimeline(ep){
|
| 781 |
+
TIMELINE=null;
|
| 782 |
+
document.getElementById('pd-timeline').textContent='loading…';
|
| 783 |
+
try{
|
| 784 |
+
TIMELINE=await fetch(`/api/tactile_timeline?ep=${ep}`).then(r=>r.json());
|
| 785 |
+
document.getElementById('pd-timeline').textContent=
|
| 786 |
+
`${TIMELINE.n_frames} frames · 6 groups`;
|
| 787 |
+
}catch(e){ document.getElementById('pd-timeline').textContent='error'; }
|
| 788 |
+
drawTimeline(curFrame);
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
const TAC_NAMES_SHORT={
|
| 792 |
+
'tactile_0':'拇尖','tactile_1':'拇中','tactile_2':'拇根',
|
| 793 |
+
'tactile_3':'食尖','tactile_4':'食中','tactile_5':'食根','tactile_6':'食掌',
|
| 794 |
+
'tactile_7':'中尖','tactile_8':'中中','tactile_9':'中根','tactile_10':'中掌',
|
| 795 |
+
'tactile_11':'无尖','tactile_12':'无中','tactile_13':'无根','tactile_14':'无掌',
|
| 796 |
+
'tactile_15':'小尖','tactile_16':'小中','tactile_17':'小根','tactile_18':'小掌',
|
| 797 |
+
'tactile_19':'掌心',
|
| 798 |
+
};
|
| 799 |
+
|
| 800 |
+
function setupTimeline(){
|
| 801 |
+
const pb=document.getElementById('tl-pb');
|
| 802 |
+
const cv=document.getElementById('tac-timeline');
|
| 803 |
+
if(!pb||!cv) return;
|
| 804 |
+
function resize(){
|
| 805 |
+
const W=pb.clientWidth, H=pb.clientHeight;
|
| 806 |
+
if(W>10&&H>10){ cv.width=W; cv.height=H; drawTimeline(curFrame); }
|
| 807 |
+
}
|
| 808 |
+
new ResizeObserver(resize).observe(pb);
|
| 809 |
+
resize();
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
function drawTimeline(frame){
|
| 813 |
+
const cv=document.getElementById('tac-timeline');
|
| 814 |
+
if(!cv||!cv.width||!cv.height) return;
|
| 815 |
+
const W=cv.width, H=cv.height;
|
| 816 |
+
const ctx=cv.getContext('2d');
|
| 817 |
+
ctx.fillStyle='#161b22'; ctx.fillRect(0,0,W,H);
|
| 818 |
+
if(!TIMELINE){
|
| 819 |
+
ctx.fillStyle='#555e6a'; ctx.font='12px sans-serif'; ctx.textAlign='center';
|
| 820 |
+
ctx.fillText('Loading…',W/2,H/2); return;
|
| 821 |
+
}
|
| 822 |
+
const sensors=TIMELINE.sensors, nf=TIMELINE.n_frames, start=TIMELINE.start;
|
| 823 |
+
const fi=Math.max(0,Math.min(frame-start,nf-1));
|
| 824 |
+
|
| 825 |
+
const LW=72;
|
| 826 |
+
const PAD={l:36,r:LW+4,t:8,b:20};
|
| 827 |
+
const cw=W-PAD.l-PAD.r, ch=H-PAD.t-PAD.b;
|
| 828 |
+
|
| 829 |
+
// Y max
|
| 830 |
+
let ymax=0;
|
| 831 |
+
sensors.forEach(s=>s.sums.forEach(v=>{if(v>ymax)ymax=v;}));
|
| 832 |
+
if(ymax<1) ymax=1;
|
| 833 |
+
|
| 834 |
+
// Grid
|
| 835 |
+
ctx.lineWidth=0.5;
|
| 836 |
+
for(let i=0;i<=4;i++){
|
| 837 |
+
const y=PAD.t+ch*(1-i/4);
|
| 838 |
+
ctx.strokeStyle='#1e2a38';
|
| 839 |
+
ctx.beginPath(); ctx.moveTo(PAD.l,y); ctx.lineTo(PAD.l+cw,y); ctx.stroke();
|
| 840 |
+
ctx.fillStyle='#555e6a'; ctx.font='8px monospace'; ctx.textAlign='right';
|
| 841 |
+
ctx.fillText(Math.round(ymax*i/4),PAD.l-3,y+3);
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
// Lines
|
| 845 |
+
sensors.forEach(s=>{
|
| 846 |
+
ctx.strokeStyle=s.color; ctx.lineWidth=1.2; ctx.globalAlpha=0.8;
|
| 847 |
+
ctx.beginPath();
|
| 848 |
+
s.sums.forEach((v,i)=>{
|
| 849 |
+
const x=PAD.l+(nf>1?i/(nf-1):0)*cw;
|
| 850 |
+
const y=PAD.t+ch*(1-v/ymax);
|
| 851 |
+
i===0?ctx.moveTo(x,y):ctx.lineTo(x,y);
|
| 852 |
+
});
|
| 853 |
+
ctx.stroke();
|
| 854 |
+
});
|
| 855 |
+
ctx.globalAlpha=1;
|
| 856 |
+
|
| 857 |
+
// Cursor
|
| 858 |
+
const cx=PAD.l+(nf>1?fi/(nf-1):0)*cw;
|
| 859 |
+
ctx.strokeStyle='rgba(255,255,255,0.5)'; ctx.lineWidth=1;
|
| 860 |
+
ctx.setLineDash([3,3]);
|
| 861 |
+
ctx.beginPath(); ctx.moveTo(cx,PAD.t); ctx.lineTo(cx,PAD.t+ch); ctx.stroke();
|
| 862 |
+
ctx.setLineDash([]);
|
| 863 |
+
ctx.fillStyle='#8b949e'; ctx.font='8px monospace'; ctx.textAlign='center';
|
| 864 |
+
ctx.fillText('f'+fi,Math.min(Math.max(cx,18),W-LW-8),PAD.t+ch+13);
|
| 865 |
+
|
| 866 |
+
// Right list: sensor name + current value
|
| 867 |
+
const lx=W-LW;
|
| 868 |
+
const rowH=Math.max(10,Math.min(14,ch/sensors.length));
|
| 869 |
+
sensors.forEach((s,idx)=>{
|
| 870 |
+
const val=(s.sums[fi]??0).toFixed(1);
|
| 871 |
+
const ly=PAD.t+rowH*idx+rowH*0.78;
|
| 872 |
+
const fs=Math.max(7,Math.min(9,Math.floor(rowH*0.75)));
|
| 873 |
+
ctx.fillStyle=s.color; ctx.fillRect(lx,ly-4,6,2);
|
| 874 |
+
ctx.font=`${fs}px sans-serif`;
|
| 875 |
+
ctx.fillStyle='#c0c8d0'; ctx.textAlign='left';
|
| 876 |
+
ctx.fillText(TAC_NAMES_SHORT[s.key]||s.key,lx+9,ly);
|
| 877 |
+
ctx.fillStyle=s.color; ctx.textAlign='right';
|
| 878 |
+
ctx.fillText(val,W-2,ly);
|
| 879 |
+
});
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
// ── Fetch frame ────────────────────────────────────────────────────────────
|
| 883 |
+
let aborter=null;
|
| 884 |
+
function fetchFrame(n, ep){
|
| 885 |
+
if(aborter) try{aborter.abort()}catch(_){}
|
| 886 |
+
aborter=new AbortController();
|
| 887 |
+
const sig=aborter.signal;
|
| 888 |
+
const ep_data=META.episodes[ep];
|
| 889 |
+
const fin=n-ep_data.start;
|
| 890 |
+
|
| 891 |
+
fetch(`/api/frame?n=${n}&ep=${ep}`,{signal:sig}).then(r=>r.json()).then(d=>{
|
| 892 |
+
document.getElementById('ts-lbl').textContent=`t = ${d.timestamp.toFixed(3)} s`;
|
| 893 |
+
document.getElementById('fr-lbl').textContent=
|
| 894 |
+
`Frame ${fin} / ${ep_data.length-1}`;
|
| 895 |
+
drawSkeleton(d.positions, d.quaternions);
|
| 896 |
+
for(const key of Object.keys(META.tactile_2d_shapes)){
|
| 897 |
+
if(d.tactile[key]) drawHeatmap(key, d.tactile[key]);
|
| 898 |
+
}
|
| 899 |
+
drawTimeline(n);
|
| 900 |
+
}).catch(e=>{ if(e.name!=='AbortError') console.warn('frame fetch:',e); });
|
| 901 |
+
|
| 902 |
+
fetch(`/api/image?ep=${ep}&f=${fin}&type=color`,{signal:sig})
|
| 903 |
+
.then(r=>r.json()).then(d=>{
|
| 904 |
+
if(d.data) document.getElementById('img-color').src='data:image/jpeg;base64,'+d.data;
|
| 905 |
+
}).catch(()=>{});
|
| 906 |
+
|
| 907 |
+
}
|
| 908 |
+
|
| 909 |
+
// ── Episode switch ─────────────────────────────────────────────────────────
|
| 910 |
+
function switchEp(ep){
|
| 911 |
+
curEp=Math.max(0,Math.min(META.n_episodes-1,ep));
|
| 912 |
+
skelScale=null; skelCenter=null; lastSkelPos=null; lastSkelQuat=null;
|
| 913 |
+
// 清空骨架面板,避免上一个 episode 的残影
|
| 914 |
+
const svgEl=document.getElementById('svg-skel');
|
| 915 |
+
if(svgEl) svgEl.innerHTML='';
|
| 916 |
+
const epd=META.episodes[curEp];
|
| 917 |
+
curFrame=epd.start;
|
| 918 |
+
const sl=document.getElementById('slider');
|
| 919 |
+
sl.min=epd.start; sl.max=epd.end; sl.value=curFrame;
|
| 920 |
+
document.getElementById('ep-select').value=curEp;
|
| 921 |
+
// 更新顶部任务描述条
|
| 922 |
+
document.getElementById('task-bar-ep').textContent=`Ep ${curEp}`;
|
| 923 |
+
document.getElementById('task-bar-text').textContent=epd.task||'—';
|
| 924 |
+
fetchFrame(curFrame,curEp);
|
| 925 |
+
fetchTimeline(curEp);
|
| 926 |
+
}
|
| 927 |
+
|
| 928 |
+
// ── Play ───────────────────────────────────────────────────────────────────
|
| 929 |
+
function togglePlay(){
|
| 930 |
+
playing=!playing;
|
| 931 |
+
document.getElementById('play-btn').textContent=playing?'⏸ Pause':'▶ Play';
|
| 932 |
+
if(playing) tick();
|
| 933 |
+
}
|
| 934 |
+
function tick(){
|
| 935 |
+
if(!playing) return;
|
| 936 |
+
const epd=META.episodes[curEp];
|
| 937 |
+
curFrame=(curFrame>=epd.end)?epd.start:curFrame+1;
|
| 938 |
+
document.getElementById('slider').value=curFrame;
|
| 939 |
+
fetchFrame(curFrame,curEp);
|
| 940 |
+
playTimer=setTimeout(tick,Math.max(40,1000/META.fps));
|
| 941 |
+
}
|
| 942 |
+
|
| 943 |
+
// ── Init ───────────────────────────────────────────────────────────────────
|
| 944 |
+
async function init(){
|
| 945 |
+
const meta=await fetch('/api/meta').then(r=>r.json());
|
| 946 |
+
META=meta; CMAP=meta.cmap_colors;
|
| 947 |
+
|
| 948 |
+
document.getElementById('c-ds').textContent=meta.name;
|
| 949 |
+
document.getElementById('c-eps').textContent=meta.n_episodes+' episodes';
|
| 950 |
+
document.getElementById('c-fps').textContent=meta.fps+' fps';
|
| 951 |
+
|
| 952 |
+
// Populate episode dropdown
|
| 953 |
+
const sel=document.getElementById('ep-select');
|
| 954 |
+
meta.episodes.forEach((ep,i)=>{
|
| 955 |
+
const opt=document.createElement('option');
|
| 956 |
+
opt.value=i;
|
| 957 |
+
opt.textContent=`Episode ${i} (${ep.length} frames)`;
|
| 958 |
+
sel.appendChild(opt);
|
| 959 |
+
});
|
| 960 |
+
sel.addEventListener('change',()=>switchEp(parseInt(sel.value)));
|
| 961 |
+
|
| 962 |
+
document.getElementById('btn-prev').onclick=()=>switchEp(curEp-1);
|
| 963 |
+
document.getElementById('btn-next').onclick=()=>switchEp(curEp+1);
|
| 964 |
+
document.getElementById('play-btn').onclick=togglePlay;
|
| 965 |
+
|
| 966 |
+
const sl=document.getElementById('slider');
|
| 967 |
+
sl.addEventListener('input',()=>{
|
| 968 |
+
if(playing){clearTimeout(playTimer);playing=false;
|
| 969 |
+
document.getElementById('play-btn').textContent='▶ Play';}
|
| 970 |
+
curFrame=parseInt(sl.value);
|
| 971 |
+
fetchFrame(curFrame,curEp);
|
| 972 |
+
});
|
| 973 |
+
|
| 974 |
+
buildTactile(meta.tactile_2d_shapes, meta.sensor_groups);
|
| 975 |
+
initSkelDrag();
|
| 976 |
+
setupTimeline();
|
| 977 |
+
switchEp(0);
|
| 978 |
+
}
|
| 979 |
+
init();
|
| 980 |
+
</script>
|
| 981 |
+
</body>
|
| 982 |
+
</html>"""
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 986 |
+
def _pick_folder():
|
| 987 |
+
try:
|
| 988 |
+
import tkinter as tk
|
| 989 |
+
from tkinter import filedialog
|
| 990 |
+
r=tk.Tk(); r.withdraw()
|
| 991 |
+
p=filedialog.askdirectory(title="选择 LeRobot 数据集文件夹")
|
| 992 |
+
r.destroy(); return p or None
|
| 993 |
+
except Exception:
|
| 994 |
+
return None
|
| 995 |
+
|
| 996 |
+
def main():
|
| 997 |
+
global _DS
|
| 998 |
+
parser=argparse.ArgumentParser()
|
| 999 |
+
parser.add_argument("--dataset","-d",default=None)
|
| 1000 |
+
parser.add_argument("--port","-p",type=int,default=PORT)
|
| 1001 |
+
args=parser.parse_args()
|
| 1002 |
+
path=args.dataset or _pick_folder()
|
| 1003 |
+
if not path: sys.exit("未指定数据集路径")
|
| 1004 |
+
_DS=DataServer(path)
|
| 1005 |
+
class _Srv(HTTPServer):
|
| 1006 |
+
allow_reuse_address=True
|
| 1007 |
+
srv=_Srv(("127.0.0.1",args.port),Handler)
|
| 1008 |
+
url=f"http://127.0.0.1:{args.port}"
|
| 1009 |
+
print(f"\n可视化服务已启动 → {url}\n按 Ctrl+C 停止\n")
|
| 1010 |
+
threading.Thread(target=lambda:(time.sleep(0.8),webbrowser.open(url)),daemon=True).start()
|
| 1011 |
+
try: srv.serve_forever()
|
| 1012 |
+
except KeyboardInterrupt: print("\n已停止")
|
| 1013 |
+
|
| 1014 |
+
if __name__=="__main__":
|
| 1015 |
+
main()
|