Last active
March 16, 2019 01:33
-
-
Save Fusion86/b7afc1ae22e0ed23eb9e6e18b41b77f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Rename SRT files in a given directory to match that of a video file. | |
Matches SRT files with video files based on S{00}E{00} in filename | |
Example: | |
Video: Game of Thrones - S03E02 - Dark Wings, Dark Words Bluray-1080p.mkv | |
Old srt name: game.of.thrones.s03e02.1080p.bluray.x264-rovers.srt | |
New srt name: Game of Thrones - S03E02 - Dark Wings, Dark Words Bluray-1080p.srt | |
Issues: | |
- Actually only works for the current directory | |
- It sucks | |
""" | |
import re | |
from sys import argv | |
from os import listdir, rename | |
from os.path import isfile, join, exists, splitext | |
from collections import defaultdict | |
if __name__ == "__main__": | |
if len(argv) < 2 or argv[1] == "--help": | |
print("Usage:") | |
print(" srt_rename.py working_dir") | |
print() | |
print("Example:") | |
print(" srt_rename.py .") | |
print(" srt_rename.py ~/Series/Steins;Gate/Season 1/") | |
exit() | |
working_dir = argv[1] | |
if not exists(working_dir): | |
print("Path doesn't exist!") | |
exit(1) | |
files = [f for f in listdir(working_dir) if isfile(join(working_dir, f))] | |
pattern = r"([sS]\d{2}[eE]\d{2})" | |
collection = defaultdict(lambda: defaultdict(dict)) # Nested defaultdict | |
for f in files: | |
m = re.search(pattern, f) | |
# Match video files with srts | |
if m is not None: | |
identifier = m.group(1).upper() | |
# Type | |
if f.endswith("srt") or f.endswith("sub") or f.endswith("idx"): | |
if type(collection[identifier]["subtitle"]) is not list: | |
collection[identifier]["subtitle"] = [] | |
collection[identifier]["subtitle"].append(f) | |
else: | |
collection[identifier]["video"] = f | |
for k, v in collection.items(): | |
if "video" not in v: | |
print(k, "is missing a video file") | |
continue | |
if "subtitle" not in v: | |
print(k, "is missing a subtitle file") | |
continue | |
# Rename srt to match video | |
# srt_extension can be .srt, .sub or .idx. See line 52 | |
basename = splitext(v["video"])[0] | |
print() | |
print("Basename:", basename) | |
print("Video:", v["video"]) | |
for sub in v["subtitle"]: | |
srt_extension = splitext(sub)[1] | |
srtname = basename + srt_extension | |
print("New", srt_extension, "name:", srtname) | |
rename(sub, srtname) | |
print() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment