-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathBaseCardType.py
More file actions
executable file
·617 lines (465 loc) · 16.6 KB
/
Copy pathBaseCardType.py
File metadata and controls
executable file
·617 lines (465 loc) · 16.6 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
from abc import abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Iterable, Optional, Union
from titlecase import titlecase
from modules.Debug import log
from modules.ImageMaker import ImageMaker, Dimensions
if TYPE_CHECKING:
from modules.Font import Font
from modules.PreferenceParser import PreferenceParser
ImageMagickCommands = list[str]
class Coordinate:
"""Class that defines a single Coordinate on an x/y plane."""
__slots__ = ('x', 'y')
def __init__(self, x: float, y: float) -> None:
"""Initialize this Coordinate with the given x/y coordinates."""
self.x = x
self.y = y
def __iter__(self) -> Iterable[tuple[float, float]]:
"""
Iterate through this object. This can be used to unpack the
Coordinate, for example:
>>> x, y = Coordinate(1, 2) # x=1, y=2
"""
return iter((self.x, self.y))
def __add__(self,
other: Union['Coordinate', tuple[float, float]],
) -> 'Coordinate':
"""
Add the given coordinates to this object, returning a new
combination of the two.
Args:
other: The Coordinate to add.
Returns:
Newly constructed Coordinate object of these coordinates.
"""
if isinstance(other, Coordinate):
return Coordinate(self.x + other.x, self.y + other.y)
return Coordinate(self.x + other[0], self.y + other[1])
def __iadd__(self,
other: Union['Coordinate', tuple[float, float]],
) -> 'Coordinate':
"""
Add the given Coordinate to this one. This adds the x/y
positions individually.
Args:
other: The Coordinate to add.
Returns:
This object.
"""
if isinstance(other, Coordinate):
self.x += other.x
self.y += other.y
else:
self.x += other[0]
self.y += other[1]
return self
def __repr__(self) -> str:
"""
Detailed object representation.
>>> repr(Coordinate(2, 3))
'Coordinate(2, 3)'
"""
return f'Coordinate({self.x}, {self.y})'
def __str__(self) -> str:
"""
Represent this Coordinate as a string.
>>> str(Coordinate(1.2, 3.4))
'1,2'
"""
return f'{self.x:.0f},{self.y:.0f}'
@property
def as_svg(self) -> str:
"""SVG representation of this Coordinate."""
return f'{self.x:.1f} {self.y:.1f}'
class Line:
"""Class that defines a drawable SVG line."""
__slots__ = ('start', 'end')
def __init__(self, start: Coordinate, end: Coordinate) -> None:
"""
Initialize a Line which spans between the given start and end
Coordinates.
Args:
start: Coordinate which defines one end of this line.
end: Coordinate which defines the other end of this line.
"""
self.start = start
self.end = end
def __str__(self) -> str:
"""Represent this Line as a string. This is a SVG-command."""
return f'M {str(self.start)} L {str(self.end)}'
def draw(self) -> str:
"""Draw this line."""
return fr'-draw "path \'{str(self)}\'"'
class Rectangle:
"""Class that defines movable SVG rectangle."""
__slots__ = ('start', 'end')
def __init__(self, start: Coordinate, end: Coordinate) -> None:
"""
Initialize this Rectangle that encompasses the given start and
end Coordinates. These Coordinates are the opposite corners of
the rectangle.
Args:
start: Coordinate which defines one starting corner of the
rectangle.
end: Coordinate which opposites the `start` coordinate of
this rectangle.
"""
self.start = start
self.end = end
def __repr__(self) -> str:
"""Unambigious representation of this object."""
return f'Rectangle({self.start!r}, {self.end!r})'
def __str__(self) -> str:
"""
Represent this Rectangle as a string. This is the joined string
representation of the start and end coordinate.
"""
return f'{str(self.start)},{str(self.end)}'
@property
def width(self) -> float:
"""Width of this Rectangle."""
return abs(self.start.x - self.end.x)
@property
def height(self) -> float:
"""Height of this Rectangle."""
return abs(self.start.y - self.end.y)
def draw(self) -> str:
"""Draw this Rectangle."""
return f'-draw "rectangle {str(self)}"'
class Shadow:
"""Class which defines a shadow string."""
__slots__ = ('opacity', 'sigma', 'x', 'y')
def __init__(self,
*,
opacity: int = 95,
sigma: int = 2,
x: int = 10,
y: int = 10,
) -> None:
"""Construct a shadow with the given parameters."""
self.opacity = opacity
self.sigma = sigma
self.x = x
self.y = y
def __str__(self) -> str:
"""String representation of this shadow effect."""
return f'{self.opacity}x{self.sigma}{self.x:+}{self.y:+}'
@property
def as_command(self) -> str:
"""Wrapper for `__str__`."""
return str(self)
class BaseCardType(ImageMaker):
"""
This class describes an abstract card type. A BaseCardType is a
subclass of ImageMaker, because all CardTypes are designed to create
title cards. This class outlines the requirements for creating a
custom type of title card.
All implementations of BaseCardType must implement this class's
abstract properties and methods in order to work with TCM.
"""
"""Default case string for all title text"""
DEFAULT_FONT_CASE = 'upper'
"""Default font replacements"""
FONT_REPLACEMENTS = {}
"""Mapping of 'case' strings to format functions"""
CASE_FUNCTIONS: dict[str, Callable[[Any], str]] = {
'blank': lambda _: '',
'lower': str.lower,
'source': str,
'title': titlecase,
'upper': str.upper,
}
"""Default episode text format string, can be overwritten by each class"""
EPISODE_TEXT_FORMAT = 'EPISODE {episode_number}'
"""Whether this class uses unique source images for card creation"""
USES_UNIQUE_SOURCES = True
"""Whether this class uses Source Images at all"""
USES_SOURCE_IMAGES = True
"""Standard size for all title cards"""
WIDTH = 3200
HEIGHT = 1800
TITLE_CARD_SIZE = f'{WIDTH}x{HEIGHT}'
"""Standard blur effect to apply to spoiler-free images"""
BLUR_PROFILE = '0x60'
@property
@abstractmethod
def ARCHIVE_NAME(self) -> str:
"""How to name archive directories for this type of card"""
raise NotImplementedError
@property
@abstractmethod
def TITLE_FONT(self) -> str:
"""
Standard font (full path or ImageMagick recognized font name) to
use for the episode title text.
"""
raise NotImplementedError
@property
@abstractmethod
def TITLE_COLOR(self) -> str:
"""Standard color to use for the episode title text"""
raise NotImplementedError
@property
@abstractmethod
def USES_SEASON_TITLE(self) -> bool:
"""Whether this class uses season titles for archives"""
raise NotImplementedError
"""Slots for standard style attributes"""
__slots__ = ('valid', 'blur', 'grayscale')
@abstractmethod
def __init__(self,
blur: bool = False,
grayscale: bool = False,
*,
preferences: Optional['PreferenceParser'] = None,
**unused,
) -> None:
"""
Construct a new CardType. Must call super().__init__() to
initialize the parent ImageMaker class (for PreferenceParser and
ImageMagickInterface objects).
Args:
blur: Whether to blur the source image. Defaults to False.
grayscale: Whether to convert the source image to grayscale.
Defaults to False.
"""
# Initialize parent ImageMaker
super().__init__(preferences=preferences)
# Object starts as valid
self.valid = True
# Store style attributes
self.blur = blur
self.grayscale = grayscale
def __repr__(self) -> str:
"""Returns an unambiguous string representation of the object."""
attributes = ', '.join(
f'{attr}={getattr(self, attr)!r}' for attr in self.__slots__
if not attr.startswith('__')
)
return f'<{self.__class__.__name__} {attributes}>'
@staticmethod
def modify_extras( # pylint: disable=unused-argument
extras: dict,
custom_font: bool,
custom_season_titles: bool,
) -> None:
"""
Modify the given extras base on whether font or season titles
are custom. The default behavior is to not modify the extras at
all.
Args:
extras: Dictionary to modify.
custom_font: Whether the font are custom.
custom_season_titles: Whether the season titles are custom.
"""
return None
@classmethod
def _is_custom_font(
cls: type['BaseCardType'],
font: 'Font',
) -> bool:
"""
Whether the given font is custom based on all the standard
font definitions of this class.
Args:
font: Font being evaluated.
Returns:
True if the given Font is customized, False otherwise.
"""
return ((font.color != cls.TITLE_COLOR)
or (font.file != cls.TITLE_FONT)
or (font.interline_spacing != 0)
or (font.interword_spacing != 0)
or (font.kerning != 1.0)
or (font.size != 1.0)
or (font.stroke_width != 1.0)
or (font.vertical_shift != 0)
)
@staticmethod
@abstractmethod
def is_custom_font(font: 'Font', extras: dict) -> bool:
"""
Abstract method to determine whether the given font
characteristics indicate the use of a custom font or not.
Returns:
True if a custom font is indicated, False otherwise.
"""
raise NotImplementedError
@staticmethod
@abstractmethod
def is_custom_season_titles(
custom_episode_map: bool,
episode_text_format: str,
) -> bool:
"""
Abstract method to determine whether the given season
characteristics indicate the use of a custom season title or not.
Returns:
True if a custom season title is indicated, False otherwise.
"""
raise NotImplementedError
@property
def resize(self) -> ImageMagickCommands:
"""
ImageMagick commands to only resize an image to the output title
card size.
"""
return [
# Use 4:4:4 sampling by default
f'-sampling-factor 4:4:4',
# Full sRGB colorspace on source image
f'-set colorspace sRGB',
# Ignore profile conversion warnings
f'+profile "*"',
# Background resize shouldn't fill with any color
f'-background transparent',
f'-gravity center',
# Fit to title card size
f'-resize "{self.TITLE_CARD_SIZE}^"',
f'-extent "{self.TITLE_CARD_SIZE}"',
]
@property
def style(self) -> ImageMagickCommands:
"""
ImageMagick commands to apply any style modifiers to an image.
"""
return [
# Use 4:4:4 sampling by default
f'-sampling-factor 4:4:4',
# Full sRGB colorspace on source image
f'-set colorspace sRGB',
# Ignore profile conversion warnings
f'+profile "*"',
# Optionally blur
f'-blur {self.BLUR_PROFILE}' if self.blur else '',
# Optionally set gray colorspace
f'-colorspace gray' if self.grayscale else '',
# Reset to full colorspace
f'-set colorspace sRGB' if self.grayscale else '',
]
@property
def resize_and_style(self) -> ImageMagickCommands:
"""
ImageMagick commands to resize and apply any style modifiers to
an image.
"""
return [
# Use 4:4:4 sampling by default
f'-sampling-factor 4:4:4',
# Full sRGB colorspace on source image
f'-set colorspace sRGB',
# Ignore profile conversion warnings
f'+profile "*"',
# Background resize shouldn't fill with any color
f'-background transparent',
f'-gravity center',
# Fit to title card size
f'-resize "{self.TITLE_CARD_SIZE}^"',
f'-extent "{self.TITLE_CARD_SIZE}"',
# Optionally blur
f'-blur {self.BLUR_PROFILE}' if self.blur else '',
# Optionally set gray colorspace
f'-colorspace gray' if self.grayscale else '',
# Reset to full colorspace
f'-set colorspace sRGB',
]
def add_overlay_mask(self,
file: Path,
/,
*,
pre_processing: Optional[ImageMagickCommands] = None,
x: int = 0,
y: int = 0,
) -> ImageMagickCommands:
"""
ImageMagick commands to add a top-level mask to the image.
Args:
file: Path to the file to search for the mask image
alongside.
pre_processing: Any ImageMagick commands to apply to the
mask before it is overlaid.
x: Offset X-coordinate to use when compositing the mask.
y: Offset Y-coordinate to use when compositing the mask.
Returns:
List of ImageMagick commands.
"""
# Do not apply any masks for stylized cards
if self.blur or self.grayscale:
return []
# Look for mask file corresponding to this source image
# Prioritize episode-specific mask, then general mask
if (mask := list(file.parent.glob(f'{file.stem}-mask.*'))):
mask = mask[0]
elif (mask := list(file.parent.glob(f'{file.stem}_mask.*'))):
mask = mask[0]
elif (mask := list(file.parent.glob(f'mask.*'))):
mask = mask[0]
else:
return []
log.debug(f'Identified mask image "{mask.resolve()}"')
if pre_processing is None:
pre_processing = self.resize_and_style
return [
fr'\( "{mask.resolve()}"',
*self.resize,
*pre_processing,
fr'\) -geometry {x:+}{y:+}',
f'-composite',
]
@property
def resize_output(self) -> ImageMagickCommands:
"""
ImageMagick commands to resize the card to the global card
dimensions.
"""
return [
f'-sampling-factor 4:4:4',
f'-set colorspace sRGB',
f'+profile "*"',
f'-background transparent',
f'-gravity center',
f'-resize "{self.preferences.card_dimensions}"',
f'-extent "{self.preferences.card_dimensions}"',
]
def add_drop_shadow(self,
commands: ImageMagickCommands,
shadow: Union[str, Shadow],
x: int = 0,
y: int = 0,
*,
shadow_color: str = 'black',
) -> ImageMagickCommands:
"""
Amend the given commands to apply a drop shadow effect.
Args:
commands: List of commands being modified. Must contain some
image definition that can be cloned.
shadow: IM Shadow string - i.e. `85x10+10+10`.
x: X-position of the offset to apply when compositing.
y: Y-position of the offset to apply when compositing.
shadow_color: Color of the shadow to add.
Returns:
List of ImageMagick commands.
"""
return [
fr'\(',
*commands,
fr'\( +clone',
f'-background "{shadow_color}"',
fr'-shadow {shadow} \)',
f'+swap',
f'-background None',
f'-layers merge',
fr'+repage \)',
f'-geometry {x:+.0f}{y:+.0f}',
f'-composite',
]
@abstractmethod
def create(self) -> None:
"""
Abstract method to create the title card outlined by the
CardType. All implementations of this method should delete any
intermediate files.
"""
raise NotImplementedError