dotfiles/config/scripts/mediaDuration

59 lines
1.3 KiB
Python
Executable file

#!/usr/bin/env python3
import os
import sys
import subprocess
import logging
import coloredlogs
coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s")
log = logging.getLogger()
def duration_file(path: str) -> float:
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
path,
]
run = subprocess.run(cmd, stdout=subprocess.PIPE)
ret = run.stdout.decode().strip()
if run.returncode != 0:
log.warning(f"{path}: unable to get duration")
elif ret == "N/A":
log.warning(f"{path}: has no duration")
else:
try:
return float(ret)
except ValueError:
log.error(f"{path}: returned {ret}")
return 0
def duration_directory(path: str) -> float:
total = 0.0
for root, dirs, files in os.walk(path):
for f in files:
fullPath = os.path.join(root, f)
total += duration_file(fullPath)
return total
total = 0.0
for arg in sys.argv[1:]:
if os.path.isfile(arg):
total += duration_file(arg)
elif os.path.isdir(arg):
total += duration_directory(arg)
else:
raise FileNotFoundError(f"No such file or directory: '{arg}'")
print(total)