Skip to content

Instantly share code, notes, and snippets.

@yjlcoder
Last active April 26, 2023 23:51
Show Gist options
  • Select an option

  • Save yjlcoder/9d9e1335052fc0756132c3d01d55378f to your computer and use it in GitHub Desktop.

Select an option

Save yjlcoder/9d9e1335052fc0756132c3d01d55378f to your computer and use it in GitHub Desktop.
# pip install plexapi
import glob
import os
import re
import sys
from typing import List
from plexapi.library import ShowSection
from plexapi.server import PlexServer
from plexapi.video import Show, Episode
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} <Show Name> <Subtitle Extension>")
sys.exit(-1)
show_name = sys.argv[1]
sub_extension = sys.argv[2]
baseurl = os.getenv("PLEX_SERVER_URL")
token = os.getenv("PLEX_TOKEN")
if baseurl is None or token is None or len(baseurl) == 0 or len(token) == 0:
print("Please check the environmental variables: PLEX_SERVER_URL and PLEX_TOKEN")
sys.exit(-1)
plex = PlexServer(baseurl, token)
shows: ShowSection = plex.library.section("TV Shows")
show: List = shows.search(title=show_name)
if len(show) == 0:
print(f"Cannot find show {show_name}", file=sys.stderr)
sys.exit(-1)
show: Show = show[0]
subtitle_files = glob.glob(f"*.{sub_extension}")
episode_pattern = re.compile(r"[^a-zA-Z0-9]S(\d+)E(\d+)[^a-zA-Z0-9]")
subtitle_file_map = {}
for subtitle_file in subtitle_files:
match_result = re.search(episode_pattern, subtitle_file)
if match_result is None:
continue
episode_id = int(match_result.group(1)), int(match_result.group(2))
if episode_id in subtitle_file_map:
print(
f"ERROR: two subtitles are identified as S{episode_id[0]}E{episode_id[1]}: {subtitle_file_map[episode_id]}, {subtitle_file}",
file=sys.stderr)
sys.exit(-1)
subtitle_file_map[episode_id] = subtitle_file
episode_id_list = sorted(subtitle_file_map.keys(), key=lambda x: x[0] * 10000 + x[1])
for episode_id in episode_id_list:
season_num, episode_num = episode_id
sub_file_path = subtitle_file_map[episode_id]
episode: Episode = show.get(season=season_num, episode=episode_num)
if episode is None:
print(f"Cannot find episode: {show.title} S{season_num}E{episode_num}")
continue
episode.uploadSubtitles(sub_file_path)
print(f"Uploaded subtitles to {show.title} S{season_num}E{episode_num}: {sub_file_path}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment