File size: 45,533 Bytes
eb6b1ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
#!/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()