Last active
February 24, 2024 08:30
-
-
Save senventise/ab455078e4ede0701c039c278eefd9e9 to your computer and use it in GitHub Desktop.
Match filename of videos and subtitles.
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 sys | |
import os | |
import re | |
""" | |
USAGE: python sub_match.py DIR | |
""" | |
# Use season and episode as identifier. | |
KEYWORD_PATTERN = r'[Ss]\d+[Ee]\d+' | |
# Video and subtitle extensions | |
VID_EXT = ['mkv', 'mp4'] | |
SUB_EXT = ['srt', 'ass'] | |
def match_subs(dir_path: str) -> None: | |
# {keyword: filename, ...} | |
videos: dict[str, str] = {} | |
subtitles: dict[str, str] = {} | |
# Enter dir | |
os.chdir(dir_path) | |
# Find videos and subtitles | |
for f in filter(os.path.isfile, os.listdir()): | |
ext = f.rsplit('.', maxsplit=1)[-1].lower() | |
if not (ext in SUB_EXT or ext in VID_EXT): | |
continue | |
keyword = re.findall(KEYWORD_PATTERN, f)[0] | |
if ext in VID_EXT: | |
videos[keyword] = f | |
elif ext in SUB_EXT: | |
subtitles[keyword] = f | |
print('# Generated shell script.') | |
# Generate script | |
for kw, video_full_name in videos.items(): | |
if kw in subtitles: | |
# `mv` if video-sub pair found | |
video_name = video_full_name.rsplit('.', maxsplit=1)[0] | |
sub_extension = subtitles[kw].rsplit('.', maxsplit=1)[-1] | |
sub_new_path = f'{video_name}.{sub_extension}' | |
# print(kw, sub_new_path) | |
print(f'mv ' | |
f'"{os.path.abspath(subtitles[kw])}" ' | |
f'"{os.path.abspath(sub_new_path)}"' | |
) | |
else: | |
# warn if no sub matched | |
print(f'echo "!!! Subtitle for {video_full_name} not found !!!"') | |
if __name__ == '__main__': | |
match_subs(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment