#!/usr/bin/env python3 """Prepare Egotools v2 SFT JSONL with physical video clips. The v2 JSONL already contains ms-swift style messages plus `videos`, `start_frame`, and `end_frame`. This script creates one mp4 per unique frame span and rewrites `videos` to point at `video_clips/*.mp4`. """ from __future__ import annotations import argparse import concurrent.futures import hashlib import json import subprocess from dataclasses import dataclass from fractions import Fraction from pathlib import Path from typing import Any @dataclass(frozen=True) class ClipSpec: clip_id: str source_name: str source_video: Path out_path: Path start_frame: int end_frame: int fps: float @property def start_s(self) -> float: # Frames in the dataset are 1-indexed and inclusive. return max(0.0, (self.start_frame - 1) / self.fps) @property def end_s(self) -> float: return max(self.start_s + 0.001, self.end_frame / self.fps) @property def duration_s(self) -> float: return max(0.001, self.end_s - self.start_s) def log(message: str) -> None: print(message, flush=True) def source_map(source_root: Path) -> dict[str, Path]: mapping: dict[str, Path] = {} for path in source_root.rglob("*.mp4"): mapping[path.name] = path mapping[f"{path.parent.name}__{path.name}"] = path return mapping def normalize_video_name(video_ref: str) -> str: name = Path(video_ref).name if name.endswith("_clips"): return name[: -len("_clips")] + ".mp4" return name def fps_for_video(path: Path, cache: dict[Path, float]) -> float: if path in cache: return cache[path] cmd = [ "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=avg_frame_rate,r_frame_rate", "-of", "default=noprint_wrappers=1:nokey=1", str(path), ] proc = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if proc.returncode != 0: raise RuntimeError(f"ffprobe failed for {path}: {proc.stderr.strip()}") rates = [line.strip() for line in proc.stdout.splitlines() if line.strip()] fps = 0.0 for rate in rates: try: fps = float(Fraction(rate)) except Exception: fps = 0.0 if fps > 0: break if fps <= 0: raise RuntimeError(f"Could not parse fps for {path}: {rates}") cache[path] = fps return fps def build_clip_id(source_name: str, start_frame: int, end_frame: int) -> str: stem = Path(source_name).stem base = f"{stem}__f{start_frame}-{end_frame}" digest = hashlib.sha1(base.encode("utf-8")).hexdigest()[:10] return f"{base}__{digest}" def load_and_write( input_jsonl: Path, output_jsonl: Path, clip_dir: Path, manifest: Path, missing_path: Path, source_root: Path, ) -> dict[str, ClipSpec]: mapping = source_map(source_root) fps_cache: dict[Path, float] = {} clips: dict[str, ClipSpec] = {} missing: list[dict[str, Any]] = [] rows_written = 0 rows_seen = 0 output_jsonl.parent.mkdir(parents=True, exist_ok=True) clip_dir.mkdir(parents=True, exist_ok=True) with input_jsonl.open() as f, output_jsonl.open("w") as out: for line_no, line in enumerate(f, 1): rows_seen += 1 obj = json.loads(line) videos = obj.get("videos") or [] if len(videos) != 1: missing.append({"line_no": line_no, "reason": "expected_one_video", "videos": videos}) continue source_name = normalize_video_name(videos[0]) source_video = mapping.get(source_name) if source_video is None: missing.append({"line_no": line_no, "reason": "missing_source_video", "video": videos[0], "normalized": source_name}) continue try: start_frame = int(obj.get("start_frame", obj.get("metadata", {}).get("start_frame"))) end_frame = int(obj.get("end_frame", obj.get("metadata", {}).get("end_frame"))) except Exception: missing.append({"line_no": line_no, "reason": "bad_frame_range", "video": videos[0]}) continue if end_frame < start_frame: missing.append( { "line_no": line_no, "reason": "end_before_start", "video": videos[0], "start_frame": start_frame, "end_frame": end_frame, } ) continue fps = fps_for_video(source_video, fps_cache) clip_id = build_clip_id(source_name, start_frame, end_frame) out_path = clip_dir / f"{clip_id}.mp4" if clip_id not in clips: clips[clip_id] = ClipSpec( clip_id=clip_id, source_name=source_name, source_video=source_video, out_path=out_path, start_frame=start_frame, end_frame=end_frame, fps=fps, ) obj["videos"] = [f"video_clips/{out_path.name}"] obj["_source_video"] = str(source_video) obj["_clip_id"] = clip_id out.write(json.dumps(obj, ensure_ascii=False) + "\n") rows_written += 1 with manifest.open("w") as out: for clip in sorted(clips.values(), key=lambda item: item.clip_id): out.write( json.dumps( { "clip_id": clip.clip_id, "source_name": clip.source_name, "source_video": str(clip.source_video), "clip_path": str(clip.out_path), "start_frame": clip.start_frame, "end_frame": clip.end_frame, "fps": clip.fps, "start_s": round(clip.start_s, 6), "end_s": round(clip.end_s, 6), "duration_s": round(clip.duration_s, 6), }, ensure_ascii=False, ) + "\n" ) with missing_path.open("w") as out: for item in missing: out.write(json.dumps(item, ensure_ascii=False) + "\n") log( json.dumps( { "rows_seen": rows_seen, "rows_written": rows_written, "missing_rows": len(missing), "unique_clips": len(clips), "output_jsonl": str(output_jsonl), "clip_dir": str(clip_dir), "manifest": str(manifest), "missing": str(missing_path), }, indent=2, ensure_ascii=False, ) ) return clips def run_ffmpeg(spec: ClipSpec, codec: str, overwrite: bool) -> tuple[str, bool, str]: if spec.out_path.exists() and spec.out_path.stat().st_size > 0 and not overwrite: return spec.clip_id, True, "exists" spec.out_path.parent.mkdir(parents=True, exist_ok=True) tmp_path = spec.out_path.with_suffix(".tmp.mp4") tmp_path.unlink(missing_ok=True) if codec == "copy": cmd = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{spec.start_s:.6f}", "-i", str(spec.source_video), "-t", f"{spec.duration_s:.6f}", "-map", "0:v:0", "-an", "-c:v", "copy", "-avoid_negative_ts", "make_zero", str(tmp_path), ] else: cmd = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{spec.start_s:.6f}", "-i", str(spec.source_video), "-t", f"{spec.duration_s:.6f}", "-map", "0:v:0", "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p", str(tmp_path), ] proc = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if proc.returncode != 0 or not tmp_path.exists() or tmp_path.stat().st_size == 0: tmp_path.unlink(missing_ok=True) return spec.clip_id, False, proc.stderr.strip() or f"ffmpeg exited {proc.returncode}" tmp_path.replace(spec.out_path) return spec.clip_id, True, "created" def create_clips(args: argparse.Namespace, clips: dict[str, ClipSpec]) -> None: specs = sorted(clips.values(), key=lambda item: item.clip_id) total = len(specs) ok = 0 failed: list[tuple[str, str]] = [] with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor: futures = {executor.submit(run_ffmpeg, spec, args.codec, args.overwrite): spec for spec in specs} for done, future in enumerate(concurrent.futures.as_completed(futures), 1): clip_id, success, message = future.result() if success: ok += 1 else: failed.append((clip_id, message)) if done == total or done % args.progress_every == 0: log(f"clips {done}/{total}, ok={ok}, failed={len(failed)}") if failed: fail_path = args.clip_dir.parent / "egotools_v2_clip_failures.jsonl" with fail_path.open("w") as out: for clip_id, message in failed: out.write(json.dumps({"clip_id": clip_id, "error": message}, ensure_ascii=False) + "\n") raise RuntimeError(f"{len(failed)} clip(s) failed; see {fail_path}") def ensure_top_level_link(repo_root: Path, clip_dir: Path, link_name: str) -> None: link_path = repo_root / link_name target = clip_dir if not target.is_absolute(): target = (repo_root / target).resolve() rel_target = Path("data_v2/video_clips") if target == (repo_root / "data_v2/video_clips").resolve() else target if link_path.is_symlink(): link_path.unlink() elif link_path.exists(): log(f"skip symlink: {link_path} already exists and is not a symlink") return link_path.symlink_to(rel_target) log(f"created symlink: {link_path} -> {rel_target}") def build_parser() -> argparse.ArgumentParser: repo_root = Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser() parser.add_argument( "--input-jsonl", type=Path, default=repo_root / "data_v2/egotools_v2_sft_final.jsonl", ) parser.add_argument("--source-root", type=Path, default=repo_root / "data_v2/videos") parser.add_argument("--output-jsonl", type=Path, default=repo_root / "data_v2/egotools_v2_sft_final_clips.jsonl") parser.add_argument("--clip-dir", type=Path, default=repo_root / "data_v2/video_clips") parser.add_argument("--manifest", type=Path, default=repo_root / "data_v2/egotools_v2_clip_manifest.jsonl") parser.add_argument("--missing", type=Path, default=repo_root / "data_v2/egotools_v2_missing_videos.jsonl") parser.add_argument("--workers", type=int, default=8) parser.add_argument("--progress-every", type=int, default=200) parser.add_argument("--codec", choices=["copy", "h264"], default="copy") parser.add_argument("--overwrite", action="store_true") parser.add_argument("--no-create-clips", action="store_true") parser.add_argument("--no-symlink", action="store_true") parser.add_argument("--symlink-name", default="video_clips") return parser def main() -> int: args = build_parser().parse_args() clips = load_and_write(args.input_jsonl, args.output_jsonl, args.clip_dir, args.manifest, args.missing, args.source_root) if not args.no_create_clips: create_clips(args, clips) if not args.no_symlink: ensure_top_level_link(Path(__file__).resolve().parents[1], args.clip_dir, args.symlink_name) return 0 if __name__ == "__main__": raise SystemExit(main())