"""Cut the frame-exact clips that cropped recording views need, and write clips/index.json (np-review-clips/1). A prover row's ``recording_views`` (per view letter: observer, start_frame, end_frame_exclusive at 20 fps) say which part of a recording the question's seconds refer to. ``np_export --clips`` sends such a view as its clip and refuses a crop without one. This tool cuts exactly the clips the selected rows need, so the export can run: python3 tools/evaluation/cut_clips.py --questions /vout/*/groups.jsonl --videos \\ --out /clips-src [--sample-per-version N --seed S | --items-from items.jsonl] [--jobs 8] python3 tools/evaluation/np_export.py ... --clips /clips-src/clips/index.json Rows are selected with np_export's own sampler (same --sample-per-version / --seed / --items-from give the same rows). A view spanning the whole recording needs no clip. Clips go to ``/clips//__f-.mp4``, cut with the same ffmpeg settings as the review console (trim by frame, libx264 crf 18, 20 fps, bt709 tags), and each is checked to hold b-a frames. Re-running skips clips already in the index whose file still matches its sha256 and whose source recording still has the path, size and mtime it had when cut (a re-rendered source is cut again). Failures are listed under ``failed`` in the index (np_export refuses an index with failures) and exit 1. """ import argparse import concurrent.futures import hashlib import json import os import shutil import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import media # noqa: E402 import np_export # noqa: E402 FPS = 20 SCHEMA = 'np-review-clips/1' FFMPEG = os.environ.get('CLIP_FFMPEG') or ('/usr/bin/ffmpeg' if Path('/usr/bin/ffmpeg').exists() else 'ffmpeg') def clip_name(observer, start, end): return f'{observer}__f{start}-{end}.mp4' def sha256(path): h = hashlib.sha256() with open(path, 'rb') as fh: for chunk in iter(lambda: fh.read(1 << 20), b''): h.update(chunk) return h.hexdigest() def source_stat(path): st = Path(path).stat() return [st.st_size, st.st_mtime_ns] def frames_of(path): info = media.probe(path) return info['frame_count'] if info['frame_count'] is not None else round(info['duration_s'] * info['fps']) def wanted(question_files, videos, keep=None): """{(script_id, observer, a, b): source mp4} for every cropped view of the selected PASS rows.""" need, full = {}, {} for qf in question_files: qf = Path(qf) script_id = qf.parent.name with open(qf, encoding='utf-8') as fh: for n, line in enumerate(fh): if not line.strip() or (keep is not None and (str(qf), n) not in keep): continue row = json.loads(line) if row.get('decision', {}).get('result') != 'PASS': continue for letter, rv in (row.get('recording_views') or {}).items(): observer = rv['observer'] if (row.get('presentation') or {}).get('videos', {}).get(letter) not in (None, observer): raise SystemExit(f'{qf}:{n + 1}: recording_views[{letter}] observer {observer} != presentation') src = np_export.find_video(videos, script_id, observer) if src is None: raise SystemExit(f'recording missing: script_id={script_id}, observer={observer} under {videos}') a, b = int(rv['start_frame']), int(rv['end_frame_exclusive']) if a == 0: if src not in full: full[src] = frames_of(src) if full[src] == b: continue need[(script_id, observer, a, b)] = Path(src).resolve() return need def cut(source, a, b, dst): part = dst.with_name(dst.name + '.part.mp4') dst.parent.mkdir(parents=True, exist_ok=True) subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-y', '-i', str(source), '-vf', f'trim=start_frame={a}:end_frame={b},setpts=PTS-STARTPTS', '-an', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-r', str(FPS), '-color_range', 'tv', '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'iec61966-2-1', '-movflags', '+faststart', str(part)], check=True, capture_output=True, text=True) got = frames_of(part) if got != b - a: part.unlink() raise RuntimeError(f'cut holds {got} frames, expected {b - a}') part.replace(dst) return sha256(dst) def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]) ap.add_argument('--questions', nargs='+', required=True, help='questions.jsonl / groups.jsonl (parent dir = script id)') ap.add_argument('--videos', required=True, help='render root, as np_export --videos') ap.add_argument('--out', required=True, help='writes /clips//*.mp4 and /clips/index.json') ap.add_argument('--sample-per-version', type=int) ap.add_argument('--seed', type=int, default=0) ap.add_argument('--items-from') ap.add_argument('--jobs', type=int, default=8) args = ap.parse_args(argv) if not shutil.which(FFMPEG) and not Path(FFMPEG).exists(): raise SystemExit(f'ffmpeg not found ({FFMPEG})') if args.sample_per_version and args.items_from: raise SystemExit('--sample-per-version and --items-from are exclusive') keep = None if args.sample_per_version: keep = np_export.sample_rows(args.questions, args.sample_per_version, args.seed) elif args.items_from: keep = np_export.select_rows(args.questions, np_export.read_item_ids(args.items_from)) need = wanted(args.questions, args.videos, keep) root = Path(args.out) / 'clips' root.mkdir(parents=True, exist_ok=True) index_path = root / 'index.json' old = json.loads(index_path.read_text()) if index_path.is_file() else {'clips': {}} clips, failed, todo = {}, {}, [] for (sid, obs, a, b), src in sorted(need.items()): rel = f'clips/{sid}/{clip_name(obs, a, b)}' prev, dst = old['clips'].get(rel), root.parent / rel if (prev and dst.is_file() and prev.get('source') == str(src) and prev.get('source_stat') == source_stat(src) and prev.get('sha256') == sha256(dst)): clips[rel] = prev else: todo.append((rel, sid, obs, a, b, src)) print(f'{len(need)} clips needed, {len(clips)} already cut, {len(todo)} to cut', flush=True) def one(job): rel, sid, obs, a, b, src = job stat = source_stat(src) digest = cut(src, a, b, root.parent / rel) return rel, {'source': str(src), 'source_stat': stat, 'script_id': sid, 'observer': obs, 'start_frame': a, 'end_frame_exclusive': b, 'frames': b - a, 'fps': FPS, 'sha256': digest} with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool: futures = {pool.submit(one, job): job for job in todo} for i, fut in enumerate(concurrent.futures.as_completed(futures), 1): rel = futures[fut][0] try: rel, entry = fut.result() clips[rel] = entry except (subprocess.CalledProcessError, RuntimeError, OSError) as exc: failed[rel] = (getattr(exc, 'stderr', None) or str(exc))[-500:] if i % 50 == 0 or i == len(todo): print(f'[{i}/{len(todo)}] cut, {len(failed)} failed', flush=True) tmp = index_path.with_name('index.json.part') tmp.write_text(json.dumps({'schema': SCHEMA, 'clips': dict(sorted(clips.items())), 'failed': failed}, ensure_ascii=False, indent=1)) tmp.replace(index_path) print(json.dumps({'index': str(index_path), 'clips': len(clips), 'failed': len(failed)})) return 1 if failed else 0 if __name__ == '__main__': sys.exit(main())