-
Notifications
You must be signed in to change notification settings - Fork 2
/
mediadims.py
executable file
·69 lines (51 loc) · 1.6 KB
/
mediadims.py
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
#!/usr/bin/env python3
# SPDX-License-Identifier: WTFPL
import argparse
import json
import locale
import signal
import subprocess
import shutil
import sys
def mediainfo_json(file: str) -> dict:
return json.loads(
subprocess.check_output(
["mediainfo", "--Output=JSON", file],
encoding="utf-8",
)
)
def from_tracks(tracks, key):
return list(filter(None, (track.get(key) for track in tracks)))
TRACK_SORT_KEY = {
"General": 0,
"Video": 1,
"Audio": 2,
"Image": 3,
}
def track_sort_key(track):
return TRACK_SORT_KEY.get(track["@type"], 100)
def main():
locale.setlocale(locale.LC_ALL, '')
signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
parser = argparse.ArgumentParser()
parser.add_argument("info", choices=["duration", "width", "height", "wxh"])
parser.add_argument("file")
args = parser.parse_args()
if not shutil.which("mediainfo"):
sys.exit("error: 'mediainfo' command could not be found")
metadata = mediainfo_json(args.file)
tracks = metadata["media"]["track"]
tracks.sort(key=track_sort_key) # useless? who knows
if args.info == "duration":
print(from_tracks(tracks, "Duration")[0])
elif args.info == "width":
print(from_tracks(tracks, "Width")[0])
elif args.info == "height":
print(from_tracks(tracks, "Height")[0])
elif args.info == "wxh":
width = from_tracks(tracks, "Width")[0]
height = from_tracks(tracks, "Height")[0]
print(f"{width}x{height}")
if __name__ == "__main__":
main()