youtube-skill/scripts/probe_durations.py

78 lines
2.3 KiB
Python

# -*- coding: utf-8 -*-
"""Probe total duration of every media subfolder under a batch root.
Usage:
python probe_durations.py
python probe_durations.py "D:\\MyBatch"
Writes: _meta_probe.json
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import cv2
def probe_video(path: Path) -> dict:
cap = cv2.VideoCapture(str(path))
if not cap.isOpened():
return {"file": path.name, "path": str(path), "duration": 0.0, "size_mb": 0, "w": 0, "h": 0, "fps": "0"}
fps = float(cap.get(cv2.CAP_PROP_FPS) or 0)
n = float(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
if n > 0 and fps > 0:
dur = n / fps
else:
cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0)
dur = float(cap.get(cv2.CAP_PROP_POS_MSEC) or 0) / 1000.0
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
cap.release()
return {
"file": path.name,
"path": str(path),
"duration": round(float(dur), 3),
"size_mb": round(path.stat().st_size / 1024 / 1024, 1),
"w": w,
"h": h,
"fps": str(fps),
}
def hms(sec: float) -> str:
sec = max(0, int(sec))
return f"{sec // 3600:02d}:{(sec % 3600) // 60:02d}:{sec % 60:02d}"
def main() -> None:
root = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path.cwd().resolve()
out: dict = {}
rows = []
for d in sorted(root.iterdir(), key=lambda p: p.name.lower()):
if not d.is_dir() or d.name.startswith("_") or d.name.startswith("."):
continue
mp4s = sorted(d.glob("*.mp4"))
if not mp4s:
continue
vids = [probe_video(p) for p in mp4s]
total = sum(v["duration"] for v in vids)
out[d.name] = {
"videos": vids,
"total_duration": round(total, 3),
"total_hms": hms(total),
}
rows.append((d.name, total, len(vids), hms(total)))
path = root / "_meta_probe.json"
path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"ROOT {root}")
print(f"{'folder':40} {'clips':>5} {'duration':>10} {'hms':>10}")
for name, total, n, hm in rows:
print(f"{name[:40]:40} {n:5d} {total:10.1f} {hm:>10}")
print(f"Wrote {path} folders={len(rows)}")
if __name__ == "__main__":
main()