"""Prepare benchmark frames and export model inputs. No network access. Source media must have been obtained with appropriate rights. """ import argparse import json import os import shutil import subprocess import tempfile from pathlib import Path def safe_path(root, relative): value = Path(relative) if value.is_absolute() or '..' in value.parts: raise ValueError(f'Unsafe relative path: {relative}') result = (root / value).resolve() if not result.is_relative_to(root.resolve()): raise ValueError(f'Path escapes root: {relative}') return result def check_sample(root, row): return [f for f in row['frames'] if not safe_path(root, f['expected_path']).is_file()] def import_frames(root, source_root, row, missing): copied = 0 for frame in missing: relative = frame['expected_path'] options = [safe_path(source_root, relative), safe_path(source_root, row['sample_id'] + '/' + Path(relative).name)] src = next((p for p in options if p.is_file()), None) if src is None: continue dst = safe_path(root, relative); dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists(): raise ValueError(f'Refusing to overwrite {relative}') with tempfile.NamedTemporaryFile(dir=dst.parent, delete=False) as tmp: tmp_path = Path(tmp.name) try: shutil.copyfile(src, tmp_path) tmp_path.replace(dst) finally: tmp_path.unlink(missing_ok=True) copied += 1 return copied def reconstruct(root, row, files_by_name, ffmpeg): recipe = row.get('reconstruction') if not recipe or recipe['method'] != 'ffmpeg_fps4_q2': return 0, 'No extraction recipe' # The recorded window uses the upstream file timeline, which may already be a clip. candidates = list(files_by_name.get(recipe['source_filename'], [])) candidates += files_by_name.get(row['sample_id'] + '.mp4', []) candidates = sorted({p.resolve() for p in candidates}) if not candidates: return 0, 'Upstream filename not found' if len(candidates) > 1: return 0, 'Multiple source files match; keep one candidate for this sample' source = candidates[0] if not shutil.which(ffmpeg): return 0, 'ffmpeg is not installed' with tempfile.TemporaryDirectory(prefix='verus-frames-') as temp: output = Path(temp) command = [ffmpeg, '-nostdin', '-hide_banner', '-loglevel', 'error', '-threads', '1', '-ss', f"{recipe['start_seconds']:.3f}", '-i', str(source), '-vf', 'fps=4,tpad=stop_mode=clone:stop_duration=0.25', '-frames:v', str(len(row['frames'])), '-q:v', '2', str(output / 'frame_%04d.jpg')] completed = subprocess.run(command, capture_output=True, text=True) if completed.returncode: return 0, 'ffmpeg extraction failed: ' + completed.stderr[-500:] generated = sorted(output.glob('frame_*.jpg')) if len(generated) != len(row['frames']): return 0, 'Frame count mismatch' count = 0 for src, f in zip(generated, row['frames']): dst = safe_path(root, f['expected_path']) if dst.exists(): if not dst.is_file(): raise ValueError('Frame destination is not a file') continue dst.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(src, dst); count += 1 return count, 'Frames extracted using the recorded recipe' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--dataset-root', type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument('--frames-root', type=Path, help='Lawfully obtained benchmark frames or full local bundle') parser.add_argument('--source-media-root', type=Path, help='Lawfully obtained upstream videos; matched by filename') parser.add_argument('--ffmpeg', default='ffmpeg') parser.add_argument('--write-inputs', help='Write model inputs when all expected frame paths exist') parser.add_argument('--available-only', action='store_true', help='Explicitly export only complete samples; this is a partial benchmark') parser.add_argument('--check', action='store_true', help='List missing frame paths without changing data') args = parser.parse_args() if args.check and (args.frames_root or args.source_media_root or args.write_inputs or args.available_only): parser.error('--check cannot import data') if args.available_only and not args.write_inputs: parser.error('--available-only requires --write-inputs') root = args.dataset_root.resolve() rows = [json.loads(line) for line in (root / 'metadata/frames.jsonl').read_text().splitlines()] if len(rows) != 192 or len({r['sample_id'] for r in rows}) != 192: raise ValueError('Expected 192 unique frame-index records') index = {} if args.source_media_root: if not args.source_media_root.is_dir(): parser.error('Source media directory does not exist') for p in args.source_media_root.rglob('*'): if p.is_file(): index.setdefault(p.name, []).append(p) if args.frames_root and not args.frames_root.is_dir(): parser.error('Frames directory does not exist') summary = dict(expected_samples=len(rows), expected_frames=sum(len(r['frames']) for r in rows), resolved=0, missing=0, copied_frames=0, generated_frames=0, skipped=0) for row in rows: missing = check_sample(root, row) if not missing: summary['resolved'] += 1; summary['skipped'] += 1; continue if args.frames_root: summary['copied_frames'] += import_frames(root, args.frames_root.resolve(), row, missing) missing = check_sample(root, row) if missing and args.source_media_root: count, reason = reconstruct(root, row, index, args.ffmpeg) summary['generated_frames'] += count print(row['sample_id'], reason) missing = check_sample(root, row) if missing: summary['missing'] += 1 print(row['sample_id'], 'MISSING', len(missing), 'frames') else: summary['resolved'] += 1 print(json.dumps(summary, indent=2)) if args.write_inputs and (summary['resolved'] == len(rows) or args.available_only): output = safe_path(root, args.write_inputs) if output.exists(): raise ValueError('Refusing to overwrite existing input file') selected = [r for r in rows if not check_sample(root, r)] if not selected: raise ValueError('No complete samples to export') output.parent.mkdir(parents=True, exist_ok=True) records = [dict(sample_id=r['sample_id'], images=[Path(os.path.relpath(safe_path(root, f['expected_path']), output.parent)).as_posix() for f in r['frames']], timestamps=[f['timestamp_seconds'] for f in r['frames']]) for r in selected] with output.open('x', encoding='utf-8') as handle: handle.write(''.join(json.dumps(r) + '\n' for r in records)) print(json.dumps(dict(exported_samples=len(records), total_samples=len(rows), coverage='full' if len(records) == len(rows) else 'partial'))) return 0 return 0 if summary['resolved'] == len(rows) else 2 if __name__ == '__main__': raise SystemExit(main())