File size: 6,977 Bytes
82223c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | #!/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()
|