#!/usr/bin/env python3 """Prepare a portable clip-sized wm-proxy session from extracted metadata. Only stdlib is needed. This prepares inputs; rendering needs the bundled compiler. Recorded observations are copied unchanged. Output timestamps use the clip grid. """ import argparse import copy import json from pathlib import Path import sqlite3 from inspect_frame import resolve_source, rows def dump(path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n') def dump_rows(path, values): path.parent.mkdir(parents=True, exist_ok=True) with path.open('x', encoding='utf-8') as stream: for value in values: stream.write(json.dumps(value, ensure_ascii=False, separators=(',', ':')) + '\n') def prepare(index, source_root, alignment_file, output): if output.exists(): raise FileExistsError(f'Choose a new output directory: {output}') alignment = json.loads(alignment_file.read_text()) count = len(alignment['grid_ns']) if count != 124 or any(len(alignment[s]) != count for s in ('left', 'right')): raise ValueError('Expected two views with 124 source frame references') conn = sqlite3.connect(index.resolve().as_uri() + '?mode=ro', uri=True) conn.row_factory = sqlite3.Row source_frames = {} source_segments = {} episode_roots = set() episodes = set() for side in ('left', 'right'): source_frames[side] = [] for item in alignment[side]: row = conn.execute('SELECT * FROM frames WHERE frame_id=?', (item['frame_id'],)).fetchone() if row is None: raise ValueError(f'Missing frame {item["frame_id"]}') frame = dict(row) if frame['status'] != 'estimated_alignment': raise ValueError('Only usable aligned frames can be prepared') source_frames[side].append(frame) sid = frame['segment_id'] if sid not in source_segments: seg = dict(conn.execute('SELECT * FROM segments WHERE segment_id=?', (sid,)).fetchone()) segment_dir = resolve_source(source_root, seg['output_directory']) # Source files are in proxy decode order, regardless of legacy frame_index quirks. raw = list(rows(segment_dir / 'source_frames.jsonl')) aligned = list(rows(segment_dir / 'source_alignment.jsonl')) if len(raw) != seg['frame_count'] or len(aligned) != seg['frame_count']: raise ValueError(f'Source frame count mismatch for segment {sid}') source_segments[sid] = (seg, raw, aligned) episode_roots.add(segment_dir.parents[3]) episodes.add(seg['episode_id']) conn.close() if len(episode_roots) != 1 or len(episodes) != 1: raise ValueError('A clip must belong to exactly one episode') episode_root = episode_roots.pop() all_frames = source_frames['left'] + source_frames['right'] domains = {f['server_clock_domain'] for f in all_frames} if len(domains) != 1 or None in domains: raise ValueError('Expected a single known server clock domain') domain = domains.pop() low = min(f['server_time_estimate_ns'] for f in all_frames) - 4_000_000_000 high = max(f['server_time_estimate_ns'] for f in all_frames) + 600_000_000 required_ticks = {f['world_capture_tick'] for f in all_frames} world_rows = [r for r in rows(episode_root / '.spool/world_state.jsonl') if r.get('server_clock_domain') == domain and (low <= r.get('server_monotonic_ns', -1) <= high or r.get('sample_seq') in required_ticks)] if not required_ticks <= {r['sample_seq'] for r in world_rows}: raise ValueError('Required world snapshots missing; extract the complete episode metadata') clients = {} agents = [] for side in ('left', 'right'): agent_ids = {source_segments[f['segment_id']][0]['agent_id'] for f in source_frames[side]} if len(agent_ids) != 1: raise ValueError(f'Inconsistent camera ownership for {side}') agent = agent_ids.pop() agents.append(agent) selected = [] for record in rows(episode_root / '.spool/agents' / agent / 'client.jsonl'): if record.get('server_clock_domain') != domain: continue timestamp = record.get('server_time_estimate_ns') if timestamp is None: timestamp = record.get('server_broadcast_monotonic_ns') if (timestamp is not None and low <= timestamp <= high) or record.get('sample_seq_estimate') in required_ticks: selected.append(record) if not selected: raise ValueError(f'No context observations for {agent}') clients[agent] = selected output.mkdir(parents=True) manifest = {'schema_version': '0.1.0', 'episode_id': episodes.pop(), 'agent_ids': agents, 'video_fps': 24, 'resolution': [1280, 720], 'preserve_decoded_rgb_timing': True, 'alignment_scope': 'release_clip_original_source_frames_on_24fps_output_grid', 'preparation_note': 'Recorded states unchanged; new visualization input, not bit-identical replay.'} dump(output / 'manifest.json', manifest) dump_rows(output / '.spool/world_state.jsonl', world_rows) for side, agent in zip(('left', 'right'), agents): raw_output, aligned_output = [], [] for i, frame in enumerate(source_frames[side]): _, raw, aligned = source_segments[frame['segment_id']] pts = alignment['grid_ns'][i] - alignment['grid_ns'][0] for source, destination in [(raw, raw_output), (aligned, aligned_output)]: record = copy.deepcopy(source[frame['proxy_frame_index']]) record.update(frame_index=i, video_pts_ns=pts, rgb_encoded_pts_ns=pts, server_time_estimate_ns=frame['server_time_estimate_ns'], server_clock_domain=frame['server_clock_domain'], estimated_sample_seq=frame['world_capture_tick'], release_source_frame_id=frame['frame_id']) destination.append(record) folder = output / 'agents' / agent dump_rows(folder / 'frame_timestamps.jsonl', raw_output) dump_rows(folder / 'frame_timestamps.aligned.jsonl', aligned_output) dump_rows(output / '.spool/agents' / agent / 'client.jsonl', clients[agent]) summary = {'num_frames_per_view': count, 'agent_ids': agents, 'world_records': len(world_rows), 'client_records': {key: len(value) for key, value in clients.items()}, 'context_before_seconds': 4, 'context_after_seconds': 0.6, 'server_clock_domain': domain, 'raw_observations_modified': False} dump(output / 'preparation.json', summary) return summary def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--index', type=Path, required=True) parser.add_argument('--source-root', type=Path, required=True) parser.add_argument('--alignment', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() print(json.dumps(prepare(args.index, args.source_root, args.alignment, args.output), indent=2)) if __name__ == '__main__': main()