Skip to content

Commit

Permalink
Merge pull request #88 from CollinHeist/develop
Browse files Browse the repository at this point in the history
Better progress bars, fix for empty titles, other minor fixes
  • Loading branch information
CollinHeist authored Apr 23, 2022
2 parents 35f91c3 + 2ae6edc commit bbdfe3d
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 33 deletions.
18 changes: 17 additions & 1 deletion modules/Debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
from logging import NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL
from tqdm import tqdm

"""TQDM bar format string"""
TQDM_BAR = ('{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} '
'[{elapsed}, {rate_fmt}{postfix}]')

class LogHandler(Handler):
"""Handler subclass to integrate logging messages with TQDM"""

def __init__(self, level=NOTSET):
super().__init__(level)

Expand All @@ -15,8 +21,9 @@ def emit(self, record):


class LogFormatterColor(Formatter):
"""Taken/modified from SO: https://stackoverflow.com/a/56944256"""
"""Custom Formatter for logging integration, uses color"""

"""Color codes"""
GRAY = '\x1b[1;30m'
CYAN = '\033[96m'
YELLOW = '\x1b[33;20m'
Expand All @@ -42,6 +49,8 @@ def format(self, record):


class LogFormatterNoColor(Formatter):
"""Custom Formatter for logging integration, does not use color"""

format_layout = '[%(levelname)s] %(message)s'

LEVEL_FORMATS = {
Expand Down Expand Up @@ -69,6 +78,13 @@ def format(self, record):
log.addHandler(handler)

def apply_no_color_formatter(log_object: 'Logger') -> None:
"""
Modify the given logger object, removing the colored Handler, adding an
instance of the colorless one.
:param log_object: The log object to modify.
"""

# Create colorless Formatter
handler = LogHandler()
handler.setFormatter(LogFormatterNoColor())
Expand Down
21 changes: 12 additions & 9 deletions modules/Manager.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from yaml import dump
from tqdm import tqdm

from modules.Debug import log
from modules.Debug import log, TQDM_BAR
from modules.PlexInterface import PlexInterface
import modules.preferences as global_preferences
from modules.Show import Show
Expand Down Expand Up @@ -93,7 +93,7 @@ def check_tmdb_for_translations(self) -> None:
return None

# For each show in the Manager, add translation
for show in (pbar := tqdm(self.shows)):
for show in (pbar := tqdm(self.shows, bar_format=TQDM_BAR)):
pbar.set_description(f'Adding translations for '
f'"{show.series_info.short_name}"')
show.add_translations(self.tmdb_interface)
Expand All @@ -105,11 +105,13 @@ def read_show_source(self) -> None:
for all Show and ShowArchives, and also looks for multipart episodes.
"""

for show in tqdm(self.shows, desc='Reading source files'):
for show in tqdm(self.shows, desc='Reading source files',
bar_format=TQDM_BAR):
show.read_source()
show.find_multipart_episodes()

for archive in tqdm(self.archives, desc='Reading archive source files'):
for archive in tqdm(self.archives, desc='Reading archive source files',
bar_format=TQDM_BAR):
archive.read_source()
archive.find_multipart_episodes()

Expand All @@ -125,7 +127,8 @@ def check_sonarr_for_new_episodes(self) -> None:
return None

# Go through each show in the Manager and query Sonarr
for show in tqdm(self.shows + self.archives, desc='Querying Sonarr'):
for show in tqdm(self.shows + self.archives, desc='Querying Sonarr',
bar_format=TQDM_BAR):
show.query_sonarr(self.sonarr_interface)


Expand All @@ -136,7 +139,7 @@ def create_missing_title_cards(self) -> None:
"""

# Go through every show in the Manager, create cards
for show in (pbar := tqdm(self.shows)):
for show in (pbar := tqdm(self.shows, bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Creating Title Cards for '
f'"{show.series_info.short_name}"')
Expand All @@ -160,7 +163,7 @@ def update_plex(self) -> None:
return None

# Go through each show in the Manager, update Plex
for show in (pbar := tqdm(self.shows)):
for show in (pbar := tqdm(self.shows, bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Updating Plex for '
f'"{show.series_info.short_name}"')
Expand All @@ -178,7 +181,7 @@ def update_archive(self) -> None:
if not self.preferences.create_archive:
return None

for show_archive in (pbar := tqdm(self.archives)):
for show_archive in (pbar := tqdm(self.archives, bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Updating archive for '
f'"{show_archive.series_info.short_name}"')
Expand All @@ -199,7 +202,7 @@ def create_summaries(self) -> None:
if not self.preferences.create_summaries:
return None

for show_archive in (pbar := tqdm(self.archives)):
for show_archive in (pbar := tqdm(self.archives, bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Creating ShowSummary for "'
f'{show_archive.series_info.short_name}"')
Expand Down
11 changes: 8 additions & 3 deletions modules/PlexInterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ def __get_series(self, library: 'Library',
try:
return library.get(series_info.full_name)
except NotFound:
log.error(f'Series "{series_info}" was not found under library '
f'"{library.title}" in Plex')
log.warning(f'Series "{series_info}" was not found under library '
f'"{library.title}" in Plex')
return None


Expand Down Expand Up @@ -189,7 +189,12 @@ def set_title_cards_for_series(self, library_name: str,
if ep_key in filtered_episodes:
# Upload card to Plex
card_file = filtered_episodes[ep_key].destination
episode.uploadPoster(filepath=card_file.resolve())
try:
episode.uploadPoster(filepath=card_file.resolve())
except Exception as e:
log.error(f'Unable to upload {card_file} to {series_info}'
f' - Plex returned "{e}"')
continue

# Update the loaded map with this card's size
size = card_file.stat().st_size
Expand Down
14 changes: 5 additions & 9 deletions modules/PreferenceParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from tqdm import tqdm
from yaml import safe_load

from modules.Debug import log
from modules.Debug import log, TQDM_BAR
from modules.ImageMagickInterface import ImageMagickInterface
from modules.ImageMaker import ImageMaker
from modules.Show import Show
Expand Down Expand Up @@ -243,7 +243,7 @@ def iterate_series_files(self) -> [Show]:
"""

# For each file in the cards list
for file in (pbar := tqdm(self.series_files)):
for file in (pbar := tqdm(self.series_files, bar_format=TQDM_BAR)):
# Create Path object for this file
file_object = Path(file)

Expand All @@ -257,12 +257,8 @@ def iterate_series_files(self) -> [Show]:
continue

# Read file, parse yaml
with file_object.open('r') as file_handle:
try:
file_yaml = safe_load(file_handle)
except Exception as e:
log.error(f'Error reading series file:\n{e}\n')
continue
if (file_yaml := self._read_file(file_object)) == {}:
continue

# Skip if there are no series to yield
if file_yaml is None or 'series' not in file_yaml:
Expand All @@ -281,7 +277,7 @@ def iterate_series_files(self) -> [Show]:

# Go through each series in this file
for show_name in tqdm(file_yaml['series'], leave=False,
desc='Creating Shows'):
desc='Creating Shows', bar_format=TQDM_BAR):
# Yield the Show object created from this entry
yield Show(
show_name,
Expand Down
4 changes: 3 additions & 1 deletion modules/Profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,9 @@ def __remove_episode_text_format(self, title_text: str) -> str:
if not text_to_remove:
return title_text

return title_text.replace(text_to_remove.group(), '')
# Replace removal text, return original if all text was removed
finalized_title = title_text.replace(text_to_remove.group(), '')
return title_text if len(finalized_title) == 0 else finalized_title


def convert_title(self, title_text: str) -> str:
Expand Down
8 changes: 5 additions & 3 deletions modules/Show.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from tqdm import tqdm

from modules.DataFileInterface import DataFileInterface
from modules.Debug import log
from modules.Debug import log, TQDM_BAR
from modules.Episode import Episode
from modules.Font import Font
from modules.MultiEpisode import MultiEpisode
Expand Down Expand Up @@ -400,7 +400,8 @@ def add_translations(self, tmdb_interface: 'TMDbInterface') -> None:

# Go through every episode and look for translations
modified = False
for _, episode in (pbar := tqdm(self.episodes.items(), leave=False)):
for _, episode in (pbar := tqdm(self.episodes.items(), leave=False,
bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Checking {episode}')

Expand Down Expand Up @@ -450,7 +451,8 @@ def create_missing_title_cards(self,
return False

# Go through each episode for this show
for _, episode in (pbar := tqdm(self.episodes.items(), leave=False)):
for _, episode in (pbar := tqdm(self.episodes.items(), leave=False,
bar_format=TQDM_BAR)):
# Update progress bar
pbar.set_description(f'Creating {episode}')

Expand Down
4 changes: 2 additions & 2 deletions modules/StandardTitleCard.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class StandardTitleCard(CardType):
}

"""Default font and text color for episode title text"""
TITLE_FONT = str((Path(__file__).parent /'ref'/'Sequel-Neue.otf').resolve())
TITLE_FONT = str((REF_DIRECTORY / 'Sequel-Neue.otf').resolve())
TITLE_COLOR = '#EBEBEB'

"""Default characters to replace in the generic font"""
Expand Down Expand Up @@ -111,7 +111,7 @@ def __title_text_global_effects(self) -> list:
f'-font "{self.font}"',
f'-kerning -1.25',
f'-interword-spacing 50',
f'-interline-spacing {interline_spacing}', #-22, south park is +70
f'-interline-spacing {interline_spacing}',
f'-pointsize {font_size}',
f'-gravity south',
]
Expand Down
10 changes: 5 additions & 5 deletions modules/TMDbInterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,15 @@ def __init__(self, api_key: str) -> None:

# Attempt to read existing ID map
if self.__ID_MAP.exists():
with self.__ID_MAP.open('r') as file_handle:
with self.__ID_MAP.open('r', encoding='utf-8') as file_handle:
self.__id_map = safe_load(file_handle)
else:
self.__id_map = {'name': {}, 'id': {}}

# Attempt to read existing blacklist, if DNE, create blank one
if self.__BLACKLIST_FILE.exists():
with self.__BLACKLIST_FILE.open('r') as file_handle:
self.__blacklist = self.__fix_blacklist(safe_load(file_handle))
with self.__BLACKLIST_FILE.open('r', encoding='utf-8') as fh:
self.__blacklist = self.__fix_blacklist(safe_load(fh))
else:
self.__blacklist = self.__EMPTY_BLACKLIST

Expand Down Expand Up @@ -171,7 +171,7 @@ def __update_blacklist(self, series_info: SeriesInfo,
self.__blacklist[query_type][key] = {'failures': 1, 'next': later}

# Write latest version of blacklist to file
with self.__BLACKLIST_FILE.open('w') as file_handle:
with self.__BLACKLIST_FILE.open('w', encoding='utf-8') as file_handle:
dump(self.__blacklist, file_handle)


Expand Down Expand Up @@ -228,7 +228,7 @@ def __add_id_to_map(self, series_info: SeriesInfo) -> None:
self.__id_map['id'][series_info.tvdb_id] = series_info.tmdb_id

# Write updated map to file
with self.__ID_MAP.open('w') as file_handle:
with self.__ID_MAP.open('w', encoding='utf-8') as file_handle:
dump(self.__id_map, file_handle)


Expand Down

0 comments on commit bbdfe3d

Please sign in to comment.