-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathTitleCard.py
More file actions
executable file
·377 lines (318 loc) · 13.7 KB
/
Copy pathTitleCard.py
File metadata and controls
executable file
·377 lines (318 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
from pathlib import Path
from re import match, sub, IGNORECASE
from typing import TYPE_CHECKING
from modules import global_objects
from modules.BaseCardType import BaseCardType
from modules.CleanPath import CleanPath
from modules.Debug import log
from modules.EpisodeInfo import EpisodeInfo
from modules.SeriesInfo import SeriesInfo
# Built-in BaseCardType classes
from modules.cards.AnimeTitleCard import AnimeTitleCard
from modules.cards.BannerTitleCard import BannerTitleCard
from modules.cards.CalligraphyTitleCard import CalligraphyTitleCard
from modules.cards.ComicBookTitleCard import ComicBookTitleCard
from modules.cards.CutoutTitleCard import CutoutTitleCard
from modules.cards.DividerTitleCard import DividerTitleCard
from modules.cards.FadeTitleCard import FadeTitleCard
from modules.cards.FormulaOneTitleCard import FormulaOneTitleCard
from modules.cards.FrameTitleCard import FrameTitleCard
from modules.cards.GraphTitleCard import GraphTitleCard
from modules.cards.InsetTitleCard import InsetTitleCard
from modules.cards.LandscapeTitleCard import LandscapeTitleCard
from modules.cards.LogoTitleCard import LogoTitleCard
from modules.cards.MarvelTitleCard import MarvelTitleCard
from modules.cards.MusicTitleCard import MusicTitleCard
from modules.cards.NotificationTitleCard import NotificationTitleCard
from modules.cards.OlivierTitleCard import OlivierTitleCard
from modules.cards.OverlineTitleCard import OverlineTitleCard
from modules.cards.PosterTitleCard import PosterTitleCard
from modules.cards.RomanNumeralTitleCard import RomanNumeralTitleCard
from modules.cards.ShapeTitleCard import ShapeTitleCard
from modules.cards.StandardTitleCard import StandardTitleCard
from modules.cards.StarWarsTitleCard import StarWarsTitleCard
from modules.cards.StripedTitleCard import StripedTitleCard
from modules.cards.TextlessTitleCard import TextlessTitleCard
from modules.cards.TintedFrameTitleCard import TintedFrameTitleCard
from modules.cards.TintedGlassTitleCard import TintedGlassTitleCard
from modules.cards.WhiteBorderTitleCard import WhiteBorderTitleCard
if TYPE_CHECKING:
from modules.Episode import Episode, MultiEpisode
from modules.Profile import Profile
class TitleCard:
"""
This class describes a title card. This class is responsible for
applying a given profile to the Episode details and initializing a
CardType with those attributes.
It also contains the mapping of card type identifier strings to
their respective CardType classes.
"""
"""Extension of the input source image"""
INPUT_CARD_EXTENSION = '.jpg'
"""Default extension of the output title card"""
DEFAULT_CARD_EXTENSION = '.jpg'
"""Default filename format for all title cards"""
DEFAULT_FILENAME_FORMAT = '{full_name} - S{season:02}E{episode:02}'
"""Default card dimensions"""
DEFAULT_WIDTH = BaseCardType.WIDTH
DEFAULT_HEIGHT = BaseCardType.HEIGHT
DEFAULT_CARD_DIMENSIONS = BaseCardType.TITLE_CARD_SIZE
"""Default card type identifier to utilize if unspecified"""
DEFAULT_CARD_TYPE = 'standard'
"""Mapping of card type identifiers to CardType classes"""
CARD_TYPES = {
'4x3': FadeTitleCard,
'anime': AnimeTitleCard,
'banner': BannerTitleCard,
'blurred border': TintedFrameTitleCard,
'calligraphy': CalligraphyTitleCard,
'comic book': ComicBookTitleCard,
'cutout': CutoutTitleCard,
'divider': DividerTitleCard,
'f1': FormulaOneTitleCard,
'fade': FadeTitleCard,
'formula 1': FormulaOneTitleCard,
'frame': FrameTitleCard,
'generic': StandardTitleCard,
'graph': GraphTitleCard,
'gundam': PosterTitleCard,
'import': TextlessTitleCard,
'inset': InsetTitleCard,
'ishalioh': OlivierTitleCard,
'landscape': LandscapeTitleCard,
'logo': LogoTitleCard,
'marvel': MarvelTitleCard,
'music': MusicTitleCard,
'musikmann': WhiteBorderTitleCard,
'notification': NotificationTitleCard,
'olivier': OlivierTitleCard,
'overline': OverlineTitleCard,
'phendrena': CutoutTitleCard,
'photo': FrameTitleCard,
'polygon': StripedTitleCard,
'polymath': StandardTitleCard,
'poster': PosterTitleCard,
'reality tv': LogoTitleCard,
'roman': RomanNumeralTitleCard,
'roman numeral': RomanNumeralTitleCard,
'shape': ShapeTitleCard,
'sherlock': TintedGlassTitleCard,
'spotify': MusicTitleCard,
'standard': StandardTitleCard,
'star wars': StarWarsTitleCard,
'striped': StripedTitleCard,
'textless': TextlessTitleCard,
'tinted frame': TintedFrameTitleCard,
'tinted glass': TintedGlassTitleCard,
'white border': WhiteBorderTitleCard,
}
__slots__ = ('episode', 'profile', 'converted_title', 'maker', 'file')
def __init__(self,
episode: 'Episode',
profile: 'Profile',
title_characteristics: dict,
**extra_characteristics,
) -> None:
"""
Constructs a new instance of this class.
Args:
episode: The episode whose TitleCard this corresponds to.
profile: The profile to apply to the creation of this title
card.
title_characteristics: Dictionary of characteristics from
the CardType class for this Episode to pass to
Title.apply_profile().
extra_characteristics: Any extra keyword arguments to pass
directly to the creation of the CardType object.
"""
# Store this card's associated episode and profile
self.episode = episode
self.profile = profile
# Apply the given profile to the Title
self.converted_title = episode.episode_info.title.apply_profile(
profile, **title_characteristics
)
# Apply any custom title text formatting if supplied
if 'title_text_format' in extra_characteristics:
try:
self.converted_title = extra_characteristics['title_text_format'].format(
title_text=self.converted_title,
**self.episode.episode_info.characteristics,
**extra_characteristics,
)
except Exception as exc:
log.error(f'Invalid title text format - {exc}')
# Initialize this episode's CardType instance
kwargs = {
'backdrop_file': episode.source.parent / 'backdrop.jpg',
'source_file': episode.source,
'card_file': episode.destination,
'title_text': self.converted_title,
'season_text': profile.get_season_text(
self.episode.episode_info,
getattr(self.episode.card_class, 'SEASON_TEXT_FORMATTER', None),
),
'episode_text': profile.get_episode_text(self.episode),
'hide_season_text': profile.hide_season_title,
'blur': episode.blur,
'grayscale': episode.grayscale,
'watched': episode.watched,
} | profile.font.attributes \
| self.episode.episode_info.indices \
| extra_characteristics
try:
self.maker = self.episode.card_class(**kwargs)
except Exception as e:
log.exception(f'Cannot initialize Card for {self.episode} - {e}')
self.maker = None
# File associated with this card is the episode's destination
self.file = episode.destination
@staticmethod
def get_output_filename(
format_string: str,
series_info: SeriesInfo,
episode_info: EpisodeInfo,
media_directory: Path
) -> Path:
"""
Get the output filename for a title card described by the given
values.
Args:
format_string: Format string that specifies how to construct
the filename.
series_info: SeriesInfo for this entry.
episode_info: EpisodeInfo to get filename of.
media_directory: Top-level media directory.
Returns:
Path for the full title card destination.
"""
# Get the season folder for this entry's season
season_folder = global_objects.pp.get_season_folder(
episode_info.season_number
)
# Get filename from the given format string, with illegals removed
abs_number = episode_info.abs_number
filename = CleanPath.sanitize_name(
format_string.format(
name=series_info.name,
full_name=series_info.full_name,
year=series_info.year,
title=episode_info.title.full_title,
season=episode_info.season_number,
episode=episode_info.episode_number,
abs_number=abs_number if abs_number is not None else 0,
)
)
# Add card extension
filename += global_objects.pp.card_extension
return media_directory / season_folder / filename
@staticmethod
def get_multi_output_filename(
format_string: str,
series_info: SeriesInfo,
multi_episode: 'MultiEpisode',
media_directory: Path
) -> Path:
"""
Get the output filename for a title card described by the given
values, and that represents a range of Episodes (not just one).
Args:
format_string: Format string that specifies how to construct
the filename.
series_info: Series info for this entry.
multi_episode: MultiEpisode object to get filename of.
media_directory: Top-level media directory.
Returns:
Path to the full title card destination.
"""
# If there is an episode key to modify, do so
if '{episode' in format_string:
# Replace existing episode number reference with start number
mod_format_string=format_string.replace('{episode','{episode_start')
# Episode number formatting with prefix
episode_text = match(
r'.*?(e?{episode_start.*?})', mod_format_string, IGNORECASE
).group(1)
# Duplicate episode text format for end text format
end_episode_text=episode_text.replace('episode_start','episode_end')
# Range of episode numbers
range_text = f'{episode_text}-{end_episode_text}'
# Completely modified format string with keys for start/end episodes
modified_format_string = sub(
r'e?{episode_start.*?}', range_text, mod_format_string,
flags=IGNORECASE
)
else:
# No episode key to modify, format the original string
modified_format_string = format_string
# # Get the season folder for these episodes
season_folder = global_objects.pp.get_season_folder(
multi_episode.season_number
)
# Get filename from the modified format string
abs_number = multi_episode.episode_info.abs_number
filename = CleanPath.sanitize_name(
modified_format_string.format(
name=series_info.name,
full_name=series_info.full_name,
year=series_info.year,
title=multi_episode.episode_info.title.full_title,
season=multi_episode.season_number,
episode_start=multi_episode.episode_start,
episode_end=multi_episode.episode_end,
abs_number=abs_number if abs_number is not None else 0,
)
)
# Add card extension
filename += global_objects.pp.card_extension
return media_directory / season_folder / filename
@staticmethod
def validate_card_format_string(format_string: str) -> bool:
"""
Return whether the given card filename format string is valid or
not.
Args:
format_string: Format string being validated.
Returns:
True if the given string can be formatted, False otherwise.
"""
try:
# Attempt to format using all the standard keys
format_string.format(
name='TestName', full_name='TestName (2000)', year=2000,
season=1, episode=1, title='Episode Title', abs_number=1,
)
return True
except Exception as e:
# Invalid format string, log
log.error(f'Card format string is invalid - "{e}"')
return False
def create(self) -> bool:
"""
Create this title card. If the card already exists, a new one is
not created. Return whether a card was created.
Returns:
True if a title card was created, False otherwise.
"""
# If card is invalid, exit
if self.maker is None or not self.maker.valid:
return False
# If the card already exists, exit
if self.file.exists():
return False
# Create parent folders if necessary for this card
self.file.parent.mkdir(parents=True, exist_ok=True)
# Create card
try:
self.maker.create()
except Exception as e:
log.exception(f'Error encountered while creating card for '
f'{self.episode} - {e}')
# Return whether card creation was successful or not
if self.file.exists():
log.debug(f'Created card "{self.file.resolve()}"')
return True
# Card doesn't exist, log commands to debug
log.debug(f'Could not create card "{self.file.resolve()}"')
self.maker.image_magick.print_command_history()
return False