File size: 3,302 Bytes
c500c2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())