dotfiles/hm/scripts/mediaDuration

61 lines
1.4 KiB
Plaintext
Raw Permalink Normal View History

#!/usr/bin/env nix-shell
#! nix-shell -i python3 --pure
#! nix-shell -p python3 python3Packages.coloredlogs ffmpeg
2020-12-27 14:20:44 +01:00
2023-11-23 22:59:09 +01:00
import logging
2020-12-27 14:20:44 +01:00
import os
import subprocess
2023-11-23 22:59:09 +01:00
import sys
2020-12-27 14:20:44 +01:00
import coloredlogs
2021-06-13 11:49:21 +02:00
coloredlogs.install(level="DEBUG", fmt="%(levelname)s %(message)s")
2020-12-27 14:20:44 +01:00
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")
2021-06-13 11:49:21 +02:00
elif ret == "N/A":
2020-12-27 14:20:44 +01:00
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)