Created
November 23, 2021 19:28
-
-
Save Fusion86/8cdd1133b4f0f698633b6b2b0ab974d1 to your computer and use it in GitHub Desktop.
Shitty script to rename subtitle files to match the video naming format.
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
import os | |
import sys | |
import glob | |
import re | |
from typing import List | |
def find_video_files(dir: str): | |
return glob.glob(os.path.join(dir, "*.mp4")) + glob.glob(os.path.join(dir, "*.mkv")) | |
def find_subtitle_files(dir: str): | |
return ( | |
glob.glob(os.path.join(dir, "*.sub")) | |
+ glob.glob(os.path.join(dir, "*.srt")) | |
+ glob.glob(os.path.join(dir, "*.idx")) | |
) | |
def get_season_episode(filename: str): | |
m = re.search(r"[Ss](\d+)[Ee](\d+)", filename) | |
if len(m.groups()) == 2: | |
return f"S{m.group(1)}E{m.group(2)}" | |
raise Exception("Couldn't extract season and episode from filename") | |
def group_by_episode(videos: List[str], subs: List[str]): | |
group = {} | |
for video in videos: | |
try: | |
sep = get_season_episode(video) | |
group[sep] = {"video": video, "other_files": []} | |
except: | |
pass | |
for sub in subs: | |
try: | |
sep = get_season_episode(sub) | |
group[sep]["other_files"].append(sub) | |
except: | |
pass | |
return group | |
def build_rename_task(group): | |
renames = [] | |
for item in group: | |
video = group[item]["video"] | |
other_files = group[item]["other_files"] | |
for other_file in other_files: | |
ext = os.path.splitext(other_file)[1] | |
new_name = os.path.splitext(video)[0] + ext | |
renames.append((other_file, new_name)) | |
return renames | |
def execute_rename(renames): | |
for (old, new) in renames: | |
print(f"Renaming '{old}' to '{new}'...") | |
os.rename(old, new) | |
print(f"Done! Renamed {len(renames)} items.") | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
print("USAGE: subs_rename.py media_folder") | |
print("E.g. subs_rename.py 'Season 11/'") | |
exit(1) | |
target_dir = os.path.abspath(sys.argv[1]) | |
videos = find_video_files(target_dir) | |
subs = find_subtitle_files(target_dir) | |
print("Video files:") | |
for file in videos: | |
print(file) | |
print() | |
print("Subtitle files:") | |
for file in subs: | |
print(file) | |
print() | |
group = group_by_episode(videos, subs) | |
renames = build_rename_task(group) | |
print("Rename:") | |
for (old, new) in renames: | |
print(f"'{old}' to '{new}'") | |
print() | |
print("Press Y to confirm: ", end="") | |
if input().lower() == "y": | |
execute_rename(renames) | |
else: | |
print("Cancelled") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment