#!/usr/bin/env python3 """Reconstruct EgoCoT-Bench processed clips from locally obtained source media. This script does not download, upload, or redistribute third-party media. Users must provide source videos obtained from the original dataset providers. """ from __future__ import annotations import argparse import csv from pathlib import Path VIDEO_EXTENSIONS = (".mp4", ".mov", ".mkv", ".avi", ".webm") def find_source_video(source_root: Path, source_dataset: str, source_video_id: str) -> Path: dataset_root = source_root / source_dataset candidates = [] for root in (dataset_root, source_root): for ext in VIDEO_EXTENSIONS: candidates.append(root / f"{source_video_id}{ext}") for candidate in candidates: if candidate.exists(): return candidate raise FileNotFoundError( f"Could not find source video for {source_dataset}/{source_video_id}. " f"Looked under {dataset_root} and {source_root}." ) def reconstruct_with_opencv(row: dict[str, str], input_video: Path, output_path: Path) -> None: try: import cv2 except ImportError as exc: raise RuntimeError( "OpenCV is required for reconstruction. Install opencv-python." ) from exc fps = float(row.get("fps", "4")) width = int(row["target_width"]) height = int(row["target_height"]) cap = cv2.VideoCapture(str(input_video)) if not cap.isOpened(): raise RuntimeError(f"Failed to open source video: {input_video}") try: raw_fps = cap.get(cv2.CAP_PROP_FPS) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) duration = frame_count / raw_fps if raw_fps > 0 else 0 target_frame_count = int(duration * fps) if target_frame_count <= 0: raise RuntimeError(f"Invalid target frame count for {input_video}") fourcc = cv2.VideoWriter_fourcc(*"mp4v") writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height)) if not writer.isOpened(): raise RuntimeError(f"Failed to open output video writer: {output_path}") try: for i in range(target_frame_count): target_time = i / fps raw_frame_idx = int(round(target_time * raw_fps)) if raw_frame_idx >= frame_count: raw_frame_idx = frame_count - 1 cap.set(cv2.CAP_PROP_POS_FRAMES, raw_frame_idx) success, frame = cap.read() if not success: continue if frame.shape[1] != width or frame.shape[0] != height: frame = cv2.resize(frame, (width, height)) writer.write(frame) finally: writer.release() finally: cap.release() def reconstruct_row( row: dict[str, str], source_root: Path, output_root: Path, dry_run: bool, ) -> tuple[str, str | None]: if row.get("source_dataset") == "Self-recorded": return "self_recorded", None rel_output = Path(row["expected_local_output_path"]) if rel_output.is_absolute(): raise ValueError(f"expected_local_output_path must be relative: {rel_output}") output_path = output_root / rel_output if output_path.exists(): return "existing", None try: input_video = find_source_video(source_root, row["source_dataset"], row["source_video_id"]) except FileNotFoundError: return "missing_source", f"{row.get('source_dataset')}/{row.get('source_video_id')}" output_path.parent.mkdir(parents=True, exist_ok=True) if not dry_run: reconstruct_with_opencv(row, input_video, output_path) return ("dry_run" if dry_run else "reconstructed"), None def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--manifest", default="manifests/media_reconstruction.csv") parser.add_argument("--source-root", required=True) parser.add_argument("--output-root", default="media_reconstructed") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() source_root = Path(args.source_root) output_root = Path(args.output_root) seen_outputs: set[str] = set() missing_sources: set[str] = set() counts = { "reconstructed": 0, "dry_run": 0, "existing": 0, "missing_source": 0, "self_recorded": 0, "duplicate": 0, } with Path(args.manifest).open(newline="", encoding="utf-8") as handle: for row in csv.DictReader(handle): output_key = row.get("expected_local_output_path", "") if output_key in seen_outputs: counts["duplicate"] += 1 continue seen_outputs.add(output_key) status, missing_source = reconstruct_row(row, source_root, output_root, args.dry_run) counts[status] += 1 if missing_source: missing_sources.add(missing_source) if missing_sources: print("Missing source videos:") for source in sorted(missing_sources): print(source) else: print("No missing source videos.") return 0 if __name__ == "__main__": raise SystemExit(main())