vstat / scripts /build_resolution_map.py
sihyun-yu's picture
VSTAT dataset release
dd56ce1
#!/usr/bin/env python3
"""Build a per-clip resolution map from an existing render of `videos/youtube/`.
Walks a reference directory laid out like `<ref>/<category>/<file>.mp4`,
runs ffprobe on each clip, and writes a JSON map keyed by
`videos/youtube/<category>/<file>.mp4` (matching `video_path` in
`youtube_metadata.json`). The map is consumed by `download_youtube.py
--resolution-map` to reproduce the exact width/height/fps of each clip.
Usage:
python scripts/build_resolution_map.py ~/Desktop/ytb/processed
python scripts/build_resolution_map.py REF_DIR -o youtube_resolutions.json
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def probe(path: Path) -> dict | None:
try:
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height,r_frame_rate",
"-show_entries", "format=duration",
"-of", "json", str(path)],
capture_output=True, text=True, check=True, timeout=30,
).stdout
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
return None
try:
info = json.loads(out)
except json.JSONDecodeError:
return None
s = (info.get("streams") or [{}])[0]
f = info.get("format", {})
fr = s.get("r_frame_rate", "0/1")
try:
n, d = (int(x) for x in fr.split("/"))
fps = round(n / d, 4) if d else None
except ValueError:
fps = None
if not (s.get("width") and s.get("height")):
return None
return {
"width": int(s["width"]),
"height": int(s["height"]),
"fps": fps,
"duration": round(float(f["duration"]), 4) if f.get("duration") else None,
}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("ref_dir", help="reference directory (e.g. ~/Desktop/ytb/processed)")
ap.add_argument("-o", "--out", default="youtube_resolutions.json",
help="output JSON path (default: youtube_resolutions.json)")
ap.add_argument("--workers", type=int, default=8)
args = ap.parse_args()
ref = Path(args.ref_dir).expanduser()
if not ref.is_dir():
sys.exit(f"ERROR: {ref} is not a directory")
paths = sorted(ref.glob("*/*.mp4"))
print(f"probing {len(paths)} files under {ref}…", file=sys.stderr)
out: dict[str, dict] = {}
bad: list[str] = []
with ThreadPoolExecutor(max_workers=max(1, args.workers)) as ex:
for p, info in zip(paths, ex.map(probe, paths)):
key = f"videos/youtube/{p.parent.name}/{p.name}"
if info is None:
bad.append(key)
continue
out[key] = info
out_path = Path(args.out)
out_path.write_text(json.dumps(out, indent=2, sort_keys=True))
print(f"wrote {out_path} ({len(out)} entries; {len(bad)} probe failures)",
file=sys.stderr)
if bad:
print(" failures:", *bad[:10], "…" if len(bad) > 10 else "", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())