File size: 27,968 Bytes
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4f352
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4f352
 
 
 
 
 
 
 
 
2fc368a
 
cb4f352
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4f352
2fc368a
 
 
cb4f352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4f352
 
 
 
 
 
 
 
 
 
 
 
 
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb4f352
 
 
2fc368a
 
 
 
 
 
 
 
 
cb4f352
2fc368a
 
cb4f352
 
2fc368a
 
 
 
 
 
 
 
 
 
cb4f352
2fc368a
 
cb4f352
 
 
 
 
2fc368a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Local, read-only EMGSuite viewer. Run with the repository's Python environment."""
from __future__ import annotations

import argparse
from collections import OrderedDict
from functools import partial
import gzip
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import math
from pathlib import Path
import re
import struct
import threading
from urllib.parse import parse_qs, urlsplit

import cv2
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

HERE = Path(__file__).resolve().parent


def clean(value):
    """Strict JSON: represent missing/unsupported values as null, never NaN."""
    if value is None or value is pd.NA:
        return None
    if isinstance(value, dict):
        return {str(k): clean(v) for k, v in value.items()}
    if isinstance(value, (list, tuple, np.ndarray)):
        return [clean(v) for v in value]
    if isinstance(value, (np.bool_, bool)):
        return bool(value)
    if isinstance(value, (np.integer, int)):
        return int(value)
    if isinstance(value, (np.floating, float)):
        return float(value) if math.isfinite(value) else None
    return value


def project_hand(points, valid, profile):
    """Project LEFT optical XYZ through the delivered views' lens models."""
    if profile.get('export_rectified') or profile.get('export_mirrored'):
        # All current profiles are unrectified/unmirrored. Fail explicitly
        # rather than silently drawing a wrong geometry for future releases.
        raise ValueError('Rectified or mirrored exports require a different projection; this viewer supports the current unrectified, unmirrored release.')
    flat = np.asarray(points, np.float64).reshape(-1, 3)
    base = np.asarray(valid, bool).reshape(-1) & np.isfinite(flat).all(axis=1)
    rotation = np.asarray(profile['R_left_to_right'], np.float64)
    translation = np.asarray(profile['t_left_to_right_m'], np.float64)
    output = {}
    for eye, xyz in [('left', flat), ('right', flat @ rotation.T + translation)]:
        supported = base & np.isfinite(xyz).all(axis=1) & (xyz[:, 2] > 1e-6)
        uv = np.full((len(flat), 2), np.nan, dtype=np.float64)
        eye_profile = profile['eyes'][eye]
        if supported.any():
            pixels, _ = cv2.projectPoints(xyz[supported], np.zeros(3), np.zeros(3),
                np.asarray(eye_profile['K'], np.float64), np.asarray(eye_profile['D'], np.float64))
            uv[supported] = pixels.reshape(-1, 2)
        # Finite projections outside the viewport are retained; Canvas clips
        # them. Invalid joints remain null and cannot form a valid bone.
        output[eye] = clean(np.round(uv.reshape(-1, 21, 2), 3))
    return output


def emg_segments(emg, lo, hi):
    """Half-open source-index ranges with continuous, usable, same-quality samples."""
    if hi <= lo:
        return []
    values = emg['microvolts_filtered'][lo:hi]
    valid = emg['filter_valid'][lo:hi] & np.isfinite(values).all(axis=1)
    runs = emg['run_id'][lo:hi]
    approved = emg['approved'][lo:hi]
    dt = np.diff(emg['times_ns'][lo:hi])
    median_dt = np.median(dt[dt > 0]) if np.any(dt > 0) else np.inf
    breaks = ((valid[1:] != valid[:-1]) | (runs[1:] != runs[:-1])
        | (approved[1:] != approved[:-1]) | (dt <= 0) | (dt > 1.5 * median_dt)
        | (np.diff(emg['source_sample_index'][lo:hi]) != 1))
    boundaries = np.r_[0, np.flatnonzero(breaks) + 1, hi-lo]
    return [{'start': int(lo+first), 'stop': int(lo+stop),
             'approved': bool(approved[first]), 'run_id': int(runs[first])}
            for first, stop in zip(boundaries[:-1], boundaries[1:]) if valid[first]]


def emg_line_segments(emg, lo, hi, bins):
    """Retain actual extrema in time order; never connect discontinuous runs."""
    values = emg['microvolts_filtered'][lo:hi]
    times = emg['seconds'][lo:hi]
    result = []
    for segment in emg_segments(emg, lo, hi):
        first, stop = segment['start']-lo, segment['stop']-lo
        count = int(stop-first)
        bucket_count = min(count, max(1, math.ceil(count * bins / (hi-lo))))
        edges = np.linspace(first, stop, bucket_count+1, dtype=np.int64)
        indices = np.empty((bucket_count, 2, values.shape[1]), dtype=np.int64)
        for k, (start, end) in enumerate(zip(edges[:-1], edges[1:])):
            indices[k, 0] = start + np.argmin(values[start:end], axis=0)
            indices[k, 1] = start + np.argmax(values[start:end], axis=0)
        indices.sort(axis=1)
        selected = np.vstack([np.full((1, values.shape[1]), first),
            indices.reshape(-1, values.shape[1]), np.full((1, values.shape[1]), stop-1)])
        result.append({'approved': segment['approved'], 'run_id': segment['run_id'],
            'time': times[selected].T,
            'value': values[selected, np.arange(values.shape[1])].T})
    return result


class Trial:
    def __init__(self, store, trial_id):
        self.store = store
        self.id = trial_id
        self.meta = store.trials[trial_id]
        self.ep = store.episodes[trial_id]
        self.frame_path = store.resolve(store.info['data_path'].format(
            chunk_index=self.ep['data/chunk_index'], file_index=self.ep['data/file_index']))
        self.frames = pd.read_parquet(self.frame_path)
        self.n = len(self.frames)
        if self.n != self.meta['frames'] or not np.array_equal(self.frames.frame_index, np.arange(self.n)):
            raise ValueError(f'Trial {trial_id}: frame table disagrees with episode metadata')
        self.origin = int(self.frames.host_time_ns.iloc[0])
        self.host_seconds = (self.frames.host_time_ns.to_numpy(np.int64) - self.origin) / 1e9
        self.profile = store.calibrations[self.meta['calibration_id']]
        self.emg_path = store.emg_path(trial_id)
        schema = pq.read_schema(self.emg_path)
        preprocessing = json.loads((schema.metadata or {}).get(b'emgsuite_emg_preprocessing', b'{}'))
        self.single_run = json.loads(schema.metadata[b'emgsuite_single_run'])
        self.emg_source = {'path': str(self.emg_path.relative_to(store.root)),
            'signal': 'microvolts_filtered', 'units': 'microvolts',
            'processing': preprocessing.get('parameters', {})}
        self.imu_path = store.camera_imu_path(trial_id)
        self.imu_source = {
            'path': str(self.imu_path.relative_to(store.root)),
            'rate_hz': self.meta['camera_imu_rate_hz'], 'units': 'device counts',
            'channel_order': [f'raw_{i}' for i in range(6)],
            'axis_order_and_scale_verified': False,
            'vendor_corrections_applied': False,
            'reference_parameters': store.imu_references[self.meta['calibration_id']],
        }
        self.lock = threading.RLock()
        self._emg = None
        self._imu = None
        self._payload = None

    def payload(self):
        with self.lock:
            if self._payload is None:
                f = self.frames
                joints = np.stack(f.hand_joints_camera_m).reshape(-1, 21, 3)
                valid = np.stack(f.hand_joint_valid)
                projections = project_hand(joints, valid, self.profile)
                names = ['contact', 'model_valid', 'contact_thumb_probability', 'contact_index_probability',
                    'pressure_thumb_adc', 'pressure_index_adc',
                    'head_pose_valid', 'map_segment_index', 'hand_observed_left', 'hand_observed_right']
                columns = {name: clean(f[name].tolist()) for name in names}
                status = f.pose_target_status.to_numpy()
                columns['target_valid'] = (status != 0).tolist()
                columns['original_target_valid'] = (status == 1).tolist()
                columns['interpolated_target_valid'] = (status == 2).tolist()
                columns['camera_valid'] = columns['head_pose_valid']
                columns['host_seconds'] = self.host_seconds.tolist()
                columns['supported_joints'] = valid.sum(axis=1).tolist()
                self._payload = clean({
                    'trial': self.meta, 'fps': self.store.info['fps'], 'length': self.n,
                    'duration': self.n / self.store.info['fps'], 'host_origin_ns': str(self.origin),
                    'image_size': self.profile['export_image_size_px'], 'columns': columns,
                    'projections': projections,
                    'video': {eye: f'/media/{self.id}/{eye}' for eye in ['left', 'right']},
                    'calibration': self.profile,
                    'emg_source': self.emg_source,
                    'camera_imu': self.imu_source,
                })
            return self._payload

    def camera_imu(self):
        """Read original capture batches without interpreting axes or applying calibration."""
        with self.lock:
            if self._imu is None:
                table = pq.read_table(self.imu_path)
                schema = pa.schema([('episode_index', pa.int32()), ('parent_frame_index', pa.int32()),
                    ('host_time_ns', pa.int64()), ('raw_counts', pa.list_(pa.int16(), 6))])
                if not table.schema.equals(schema, check_metadata=False):
                    raise ValueError('Unexpected camera IMU schema')
                counts = table['raw_counts'].combine_chunks()
                if any(col.null_count for col in table.columns) or counts.values.null_count:
                    raise ValueError('Camera IMU contains null samples')
                parents = table['parent_frame_index'].to_numpy()
                times = table['host_time_ns'].to_numpy()
                values = counts.values.to_numpy().reshape(-1, 6)
                if (not len(table) or not np.all(table['episode_index'].to_numpy() == self.id)
                        or not np.all((parents >= 0) & (parents < self.n))
                        or not np.all(np.diff(parents) >= 0) or not np.all(np.diff(times) > 0)
                        or values.shape != (len(table), 6)):
                    raise ValueError('Camera IMU sample shape, frame joins or timestamps are invalid')
                self._imu = {'parents': parents, 'times_ns': times, 'raw_counts': values}
            return self._imu

    def emg(self):
        with self.lock:
            if self._emg is None:
                table = pd.read_parquet(self.emg_path)
                times = table.host_time_ns.to_numpy(np.int64)
                if len(table) != self.meta['emg_samples'] or not np.all(np.diff(times) > 0):
                    raise ValueError('EMG row count or timestamps disagree with trial metadata')
                values = np.stack(table.microvolts_filtered).astype(np.float32)
                self._emg = {
                    'times_ns': times, 'seconds': (times - self.origin) / 1e9,
                    'microvolts_filtered': values,
                    'filter_valid': np.isfinite(values).all(axis=1),
                    'approved': np.full(len(times), self.single_run['all_approved'], dtype=bool),
                    'run_id': np.full(len(times), self.single_run['run_id'], dtype=np.int64),
                    'source_sample_index': self.single_run['first_source_index'] + np.arange(len(times)),
                }
            return self._emg

    def emg_full(self):
        """Lossless full-trial transport: aligned JSON header, float64 time, float32 EMG."""
        emg = self.emg()
        values = emg['microvolts_filtered']
        samples, channels = values.shape
        segments = emg_segments(emg, 0, samples)
        metadata = {'episode_index': self.id, 'samples': samples, 'channels': channels,
            'unit': 'microvolts', 'source': self.emg_source, 'segments': segments,
            'filter_valid_samples': sum(s['stop']-s['start'] for s in segments),
            'approved_samples': int(emg['approved'].sum())}
        header = json.dumps(metadata, separators=(',', ':'), allow_nan=False).encode()
        prefix = b'EMGTRIAL' + struct.pack('<II', 1, len(header))
        padding = b'\0' * (-(len(prefix)+len(header)) % 8)
        return b''.join([prefix, header, padding,
            emg['seconds'].astype('<f8', copy=False).tobytes(),
            values.astype('<f4', copy=False).tobytes()])

    def emg_window(self, start, end, bins, unit):
        if unit != 'microvolts' or not (math.isfinite(start) and math.isfinite(end)):
            raise ValueError('Invalid EMG unit or time range')
        if end <= start or end - start > 32:
            raise ValueError('EMG requests must span more than zero and at most 32 seconds')
        bins = max(16, min(2000, bins))
        emg = self.emg()
        lo, hi = np.searchsorted(emg['seconds'], [start, end], side='left')
        n = int(hi - lo)
        if not n:
            return {'unit': unit, 'source': self.emg_source, 'start': start, 'end': end,
                'samples': 0, 'filter_valid_samples': 0, 'filter_valid_fraction': [],
                'time': [], 'min': [], 'max': [], 'line_segments': []}
        edges = np.linspace(lo, hi, min(n, bins) + 1, dtype=np.int64)
        values = emg['microvolts_filtered'][lo:hi]
        usable = emg['filter_valid'][lo:hi] & np.isfinite(values).all(axis=1)
        offsets = edges[:-1] - lo
        mins = np.minimum.reduceat(np.where(usable[:, None], values, np.inf), offsets, axis=0)
        maxs = np.maximum.reduceat(np.where(usable[:, None], values, -np.inf), offsets, axis=0)
        filter_fraction = np.add.reduceat(usable.astype(np.int64), offsets) / np.diff(edges)
        centers = (emg['seconds'][edges[:-1]] + emg['seconds'][edges[1:] - 1]) / 2
        approval = np.add.reduceat(emg['approved'][lo:hi].astype(np.int64), offsets) / np.diff(edges)
        runs_min = np.minimum.reduceat(emg['run_id'][lo:hi], offsets)
        runs_max = np.maximum.reduceat(emg['run_id'][lo:hi], offsets)
        return clean({
            'unit': unit, 'start': start, 'end': end, 'samples': n, 'sample_start': int(lo), 'sample_stop': int(hi),
            'approved_samples': int(emg['approved'][lo:hi].sum()),
            'source': self.emg_source, 'filter_valid_samples': int(usable.sum()),
            'filter_valid_fraction': filter_fraction,
            'run_ids': np.unique(emg['run_id'][lo:hi]).tolist(), 'time': centers,
            'min': mins.T, 'max': maxs.T, 'approved_fraction': approval,
            'run_id': np.where(runs_min == runs_max, runs_min, -1),
            'line_segments': emg_line_segments(emg, lo, hi, bins),
        })

    def frame(self, index):
        if not 0 <= index < self.n:
            raise ValueError('Frame index is outside this trial')
        row = clean(self.frames.iloc[index].to_dict())
        # Exact ns values are strings so no future dataset with larger clocks
        # can lose precision when JSON is parsed by JavaScript.
        for key in row:
            if key.endswith('_ns') and row[key] is not None:
                row[key] = str(row[key])
        emg = self.emg()
        stop_ns = (int(self.frames.host_time_ns.iloc[index + 1]) if index + 1 < self.n
                   else int(self.meta['event_done_host_ns']))
        lo, hi = np.searchsorted(emg['times_ns'], [int(row['host_time_ns']), stop_ns]).tolist()
        details = {'source': self.emg_source, 'sample_range': [lo, hi], 'samples': hi-lo,
            'filter_valid_samples': int(emg['filter_valid'][lo:hi].sum()),
            'approved_samples': int(emg['approved'][lo:hi].sum()), 'run_ids': np.unique(emg['run_id'][lo:hi]).tolist()}
        if lo < hi:
            details['first_sample'] = {k: clean(v[lo]) for k, v in emg.items() if k != 'seconds'}
            details['first_sample']['times_ns'] = str(details['first_sample']['times_ns'])
        imu = self.camera_imu()
        # Capture association is explicit; a batch can straddle the exposure time.
        imu_lo, imu_hi = np.searchsorted(imu['parents'], [index, index + 1]).tolist()
        imu_details = {
            'source': self.imu_source['path'], 'units': self.imu_source['units'],
            'channel_order': self.imu_source['channel_order'],
            'parent_frame_index': index, 'sample_range': [imu_lo, imu_hi],
            'samples': imu_hi - imu_lo,
            'measurements': [{'host_time_ns': str(int(imu['times_ns'][i])),
                'offset_from_exposure_ms': (int(imu['times_ns'][i]) - int(row['host_time_ns'])) / 1e6,
                'raw_counts': imu['raw_counts'][i].tolist()} for i in range(imu_lo, imu_hi)],
        }
        return {'frame': row, 'emg': details, 'camera_imu': imu_details}



class Store:
    def __init__(self, root, cache_size=2):
        self.root = Path(root).resolve()
        self.info = json.loads((self.root / 'meta/info.json').read_text())
        self.trials = {int(r['episode_index']): r for r in pq.read_table(self.root / 'meta/trials.parquet').to_pylist()}
        self.episodes = {}
        for path in sorted((self.root / 'meta/episodes').rglob('*.parquet')):
            for r in pq.read_table(path).to_pylist():
                if r['episode_index'] in self.episodes:
                    raise ValueError('Duplicate episode ID')
                self.episodes[int(r['episode_index'])] = r
        if set(self.trials) != set(self.episodes):
            raise ValueError('Trial IDs differ from episode index')
        for idx, r in self.trials.items():
            ep = self.episodes[idx]
            r['frames'] = ep['length']
            r['emg_path'] = 'sensors/emg/chunk-{:03d}/file-{:03d}.parquet'.format(
                ep['data/chunk_index'], ep['data/file_index'])
        self.calibrations = {r['calibration_id']: json.loads(r['profile_json'])
            for r in pq.read_table(self.root / 'meta/calibrations.parquet').to_pylist()}
        self.imu_references = {r['calibration_id']: json.loads(r['parameters_json'])
            if r['parameters_json'] is not None else None
            for r in pq.read_table(self.root / 'meta/camera_imu_reference.parquet').to_pylist()}
        self.tasks = pq.read_table(self.root / 'meta/tasks.parquet').to_pylist()
        self.cache_size = cache_size
        self.cache = OrderedDict()
        self.lock = threading.RLock()
        # Resolve all paths now, including the EMG files, so unavailable trials
        # fail at startup instead of producing partial interfaces later.
        for idx, ep in self.episodes.items():
            self.resolve(self.info['data_path'].format(chunk_index=ep['data/chunk_index'], file_index=ep['data/file_index']))
            self.emg_path(idx)
            self.camera_imu_path(idx)
            if self.trials[idx]['calibration_id'] not in self.calibrations:
                raise ValueError(f'Trial {idx}: missing calibration')
            if self.trials[idx]['calibration_id'] not in self.imu_references:
                raise ValueError(f'Trial {idx}: missing camera IMU reference row')
            for eye in ['left', 'right']:
                self.video_path(idx, eye)

    def resolve(self, path):
        resolved = (self.root / path).resolve()
        if not resolved.is_relative_to(self.root) or not resolved.is_file():
            raise FileNotFoundError(f'Missing or invalid dataset path: {path}')
        return resolved

    def emg_path(self, trial_id):
        # This path is derived from episode chunk/file indices at startup.
        return self.resolve(self.trials[trial_id]['emg_path'])

    def camera_imu_path(self, trial_id):
        ep = self.episodes[trial_id]
        return self.resolve('data/camera_imu/chunk-{:03d}/file-{:03d}.parquet'.format(
            ep['data/chunk_index'], ep['data/file_index']))

    def get(self, trial_id):
        if trial_id not in self.trials:
            raise KeyError('Unknown trial')
        with self.lock:
            if trial_id not in self.cache:
                self.cache[trial_id] = Trial(self, trial_id)
            self.cache.move_to_end(trial_id)
            while len(self.cache) > self.cache_size:
                self.cache.popitem(last=False)
            return self.cache[trial_id]

    def video_path(self, trial_id, eye):
        if eye not in ['left', 'right'] or trial_id not in self.episodes:
            raise KeyError('Unknown video')
        ep = self.episodes[trial_id]
        key = f'observation.images.{eye}'
        return self.resolve(self.info['video_path'].format(video_key=key,
            chunk_index=ep[f'videos/{key}/chunk_index'], file_index=ep[f'videos/{key}/file_index']))

    def catalog(self):
        return clean({'fps': self.info['fps'], 'tasks': self.tasks, 'trials': [
            {**r, 'duration': r['frames'] / self.info['fps'],
                'date': r['recording'].split('/')[0],
                'event_start_host_ns': str(r['event_start_host_ns']), 'event_done_host_ns': str(r['event_done_host_ns'])}
            for _, r in sorted(self.trials.items())]})


def parse_range(header, size):
    if header is None:
        return 0, size-1, False
    match = re.fullmatch(r'bytes=(\d*)-(\d*)', header.strip())
    if not match or not any(match.groups()):
        raise ValueError('Only a single byte range is supported')
    first, last = match.groups()
    if not first:
        count = int(last)
        if count <= 0:
            raise ValueError('Empty suffix range')
        start, end = max(0, size-count), size-1
    else:
        start, end = int(first), min(int(last), size-1) if last else size-1
    if start >= size or end < start:
        raise ValueError('Range outside file')
    return start, end, True


class Handler(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'

    def __init__(self, *args, store, **kwargs):
        self.store = store
        super().__init__(*args, **kwargs)

    def handle(self):
        # Rapid scrubbing/trial changes intentionally cancel browser requests,
        # including idle HTTP/1.1 keep-alive connections.
        try:
            super().handle()
        except (BrokenPipeError, ConnectionResetError):
            self.close_connection = True

    def log_message(self, fmt, *args):
        if len(args) < 2 or str(args[1]) not in ['200', '206']:
            super().log_message(fmt, *args)

    def send_bytes(self, body, mime, status=200, extra=None):
        self.send_response(status)
        self.send_header('Content-Type', mime)
        self.send_header('Content-Length', str(len(body)))
        self.send_header('Cache-Control', 'no-cache')
        self.send_header('X-Content-Type-Options', 'nosniff')
        for key, value in (extra or {}).items():
            self.send_header(key, value)
        self.end_headers()
        if self.command != 'HEAD':
            self.wfile.write(body)

    def send_json(self, data, status=200):
        body = json.dumps(clean(data), separators=(',', ':'), allow_nan=False).encode()
        extra = {}
        if 'gzip' in self.headers.get('Accept-Encoding', '') and len(body) > 2048:
            body = gzip.compress(body, compresslevel=3)
            extra = {'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding'}
        self.send_bytes(body, 'application/json; charset=utf-8', status, extra)

    def send_video(self, path):
        size = path.stat().st_size
        try:
            start, end, partial = parse_range(self.headers.get('Range'), size)
        except ValueError:
            self.send_bytes(b'', 'video/mp4', 416, {'Content-Range': f'bytes */{size}', 'Accept-Ranges': 'bytes'})
            return
        self.send_response(206 if partial else 200)
        self.send_header('Content-Type', 'video/mp4')
        self.send_header('Content-Length', str(end-start+1))
        self.send_header('Accept-Ranges', 'bytes')
        self.send_header('Cache-Control', 'private, max-age=3600')
        if partial:
            self.send_header('Content-Range', f'bytes {start}-{end}/{size}')
        self.end_headers()
        if self.command != 'HEAD':
            with path.open('rb') as handle:
                handle.seek(start)
                remaining = end-start+1
                while remaining:
                    chunk = handle.read(min(1024*1024, remaining))
                    if not chunk:
                        break
                    self.wfile.write(chunk)
                    remaining -= len(chunk)

    def do_HEAD(self):
        self.do_GET()

    def do_GET(self):
        try:
            url = urlsplit(self.path)
            path = url.path
            static = {'/': ('index.html', 'text/html; charset=utf-8'),
                '/index.html': ('index.html', 'text/html; charset=utf-8'),
                '/app.js': ('app.js', 'text/javascript; charset=utf-8'),
                '/style.css': ('style.css', 'text/css; charset=utf-8')}
            if path in static:
                name, mime = static[path]
                self.send_bytes((HERE / name).read_bytes(), mime)
            elif path == '/api/trials':
                self.send_json(self.store.catalog())
            elif path == '/favicon.ico':
                self.send_bytes(b'', 'image/x-icon', 204)
            elif match := re.fullmatch(r'/media/(\d+)/(left|right)', path):
                self.send_video(self.store.video_path(int(match[1]), match[2]))
            elif match := re.fullmatch(r'/api/trial/(\d+)/emg/full', path):
                self.send_bytes(self.store.get(int(match[1])).emg_full(), 'application/octet-stream')
            elif match := re.fullmatch(r'/api/trial/(\d+)(?:/(emg|frame)(?:/(\d+))?)?', path):
                trial = self.store.get(int(match[1]))
                if match[2] == 'emg':
                    q = parse_qs(url.query)
                    get = lambda key, default: q.get(key, [default])[0]
                    self.send_json(trial.emg_window(float(get('start', '-2')), float(get('end', '2')),
                        int(get('bins', '1500')), get('unit', 'microvolts')))
                elif match[2] == 'frame' and match[3] is not None:
                    self.send_json(trial.frame(int(match[3])))
                elif match[2] is None:
                    self.send_json(trial.payload())
                else:
                    self.send_json({'error': 'Invalid endpoint'}, 404)
            else:
                self.send_json({'error': 'Not found'}, 404)
        except (BrokenPipeError, ConnectionResetError):
            pass
        except (KeyError, FileNotFoundError) as exc:
            self.send_json({'error': str(exc)}, 404)
        except ValueError as exc:
            self.send_json({'error': str(exc)}, 400)
        except Exception as exc:
            import traceback
            traceback.print_exc()
            self.send_json({'error': f'{type(exc).__name__}: {exc}'}, 500)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=HERE.parent)
    parser.add_argument('--port', type=int, default=8023, help='Use 0 for an available ephemeral port')
    args = parser.parse_args()
    store = Store(args.root)
    server = ThreadingHTTPServer(('127.0.0.1', args.port), partial(Handler, store=store))
    server.daemon_threads = True
    print(f'EMGSuite visualizer: http://127.0.0.1:{server.server_port}/', flush=True)
    print(f'{len(store.trials)} trials; source dataset read-only; two-trial memory cache.', flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.server_close()


if __name__ == '__main__':
    main()