Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
robotics
embodied-ai
human-demonstration
egocentric-video
bimanual-manipulation
tactile-sensing
License:
File size: 23,071 Bytes
d4159be | 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 | """Read-only customer library with bounded resident previews and background loading.
The source tree is never used as an output directory. All generated files live in
player-cache/customer beneath this independent player copy.
"""
import argparse
from collections import Counter, OrderedDict
from contextlib import redirect_stdout, redirect_stderr
import json
import os
import queue
from pathlib import Path
import socket
import subprocess
import sys
import time
import traceback
from urllib.parse import urlencode
import cv2
import h5py
import numpy as np
import pyarrow.parquet as pq
import rerun as rr
from rerun.chunk import RrdReader
from loom_viewer import ROOT, CAMERAS, convert, layout
from viewer_control import ViewerControl
CACHE = ROOT / 'player-cache/customer'
VERSION = 'english-library-1'
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
temporary.replace(path)
def snapshot(directory):
# Sizes and timestamps suffice for cache invalidation; never hash the videos.
return {p.relative_to(directory).as_posix(): [s.st_size, s.st_mtime_ns]
for p in sorted(directory.rglob('*')) if p.is_file() for s in [p.stat()]}
def cache_input_mismatches(actual, expected):
"""Validate immutable delivery inputs without depending on transfer timestamps.
Cache identity is established separately by the episode UUID and frame count.
File mtimes are provenance only: ZIP/exFAT/network copies can change precision.
This is a size/presence check, not a content checksum.
"""
if not isinstance(expected, dict) or not expected:
return ['cache has no input inventory']
errors = []
for name, recorded in expected.items():
current = actual.get(name)
if current is None:
errors.append(f'missing input: {name}')
elif not isinstance(recorded, (list, tuple)) or not recorded:
errors.append(f'invalid input inventory: {name}')
elif current[0] != recorded[0]:
errors.append(f'input size differs: {name} (expected {recorded[0]}, got {current[0]})')
return errors
def validate_display_cache(cache, frames, inputs):
directory = Path(cache) / 'display-v1'
for name in ['manifest.json', 'world.json.gz', 'tactile.json.gz']:
if not (directory / name).is_file():
raise ValueError(f'Missing compact display cache: {directory / name}. Copy player/runtime/cache with the data.')
manifest = json.loads((directory / 'manifest.json').read_text(encoding='utf-8'))
if manifest.get('frames') != frames:
raise ValueError(f'Display cache frame count differs: {directory}')
errors = cache_input_mismatches(inputs, manifest.get('inputs'))
if errors:
raise ValueError(f'Display cache inputs differ: {directory}: {"; ".join(errors[:3])}')
return manifest
def find_mano_cache(cache_root, episode_uuid, frames, inputs):
candidates = sorted(Path(cache_root).glob(episode_uuid + '-*/native-skin-v1/index.json'))
if not candidates:
raise ValueError(f'MANO cache missing for episode {episode_uuid} under {cache_root}. '
'Copy the complete player/runtime/cache folder together with data.')
problems = []
compatible = []
for candidate in candidates:
try:
index = json.loads(candidate.read_text(encoding='utf-8'))
if index.get('format') != 'SKQ1' or index.get('frames') != frames:
raise ValueError('MANO cache format or frame count differs')
errors = cache_input_mismatches(inputs, index.get('inputs'))
if errors:
raise ValueError('; '.join(errors[:3]))
chunk_size = index.get('chunk_size', 0)
if not isinstance(chunk_size, int) or chunk_size <= 0:
raise ValueError('Invalid MANO chunk size')
segments = (frames + chunk_size - 1) // chunk_size
if index.get('segments') != segments:
raise ValueError('MANO segment count differs')
required = ['topology.bin.gz'] + [f'segment-{i:04d}.bin.gz' for i in range(segments)]
missing = [name for name in required if not (candidate.parent / name).is_file()]
if missing:
raise ValueError(f'MANO cache incomplete: {missing[:3]}. Copy the complete player/runtime/cache folder.')
validate_display_cache(candidate.parent.parent, frames, inputs)
exact = all(inputs.get(k) == v for k, v in index['inputs'].items())
compatible.append((exact, candidate.parent))
except (OSError, ValueError, TypeError) as error:
problems.append(f'{candidate.parent}: {error}')
if not compatible:
raise ValueError('Prepared cache does not match this episode: ' + ' | '.join(problems[:2]))
# If several revisions were supplied, prefer the original exact provenance.
exact = [path for matches, path in compatible if matches]
if exact:
return exact[0]
if len(compatible) != 1:
raise ValueError(f'Multiple prepared cache revisions for episode {episode_uuid}; '
'retain the cache supplied with this dataset.')
return compatible[0][1]
def discover(data_root, scene=None):
data_root = Path(data_root).resolve(strict=True)
if CACHE.resolve().is_relative_to(data_root):
raise ValueError('The player cache must be outside the source data directory')
items, problems = [], []
metadata_paths = [*data_root.glob('*/ep_*/meta/metadata.json'),
*data_root.glob('*/task_*/ep_*/meta/metadata.json')]
for metadata in sorted(metadata_paths):
ep = metadata.parent.parent
parts = ep.relative_to(data_root).parts
scene_name, episode = parts[0], parts[-1]
task = parts[1] if len(parts) == 3 else ''
if scene and scene != scene_name:
continue
try:
meta = json.loads(metadata.read_text(encoding='utf-8'))
sync = pq.read_table(ep / 'meta/timeline/sync.parquet',
columns=['frame_idx', 'master_ts']).to_pydict()
n = len(sync['frame_idx'])
if n < 2 or n != meta['frame_count'] or not np.all(np.diff(sync['master_ts']) > 0):
raise ValueError('Invalid frame timeline')
files = snapshot(ep)
required = [f'camera/{camera}.mp4' for camera in CAMERAS]
required += ['annotations/auto_actions.json', 'meta/world_motion.json',
'meta/devices/cameras/head_RGB.json', 'meta/devices/extrinsics.json']
missing = [p for p in required if p not in files]
if missing:
raise ValueError(f'Missing files: {missing}')
for path, keys in {
'world_pose/world_motion.h5': ['left_world_m', 'right_world_m',
'head_position_m', 'head_quaternion_xyzw', 'hand_anchor_m'],
'imu/head_imu.h5': ['aligned/orientation'],
'head_depth/head_depth.h5': ['depth'],
'tactile/left.h5': ['adc'], 'tactile/right.h5': ['adc'],
'mocap/left.h5': ['skeleton'], 'mocap/right.h5': ['skeleton'],
}.items():
with h5py.File(ep / path, 'r') as handle:
if any(len(handle[key]) != n for key in keys):
raise ValueError(f'Frame count mismatch: {path}')
mesh = find_mano_cache(data_root.parent / 'player/runtime/cache', meta['episode_uuid'], n, files)
item = dict(scene=scene_name, task=task, episode=episode, local=str(ep),
key=ep.relative_to(data_root).as_posix(), frames=n,
second_time=sync['master_ts'][1], second_frame=sync['frame_idx'][1],
end_time=sync['master_ts'][-1], end_frame=sync['frame_idx'][-1],
mesh_cache=str(mesh), inputs=files, mesh_inputs=snapshot(mesh))
items.append(item)
except Exception as error:
problems.append(dict(episode=str(ep), error=str(error)))
if not items:
raise RuntimeError(f'No compatible episodes found in {data_root}: {problems[:3]}')
tasks = {}
for item in items:
tasks.setdefault(item['scene'], set()).add(item['task'])
for item in items:
suffix = ' - ' + (item['task'] or 'Direct') if len(tasks[item['scene']]) > 1 else ''
item['application'] = 'LoomG2 - ' + item['scene'].title() + suffix
write_json(CACHE / 'catalog.json', dict(source=str(data_root), version=VERSION,
counts=dict(Counter(i['scene'] for i in items)), items=items, unavailable=problems))
return items, problems
def store_id(item):
return f"Recording:{item['application']}:{item['episode']}"
def location(item):
return 'about:recording?' + urlencode(dict(app_id=item['application'], recording_id=item['episode']))
def cached_path(item):
return CACHE / item['key'] / (item['episode'] + '.rrd')
def provenance(item):
return dict(version=VERSION, source=item['local'], inputs=item['inputs'], mesh_inputs=item['mesh_inputs'])
def cache_valid(item):
output = cached_path(item)
try:
return output.is_file() and json.loads(output.with_suffix('.cache.json').read_text(
encoding='utf-8')) == provenance(item)
except (OSError, ValueError):
return False
def register(item, url, blueprint=False, message=None):
rec = rr.RecordingStream(item['application'], recording_id=item['episode'])
rec.connect_grpc(url, default_blueprint=layout() if blueprint else None)
rec.send_recording_name(item['episode'])
for relative in item['inputs']:
rec.log('__directory/' + item['episode'] + '/' + relative,
rr.TextDocument(relative), static=True)
# Keep the true time extent available while loading, without inventing modality events.
for t, frame in [(item['second_time'], item['second_frame']), (item['end_time'], item['end_frame'])]:
rec.set_time('time', duration=float(t))
rec.set_time('frame', sequence=int(frame))
rec.log('__library/extent', rr.TextDocument('Episode'))
rec.set_time('time', duration=float(item['second_time']))
rec.set_time('frame', sequence=int(item['second_frame']))
preview = np.zeros((480, 640, 3), dtype=np.uint8)
cv2.putText(preview, item['scene'].title() + ' / ' + item['episode'], (32, 220),
cv2.FONT_HERSHEY_SIMPLEX, .8, (210, 210, 210), 1, cv2.LINE_AA)
cv2.putText(preview, message or 'Loading episode...', (32, 263),
cv2.FONT_HERSHEY_SIMPLEX, .65, (155, 155, 155), 1, cv2.LINE_AA)
# A separate static entity avoids masking cached RGB frames whose row IDs are older
# than this session's placeholder, and contributes no fake frame dots to STREAMS.
rec.log('data/video/head_RGB/__loading', rr.Image(preview).compress(jpeg_quality=80), static=True)
rec.flush()
rec.disconnect()
def worker(item, url):
output = cached_path(item)
status = rr.RecordingStream(item['application'], recording_id=item['episode'], send_properties=False)
status.connect_grpc(url)
status.log('data/video/head_RGB/__loading', rr.EncodedImage.from_fields(clear_unset=True), static=True)
status.flush()
status.disconnect()
if cache_valid(item):
rec = rr.RecordingStream(item['application'], recording_id=item['episode'], send_properties=False)
rec.connect_grpc(url)
rec.send_chunks(RrdReader(output).store())
rec.flush()
rec.disconnect()
print('CACHED', item['key'], flush=True)
else:
convert(item, True, output=output, mesh_cache=item['mesh_cache'], stream_url=url)
# Detect edits by another program during conversion; never cache a mixed input version.
if snapshot(Path(item['local'])) != item['inputs'] or snapshot(Path(item['mesh_cache'])) != item['mesh_inputs']:
raise RuntimeError('Source changed while loading; reopen the library to rescan')
write_json(output.with_suffix('.cache.json'), provenance(item))
def set_initial_cursor(control, item):
control.call('rerun_set_time_cursor', dict(store_id=store_id(item),
timeline=dict(name='time'), time=dict(time=round(item['second_time'] * 1e9)),
play_state='PLAY_STATE_PAUSED'))
def resident_budget():
"""Reserve at most a quarter of physical RAM, capped at 8 GiB, for previews."""
import ctypes
class MemoryStatus(ctypes.Structure):
_fields_ = [('length', ctypes.c_ulong), ('load', ctypes.c_ulong)] + [
(name, ctypes.c_ulonglong) for name in
['total', 'available', 'page_total', 'page_available', 'virtual_total', 'virtual_available', 'extended']]
status = MemoryStatus()
status.length = ctypes.sizeof(status)
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
return min(8 * 1024**3, max(512 * 1024**2, status.total // 4))
return 2 * 1024**3
def resident_cost(item):
# Allow for decoded arrays, query caches and GPU copies in addition to the RRD.
output = cached_path(item)
size = output.stat().st_size if output.exists() else item['frames'] * 650_000
return max(64 * 1024**2, size * 4)
def recording_label(item, url, suffix=''):
rec = rr.RecordingStream(item['application'], recording_id=item['episode'], send_properties=False)
rec.connect_grpc(url)
rec.send_recording_name(item['episode'] + suffix)
rec.flush()
rec.disconnect()
def serve(data_root, scene=None):
items, problems = discover(data_root, scene)
print(f'Library: {len(items)} episodes; unavailable: {len(problems)}', flush=True)
if problems:
# Do not silently pretend the entire library loaded.
raise RuntimeError(f'{len(problems)} episodes failed validation; see player-cache/customer/catalog.json')
with socket.socket() as listener:
listener.bind(('127.0.0.1', 0))
port = listener.getsockname()[1]
url = f'rerun+http://127.0.0.1:{port}/proxy'
viewer_log = (CACHE / 'viewer.log').open('w', encoding='utf-8')
viewer = subprocess.Popen([str(ROOT / 'native-player/rerun.exe'), '--bind', '127.0.0.1',
'--port', str(port), '--memory-limit', '80%'],
stdout=viewer_log, stderr=viewer_log,
creationflags=subprocess.CREATE_NO_WINDOW)
control = None
jobs = {}
resident = OrderedDict()
failed = set()
modes = {}
budget = resident_budget()
last_status = None
current = None
try:
control = ViewerControl(port)
initialized_apps = set()
for item in items:
register(item, url, blueprint=item['application'] not in initialized_apps)
initialized_apps.add(item['application'])
control.call('rerun_set_location', dict(location=location(items[0])))
lookup = {store_id(item): item for item in items}
# Resident entries survive selection changes. Only memory-budget eviction unloads them.
cursors = {}
write_json(CACHE / 'session.json', dict(port=port, viewer_pid=viewer.pid,
loader_pid=os.getpid(), count=len(items), source=str(data_root)))
def unload(item, open_ids):
resident.pop(item['key'], None)
if store_id(item) in open_ids:
control.call('rerun_close', dict(store_ids=dict(store_ids=[store_id(item)])))
register(item, url)
if current:
control.call('rerun_set_location', dict(location=location(current)))
def trim(open_ids, reserve=0):
# Never evict the selected episode or an in-progress conversion.
while sum(entry['cost'] for entry in resident.values()) + reserve > budget:
victim = next((entry['item'] for key, entry in resident.items()
if key not in jobs and (current is None or key != current['key'])), None)
if victim is None:
break
print('EVICT', victim['key'], 'memory budget', flush=True)
unload(victim, open_ids)
while viewer.poll() is None:
try:
state = control.call('rerun_get_state')
except (RuntimeError, queue.Empty):
try:
viewer.wait(timeout=2)
break
except subprocess.TimeoutExpired:
raise
active = state.get('active_store_id')
selected = lookup.get(active)
open_ids = {r['store_id'] for r in state.get('recordings', [])}
# Finish jobs before processing a new selection, including jobs for background episodes.
for key, job in list(jobs.items()):
code = job['process'].poll()
if code is None:
continue
job['log'].close()
del jobs[key]
item = job['item']
if code == 0 and store_id(item) in open_ids:
resident[key] = dict(item=item, signature=job['signature'], cost=resident_cost(item))
recording_label(item, url)
print('READY', key, job['mode'], flush=True)
elif code:
failed.add(key)
print('ERROR', key, code, 'see its load.log', flush=True)
register(item, url, message='Unable to load. Select another episode to retry.')
recording_label(item, url, ' (Load failed)')
for key, entry in list(resident.items()):
if store_id(entry['item']) not in open_ids:
del resident[key]
for recording in state.get('recordings', []):
if current and recording['store_id'] == store_id(current):
time_value = recording.get('current_time', {})
if 'time' in time_value:
cursors[recording['store_id']] = time_value
if selected and (current is None or selected['key'] != current['key']):
if current and store_id(current) in open_ids:
control.call('rerun_set_time_cursor', dict(store_id=store_id(current),
play_state='PLAY_STATE_PAUSED'))
current = selected
current['inputs'] = snapshot(Path(current['local']))
current['mesh_inputs'] = snapshot(Path(current['mesh_cache']))
key = current['key']
failed.discard(key)
if key in resident and resident[key]['signature'] != provenance(current):
unload(current, open_ids)
if key in resident:
resident.move_to_end(key)
modes[key] = 'memory'
print('REUSE', key, 'memory', flush=True)
if active in cursors:
cursor = cursors[active]
control.call('rerun_set_time_cursor', dict(store_id=active,
timeline=cursor['timeline'], time=cursor['time'],
play_state='PLAY_STATE_PAUSED'))
else:
set_initial_cursor(control, current)
if (current and current['key'] not in resident and current['key'] not in jobs
and current['key'] not in failed and store_id(current) in open_ids and len(jobs) < 2):
key = current['key']
trim(open_ids, reserve=resident_cost(current) + sum(j['cost'] for j in jobs.values()))
output = cached_path(current)
output.parent.mkdir(parents=True, exist_ok=True)
job_file = output.parent / 'load-job.json'
write_json(job_file, current)
child_log = (output.parent / 'load.log').open('w', encoding='utf-8')
mode = 'disk' if cache_valid(current) else 'conversion'
modes[key] = mode
recording_label(current, url, ' (Loading...)' if mode == 'disk' else ' (Preparing...)')
child = subprocess.Popen([str(ROOT / '.venv/Scripts/python.exe'),
str(ROOT / 'customer_library.py'), '--worker', str(job_file),
'--url', url], stdout=child_log, stderr=child_log,
env=dict(os.environ, PYTHONIOENCODING='utf-8'),
creationflags=subprocess.CREATE_NO_WINDOW)
jobs[key] = dict(process=child, log=child_log, item=current,
signature=provenance(current), mode=mode, cost=resident_cost(current))
print('LOAD', key, mode, flush=True)
trim(open_ids, reserve=sum(j['cost'] for j in jobs.values()))
if current:
key = current['key']
status = dict(state='ready' if key in resident else 'error' if key in failed
else 'loading' if key in jobs else 'queued', episode=key,
cache=str(cached_path(current)), source=modes.get(key),
resident=list(resident), loading=list(jobs), memory_budget_bytes=budget)
if status != last_status:
write_json(CACHE / 'status.json', status)
last_status = status
time.sleep(.3)
finally:
for job in jobs.values():
if job['process'].poll() is None:
job['process'].terminate()
job['process'].wait(timeout=10)
job['log'].close()
if control:
control.close()
viewer_log.close()
def run_library(data_root, scene=None):
CACHE.mkdir(parents=True, exist_ok=True)
with (CACHE / 'loader.log').open('w', encoding='utf-8', buffering=1) as log:
with redirect_stdout(log), redirect_stderr(log):
try:
from compact_player import serve as serve_compact
serve_compact(data_root, scene)
except Exception:
traceback.print_exc()
import ctypes
ctypes.windll.user32.MessageBoxW(None,
f'Unable to load the data library.\nSee {CACHE / "loader.log"}',
'LoomG2 Player', 0x10)
raise
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--worker', type=Path, required=True)
parser.add_argument('--url', required=True)
args = parser.parse_args()
worker(json.loads(args.worker.read_text(encoding='utf-8')), args.url)
|