#!/usr/bin/env python3 from __future__ import annotations import argparse import json import os import sys from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from pathlib import Path from typing import Any import tqdm SCRIPT_DIR = Path(__file__).resolve().parent if str(SCRIPT_DIR) not in sys.path: sys.path.insert(0, str(SCRIPT_DIR)) from vlac2_release_common import ( discover_benchmark_jsons, dump_json, ensure_generated_marker, infer_main_path_from_row, load_json, normalize_main_path, PORTABLE_IMAGE_ROOT, resolve_benchmark_root, ) try: import cv2 # type: ignore except ImportError: cv2 = None try: import imageio.v2 as imageio # type: ignore except ImportError: imageio = None try: import av # type: ignore except ImportError: av = None @dataclass(frozen=True) class EpisodeSpec: main_path: Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Extract the portable VLAC2 release benchmark episodes into a JPG tree." ) parser.add_argument( "--data-root", type=Path, required=True, help="Directory containing the extracted raw benchmark videos.", ) parser.add_argument( "--frames-root", type=Path, default=PORTABLE_IMAGE_ROOT, help="Directory where extracted benchmark frames will be written. Defaults to _extracted_frames under the release directory.", ) parser.add_argument( "--benchmark-root", type=Path, default=None, help="Directory containing benchmark JSON files. Defaults to the release-local benchmark directory.", ) parser.add_argument( "--benchmark-json", action="append", default=[], type=Path, help="Specific benchmark JSON file(s) to extract frames for. May be passed multiple times.", ) parser.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 8) // 2)) parser.add_argument( "--overwrite-existing", action="store_true", help="Re-extract even if an output manifest says the target episode-view is already complete.", ) return parser.parse_args() def bundled_release_root() -> Path: return SCRIPT_DIR.parent.resolve() def resolve_data_root(raw_arg: Path, release_root: Path) -> Path: return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve() def resolve_frames_root(raw_arg: Path, release_root: Path) -> Path: return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve() def resolve_benchmark_path(raw_arg: Path, release_root: Path) -> Path: return raw_arg.resolve() if raw_arg.is_absolute() else (release_root / raw_arg).resolve() def require_decoder() -> None: if cv2 is None and imageio is None and av is None: raise SystemExit( "No video decoder available. Install opencv-python, PyAV, or imageio before running frame extraction." ) def benchmark_files_from_root(benchmark_root: Path) -> list[Path]: files = discover_benchmark_jsons(benchmark_root) if not files: raise SystemExit(f"No benchmark json found under {benchmark_root}") return files def benchmark_files_from_args(args: argparse.Namespace, release_root: Path) -> tuple[list[Path], Path | None]: if args.benchmark_json: benchmark_paths: list[Path] = [] seen: set[Path] = set() for raw_path in args.benchmark_json: path = resolve_benchmark_path(raw_path, release_root) if not path.exists(): raise SystemExit(f"Missing benchmark json: {path}") if not path.is_file(): raise SystemExit(f"Expected benchmark json file, got directory: {path}") resolved = path.resolve() if resolved in seen: continue seen.add(resolved) benchmark_paths.append(resolved) if not benchmark_paths: raise SystemExit("No benchmark json provided") return benchmark_paths, None if args.benchmark_root is not None: benchmark_root = resolve_benchmark_path(args.benchmark_root, release_root) else: benchmark_root = resolve_benchmark_root(release_root) return benchmark_files_from_root(benchmark_root), benchmark_root def episode_group_key(main_path: Path) -> str: parts = list(main_path.parts) for idx, part in enumerate(parts): if part.startswith("observation.images.") and idx + 1 < len(parts): return str(Path(*parts[:idx], parts[idx + 1])) return str(main_path) def collect_episode_specs(benchmark_paths: list[Path]) -> tuple[list[EpisodeSpec], dict[str, Any]]: grouped: dict[str, tuple[Path, set[str]]] = {} stats = { "benchmark_files_total": len(benchmark_paths), "rows_total": 0, "rows_missing_main_path": 0, } for benchmark_path in benchmark_paths: rows = load_json(benchmark_path) if not isinstance(rows, list): raise ValueError(f"Expected list json: {benchmark_path}") stats["rows_total"] += len(rows) for row in rows: inferred_main_path = infer_main_path_from_row(row) if inferred_main_path is None: stats["rows_missing_main_path"] += 1 continue normalized = normalize_main_path(inferred_main_path) # Keep different camera views for the same episode separate. The # benchmark's main_path can target wrist/head/bird/etc. views, and # merging by episode drops required frame directories. key = str(normalized) if key not in grouped: grouped[key] = (normalized, {str(benchmark_path)}) else: grouped[key][1].add(str(benchmark_path)) specs = [ EpisodeSpec(main_path=main_path) for _group_key, (main_path, _sources) in sorted(grouped.items()) ] stats["episodes_unique"] = len(specs) return specs, stats def resolve_main_video(raw_root: Path, main_path: Path) -> Path: candidate = raw_root / main_path if candidate.suffix == ".mp4": return candidate # Keep the full main_path leaf intact when appending ".mp4" so episode # identifiers containing dots (for example timestamps like "....311186") # are not truncated. Fall back to with_suffix(".mp4") for compatibility # with any legacy raw layouts that already dropped the tail suffix. preferred = Path(f"{candidate}.mp4") legacy = candidate.with_suffix(".mp4") if preferred.exists() or preferred == legacy: return preferred if legacy.exists(): return legacy return preferred def discover_view_videos(raw_root: Path, main_path: Path) -> list[Path]: main_video = resolve_main_video(raw_root, main_path) if not main_video.exists(): raise FileNotFoundError(f"Missing raw video: {main_video}") return [main_video] def manifest_path_for(output_dir: Path) -> Path: return output_dir / ".vlac_extract_manifest.json" def output_dir_from_video(raw_root: Path, output_root: Path, video_path: Path) -> Path: relative = video_path.relative_to(raw_root).with_suffix("") return output_root / relative def is_complete(output_dir: Path, source_video: Path) -> bool: manifest_path = manifest_path_for(output_dir) if not manifest_path.exists(): return False try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) except Exception: return False frame_count = int(manifest.get("frame_count") or 0) if frame_count <= 0: return False source_mtime_ns = int(source_video.stat().st_mtime_ns) source_size = int(source_video.stat().st_size) if int(manifest.get("source_mtime_ns") or -1) != source_mtime_ns: return False if int(manifest.get("source_size") or -1) != source_size: return False jpg_files = sorted(output_dir.glob("*.jpg")) return len(jpg_files) == frame_count def clear_output_dir(output_dir: Path) -> None: if not output_dir.exists(): return for pattern in ("*.jpg", "frame_*.jpg", ".vlac_extract_manifest.json"): for path in output_dir.glob(pattern): if path.is_file(): path.unlink() def write_manifest(output_dir: Path, source_video: Path, frame_count: int) -> None: manifest = { "source_video": str(source_video), "source_size": int(source_video.stat().st_size), "source_mtime_ns": int(source_video.stat().st_mtime_ns), "frame_count": int(frame_count), } manifest_path_for(output_dir).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def extract_with_cv2(source_video: Path, output_dir: Path) -> int: assert cv2 is not None capture = cv2.VideoCapture(str(source_video)) if not capture.isOpened(): raise RuntimeError(f"cv2 failed to open {source_video}") temp_paths: list[Path] = [] frame_idx = 0 try: while True: ok, frame = capture.read() if not ok: break temp_path = output_dir / f"frame_{frame_idx:06d}.jpg" if not cv2.imwrite(str(temp_path), frame): raise RuntimeError(f"cv2 failed to write {temp_path}") temp_paths.append(temp_path) frame_idx += 1 finally: capture.release() for idx, temp_path in enumerate(temp_paths): temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg") return frame_idx def extract_with_imageio(source_video: Path, output_dir: Path) -> int: assert imageio is not None temp_paths: list[Path] = [] frame_idx = 0 try: for frame in imageio.get_reader(str(source_video)): temp_path = output_dir / f"frame_{frame_idx:06d}.jpg" imageio.imwrite(str(temp_path), frame) temp_paths.append(temp_path) frame_idx += 1 except Exception as exc: if frame_idx == 0: raise RuntimeError(f"imageio failed to decode {source_video}: {exc}") from exc raise for idx, temp_path in enumerate(temp_paths): temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg") return frame_idx def extract_with_av(source_video: Path, output_dir: Path) -> int: assert av is not None container = av.open(str(source_video)) temp_paths: list[Path] = [] frame_idx = 0 try: for frame in container.decode(video=0): temp_path = output_dir / f"frame_{frame_idx:06d}.jpg" frame.to_image().save(temp_path, format="JPEG") temp_paths.append(temp_path) frame_idx += 1 finally: container.close() for idx, temp_path in enumerate(temp_paths): temp_path.rename(output_dir / f"{idx}-{frame_idx}.jpg") return frame_idx def extract_one_video(source_video: Path, output_dir: Path, overwrite_existing: bool) -> dict[str, Any]: if not overwrite_existing and is_complete(output_dir, source_video): manifest = json.loads(manifest_path_for(output_dir).read_text(encoding="utf-8")) return { "source_video": str(source_video), "output_dir": str(output_dir), "frame_count": int(manifest["frame_count"]), "status": "skipped_existing", } output_dir.mkdir(parents=True, exist_ok=True) clear_output_dir(output_dir) if cv2 is not None: frame_count = extract_with_cv2(source_video, output_dir) if frame_count == 0 and av is not None: clear_output_dir(output_dir) frame_count = extract_with_av(source_video, output_dir) if frame_count == 0 and imageio is not None: clear_output_dir(output_dir) frame_count = extract_with_imageio(source_video, output_dir) elif av is not None: frame_count = extract_with_av(source_video, output_dir) elif imageio is not None: frame_count = extract_with_imageio(source_video, output_dir) else: raise RuntimeError("No available decoder") if frame_count <= 0: raise RuntimeError(f"Decoder produced zero frames for {source_video}") write_manifest(output_dir, source_video, frame_count) return { "source_video": str(source_video), "output_dir": str(output_dir), "frame_count": frame_count, "status": "extracted", } def main() -> None: args = parse_args() require_decoder() release_root = bundled_release_root() data_root = resolve_data_root(args.data_root, release_root) output_root = resolve_frames_root(args.frames_root, release_root) ensure_generated_marker(output_root) benchmark_paths, benchmark_root = benchmark_files_from_args(args, release_root) specs, stats = collect_episode_specs(benchmark_paths) jobs: list[tuple[Path, Path]] = [] missing_raw_episodes: list[dict[str, str]] = [] for spec in specs: try: view_videos = discover_view_videos(data_root, spec.main_path) except FileNotFoundError as exc: missing_raw_episodes.append( { "main_path": str(spec.main_path), "error": str(exc), } ) continue for video_path in view_videos: jobs.append((video_path, output_dir_from_video(data_root, output_root, video_path))) results: list[dict[str, Any]] = [] with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as executor: future_to_job = { executor.submit(extract_one_video, video_path, output_dir, args.overwrite_existing): (video_path, output_dir) for video_path, output_dir in jobs } for future in tqdm.tqdm(as_completed(future_to_job), total=len(future_to_job), desc="Extract release frames"): video_path, output_dir = future_to_job[future] try: results.append(future.result()) except Exception as exc: results.append( { "source_video": str(video_path), "output_dir": str(output_dir), "status": "error", "error": str(exc), } ) summary = { **stats, "release_root": str(release_root), "benchmark_root": str(benchmark_root) if benchmark_root is not None else None, "data_root": str(data_root), "output_root": str(output_root), "benchmark_files": [str(path) for path in benchmark_paths], "jobs_total": len(jobs), "jobs_extracted": sum(1 for row in results if row["status"] == "extracted"), "jobs_skipped_existing": sum(1 for row in results if row["status"] == "skipped_existing"), "jobs_failed": sum(1 for row in results if row["status"] == "error"), "missing_raw_episodes": missing_raw_episodes, "results": results, } summary_path = output_root / "frame_extraction_summary.json" dump_json(summary_path, summary) print(f"[frame-extraction] {summary_path}") if __name__ == "__main__": main()