forked from Luctia/ezarr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia-discard.py
72 lines (66 loc) · 2.75 KB
/
media-discard.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
70
71
72
#!/usr/bin/env python3
import sys
import subprocess
import json
import shutil
import os.path
import os
import random
# Based on https://github.com/iwalton3/media-scripts/blob/master/media-discard/README.md
# Usage: find /path/to/folder -iname "*.mkv" | while read -r line; do PYTHONUNBUFFERED="yes" ./media-discard.py "$line" 2>&1 | tee -a /var/log/jellyfin-discard-log; done
MAX_NO_OF_SUBTITLES = 15
fname = sys.argv[1]
metadata = json.loads(subprocess.check_output(["mkvmerge","-J",fname]).decode())
permitted_locales = {None, 'und', 'eng', 'jpn', 'hun', 'mis', 'mul', 'zxx'}
saved_audio_tracks = []
saved_subtitle_tracks = []
has_bad_tracks = False
subtitle_count = sum(1 for track in metadata["tracks"] if track["type"] == "subtitles")
if subtitle_count < MAX_NO_OF_SUBTITLES:
print("This file {0} doesn't contain a ton of subtitle channels, skipping!".format(fname))
sys.exit(0)
for track in metadata["tracks"]:
props = track["properties"]
if track["type"] == "audio":
if props["language"] in permitted_locales:
saved_audio_tracks.append(str(track["id"]))
else:
has_bad_tracks = True
print("Discard audio: #{0} {1} ({2})".format(track["id"], props.get("track_name"), props.get("language")))
elif track["type"] == "subtitles":
if props["language"] in permitted_locales:
saved_subtitle_tracks.append(str(track["id"]))
else:
has_bad_tracks = True
print("Discard subtitle: #{0} {1} ({2})".format(track["id"], props.get("track_name"), props.get("language")))
if has_bad_tracks:
if len(saved_audio_tracks) == 0:
print("File {0} would have no audio tracks!".format(fname))
sys.exit(1)
tempfile = "_temp_{0}.mkv".format(random.randint(0,1000000))
options = ["mkvmerge","-o",tempfile,
"-a",",".join(saved_audio_tracks)]
if len(saved_subtitle_tracks) == 0:
options.append("-S")
else:
options.extend(["-s", ",".join(saved_subtitle_tracks)])
options.append(fname)
subprocess.check_call(options)
orig_size = os.path.getsize(fname)
new_size = os.path.getsize(tempfile)
if orig_size * 0.50 > new_size:
print("File {0} is too small after conversion.".format(fname))
os.remove(tempfile)
sys.exit(1)
print("Moving file {0}...".format(fname))
shutil.move(fname, fname+".bak")
try:
shutil.move(tempfile, fname)
except Exception:
print("File {0} could not be moved.".format(fname))
shutil.move(fname+".bak", fname)
if os.path.isfile(fname+".bak"):
os.remove(fname+".bak")
print("Size reduced {0} MiB ({1:n}%)".format((orig_size-new_size)//(1024**2), 100-(new_size*100//orig_size)))
else:
print("File {0} is already minified!".format(fname))