OmniLife360 / scripts /prepare_frames_from_metadata.py
Sg11100's picture
Release OmniLife360 dataset benchmark
82223c9
Raw
History Blame Contribute Delete
6.98 kB
#!/usr/bin/env python3
"""Download public source videos and extract OmniLife360 panoramic frames.
The script reads metadata/train_test_split_with_links.json and writes frames to:
<output_root>/<split>/<scene>/<clip_id>/images/%04d.jpg
Only entries with a non-null source_url are processed. Author-captured sequences
are intentionally skipped because they are not publicly linked in this release.
"""
import argparse
import json
import re
import subprocess
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Tuple
VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov", ".m4v"}
def iter_entries(metadata: Dict, split_filter: str) -> Iterator[Tuple[str, str, str, Dict]]:
for split, scenes in metadata.items():
if split_filter != "all" and split != split_filter:
continue
for scene, clips in scenes.items():
for clip_id, info in clips.items():
yield split, scene, clip_id, info
def safe_stem(value: str) -> str:
return re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("_") or "source_video"
def find_downloaded_video(download_dir: Path, source_id: str) -> Optional[Path]:
stem = safe_stem(source_id)
candidates: List[Path] = []
for path in download_dir.glob(f"{stem}.*"):
if path.suffix.lower() in VIDEO_EXTENSIONS and path.is_file():
candidates.append(path)
if not candidates:
return None
candidates.sort(key=lambda p: p.stat().st_mtime, reverse=True)
return candidates[0]
def run(cmd: List[str], dry_run: bool) -> None:
print("+", " ".join(cmd))
if not dry_run:
subprocess.run(cmd, check=True)
def download_video(
source_url: str,
source_id: str,
download_dir: Path,
ytdlp_format: str,
dry_run: bool,
) -> Path:
existing = find_downloaded_video(download_dir, source_id)
if existing is not None:
return existing
download_dir.mkdir(parents=True, exist_ok=True)
out_template = str(download_dir / f"{safe_stem(source_id)}.%(ext)s")
cmd = [
"yt-dlp",
"-f",
ytdlp_format,
"--merge-output-format",
"mp4",
"-o",
out_template,
source_url,
]
run(cmd, dry_run)
if dry_run:
return download_dir / f"{safe_stem(source_id)}.mp4"
downloaded = find_downloaded_video(download_dir, source_id)
if downloaded is None:
raise FileNotFoundError(f"yt-dlp finished but no video was found for {source_id}")
return downloaded
def extract_frames(
video_path: Path,
out_dir: Path,
start_sec: float,
end_sec: float,
fps: float,
width: int,
height: int,
quality: int,
overwrite: bool,
dry_run: bool,
) -> int:
image_dir = out_dir / "images"
existing = sorted(image_dir.glob("*.jpg")) if image_dir.is_dir() else []
if existing and not overwrite:
print(f"[skip] existing frames: {image_dir}")
return len(existing)
image_dir.mkdir(parents=True, exist_ok=True)
if overwrite:
for path in image_dir.glob("*.jpg"):
if not dry_run:
path.unlink()
cmd = [
"ffmpeg",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-nostdin",
"-i",
str(video_path),
"-ss",
f"{start_sec:.6f}",
"-to",
f"{end_sec:.6f}",
"-vf",
f"fps={fps},scale={width}:{height}:flags=lanczos",
"-q:v",
str(quality),
str(image_dir / "%04d.jpg"),
]
run(cmd, dry_run)
if dry_run:
return 0
return len(list(image_dir.glob("*.jpg")))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Prepare OmniLife360 panoramic frames from public source URLs."
)
parser.add_argument(
"--metadata",
default="metadata/train_test_split_with_links.json",
help="Path to train_test_split_with_links.json.",
)
parser.add_argument(
"--output-root",
required=True,
help="Directory where <split>/<scene>/<clip_id>/images will be written.",
)
parser.add_argument(
"--download-root",
required=True,
help="Directory where downloaded source videos will be cached.",
)
parser.add_argument("--split", choices=["train", "test", "all"], default="all")
parser.add_argument("--fps", type=float, default=1.0)
parser.add_argument("--width", type=int, default=1920)
parser.add_argument("--height", type=int, default=960)
parser.add_argument("--jpeg-quality", type=int, default=2)
parser.add_argument(
"--ytdlp-format",
default="bestvideo+bestaudio/best",
help="Format selector passed to yt-dlp.",
)
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--max-items", type=int, default=0)
parser.add_argument("--dry-run", action="store_true")
return parser.parse_args()
def main() -> None:
args = parse_args()
metadata = json.loads(Path(args.metadata).read_text(encoding="utf-8"))
output_root = Path(args.output_root)
download_root = Path(args.download_root)
processed = 0
skipped = 0
failed = 0
for split, scene, clip_id, info in iter_entries(metadata, args.split):
source_url = info.get("source_url")
if not source_url:
skipped += 1
continue
if args.max_items and processed >= args.max_items:
break
source_id = info.get("source_video_id") or info.get("video_id") or clip_id
start_sec = float(info.get("start_sec", 0.0))
end_sec = float(info.get("end_sec", 0.0))
if end_sec <= start_sec:
print(f"[skip] invalid time window: {split}/{scene}/{clip_id}")
skipped += 1
continue
out_dir = output_root / split / scene / clip_id
try:
video_path = download_video(
source_url=source_url,
source_id=source_id,
download_dir=download_root,
ytdlp_format=args.ytdlp_format,
dry_run=args.dry_run,
)
n = extract_frames(
video_path=video_path,
out_dir=out_dir,
start_sec=start_sec,
end_sec=end_sec,
fps=args.fps,
width=args.width,
height=args.height,
quality=args.jpeg_quality,
overwrite=args.overwrite,
dry_run=args.dry_run,
)
print(f"[ok] {split}/{scene}/{clip_id} frames={n}")
processed += 1
except Exception as exc:
print(f"[fail] {split}/{scene}/{clip_id}: {exc}")
failed += 1
print(f"done: processed={processed} skipped={skipped} failed={failed}")
if failed:
raise SystemExit(1)
if __name__ == "__main__":
main()