1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
5 from PIL import Image, ImageFont, ImageDraw, ImageFilter
7 from librarian import get_resource, OutputFile, URLOpener
11 """Gets metrics from an object, scaling it by a factor."""
12 def __init__(self, obj, scale):
14 self._scale = float(scale)
16 def __getattr__(self, name):
17 src = getattr(self._obj, name)
18 if src and self._scale:
19 return type(src)(self._scale * src)
25 """Creates an Image with a series of centered strings."""
31 def __init__(self, max_width, max_height, padding_x=None, padding_y=None, bar_width=0, bar_color=None):
33 padding_x = self.SHADOW_X + self.SHADOW_BLUR
35 padding_y = self.SHADOW_Y + self.SHADOW_BLUR
37 self.max_width = max_width
38 self.bar_width = bar_width
39 self.bar_color = bar_color
40 self.max_text_width = max_width - 2 * padding_x - bar_width
41 self.padding_x = padding_x
42 self.padding_y = padding_y
43 self.height = padding_y
44 self.img = Image.new('RGBA', (max_width, max_height))
45 self.draw = ImageDraw.Draw(self.img)
46 self.shadow_img = None
47 self.shadow_draw = None
49 def skip(self, height):
50 """Skips some vertical space."""
53 def text(self, text, color='#000', font=None, line_height=20,
54 shadow_color=None, centering=True):
55 """Writes some centered text."""
56 text = re.sub(r'\s+', ' ', text)
58 if not self.shadow_img:
59 self.shadow_img = Image.new('RGBA', self.img.size)
60 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
63 line_width = self.draw.textsize(line, font=font)[0]
64 while line_width > self.max_text_width:
65 parts = line.rsplit(' ', 1)
67 line_width = self.max_text_width
71 if len(line) > 2 and line[-2] == ' ':
74 line_width = self.draw.textsize(line, font=font)[0]
75 line = line.strip() + ' '
78 pos_x = (self.max_width - line_width) // 2
80 pos_x = self.bar_width + self.padding_x
83 self.shadow_draw.text(
84 (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
85 line, font=font, fill=shadow_color
88 self.draw.text((pos_x, self.height), line, font=font, fill=color)
89 self.height += line_height
91 text = text[len(line):]
94 """Creates the actual Image object."""
95 image = Image.new('RGBA', (self.max_width,
96 int(round(self.height + self.padding_y))))
99 shadow = self.shadow_img.filter(ImageFilter.BLUR)
100 image.paste(shadow, (0, 0), shadow)
101 image.paste(self.img, (0, 0), self.img)
103 image.paste(self.img, (0, 0))
108 """Abstract base class for cover images generator."""
111 background_color = '#fff'
112 background_img = None
115 author_margin_left = 20
116 author_margin_right = 20
118 author_color = '#000'
120 author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
121 author_font_size = 30
124 title_margin_left = 20
125 title_margin_right = 20
129 title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
134 uses_dc_cover = False
146 'JPEG': 'image/jpeg',
150 def __init__(self, book_info, format=None, width=None, height=None, cover_logo=None):
151 self.book_info = book_info
153 self.predesigned = False
154 if book_info.cover_class == 'image':
155 self.predesigned = True
158 if book_info.cover_box_position == 'none':
159 self.predesigned = True
161 self.authors = [auth.readable() for auth in book_info.authors]
162 self.title = book_info.title
163 if format is not None:
165 self.set_size(width, height)
167 def set_size(self, width, height):
169 self.height = int(round(height * self.width / width))
170 scale = max(float(width or 0) / self.width,
171 float(height or 0) / self.height)
175 self.scale_after = scale
177 def pretty_authors(self):
178 """Allows for decorating authors' names."""
181 def pretty_title(self):
182 """Allows for decorating title."""
186 metr = Metric(self, self.scale)
187 img = Image.new('RGB', (metr.width, metr.height),
188 self.background_color)
190 if self.background_img:
191 background = Image.open(self.background_img)
192 img.paste(background, None, background)
197 logo = Image.open(get_resource('res/wl-logo.png'))
200 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
203 (metr.width - metr.logo_width) // 2,
204 img.size[1] - logo.size[1] - metr.logo_bottom
207 top = metr.author_top
209 metr.width - metr.author_margin_left - metr.author_margin_right,
213 author_font = ImageFont.truetype(
214 self.author_font_ttf, metr.author_font_size,
215 layout_engine=ImageFont.Layout.BASIC)
216 for pa in self.pretty_authors():
217 tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
219 text_img = tbox.image()
220 img.paste(text_img, (metr.author_margin_left, top), text_img)
222 top += text_img.size[1] + metr.title_top
224 metr.width - metr.title_margin_left - metr.title_margin_right,
227 title_font = ImageFont.truetype(
228 self.title_font_ttf, metr.title_font_size,
229 layout_engine=ImageFont.Layout.BASIC)
230 tbox.text(self.pretty_title(), self.title_color, title_font,
231 metr.title_lineskip, self.title_shadow)
232 text_img = tbox.image()
233 img.paste(text_img, (metr.title_margin_left, top), text_img)
237 def final_image(self):
239 if self.scale_after != 1:
241 int(round(img.size[0] * self.scale_after)),
242 int(round(img.size[1] * self.scale_after))),
243 Image.Resampling.LANCZOS)
247 return self.mime_types[self.format]
250 return self.exts[self.format]
252 def save(self, *args, **kwargs):
254 'format': self.format,
257 default_kwargs.update(kwargs)
258 return self.final_image().save(*args, **default_kwargs)
260 def output_file(self, *args, **kwargs):
262 self.save(imgstr, *args, **kwargs)
263 return OutputFile.from_bytes(imgstr.getvalue())
266 class WLCover(Cover):
267 """Wolne Lektury cover without logos."""
271 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
272 author_font_size = 20
274 author_centering = True
275 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
278 title_box_width = 350
279 title_centering = True
282 box_bottom_margin = 100
297 box_position = 'middle'
298 background_color = '#444'
299 author_color = '#444'
300 background_img = get_resource('res/cover.png')
301 background_top = False
305 'Starożytność': '#9e3610',
306 'Średniowiecze': '#564c09',
307 'Renesans': '#8ca629',
309 'Oświecenie': '#f2802e',
310 'Romantyzm': '#db4b16',
311 'Pozytywizm': '#961060',
312 'Modernizm': '#7784e0',
313 'Dwudziestolecie międzywojenne': '#3044cf',
314 'Współczesność': '#06393d',
316 set_title_color = True
318 kind_box_position = {
323 def __init__(self, book_info, format=None, width=None, height=None,
324 bleed=0, cover_logo=None):
325 super(WLCover, self).__init__(book_info, format=format, width=width,
328 self.slug = book_info.url.slug
330 self.box_position = book_info.cover_box_position or \
331 self.kind_box_position.get(book_info.kind, self.box_position)
333 if book_info.cover_bar_color == 'none':
336 self.bar_color = book_info.cover_bar_color or \
337 self.get_variable_color(book_info) or self.bar_color
339 if self.set_title_color:
340 self.title_color = self.get_variable_color(book_info) or self.title_color
343 self.box_top_margin += bleed
344 self.box_bottom_margin += bleed
345 self.bar_width += bleed
347 if book_info.cover_url:
348 url = book_info.cover_url
354 bg_src = requests.get(url, timeout=5)
355 self.background_img = BytesIO(bg_src.content)
357 except Exception as e:
365 def get_variable_color(self, book_info):
366 return self.epoch_colors.get(book_info.epoch, None)
368 def pretty_authors(self):
369 return [a.upper() for a in self.authors]
371 def add_box(self, img):
372 if self.box_position == 'none':
375 metr = Metric(self, self.scale)
378 box = TextBox(metr.title_box_width - 2 * self.bleed, metr.height,
379 padding_y=metr.box_padding_y,
380 padding_x=metr.box_padding_x,
381 bar_width=metr.box_bar_width,
382 bar_color=self.bar_color,
384 author_font = ImageFont.truetype(
385 self.author_font_ttf, metr.author_font_size,
386 layout_engine=ImageFont.Layout.BASIC)
387 for pa in self.pretty_authors():
388 box.text(pa, font=author_font, line_height=metr.author_lineskip,
389 color=self.author_color, shadow_color=self.author_shadow,
390 centering=self.author_centering
393 box.skip(metr.box_above_line)
395 (metr.box_line_left, box.height, metr.box_line_right, box.height),
396 fill=self.author_color, width=metr.box_line_width
398 box.skip(metr.box_below_line)
401 title_font = ImageFont.truetype(
402 self.title_font_ttf, metr.title_font_size,
403 layout_engine=ImageFont.Layout.BASIC)
404 box.text(self.pretty_title(),
405 line_height=metr.title_lineskip,
407 color=self.title_color,
408 shadow_color=self.title_shadow,
409 centering=self.title_centering
412 box_img = box.image()
415 if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
416 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
417 elif self.box_position == 'top':
418 box_top = metr.box_top_margin
420 box_top = (metr.height - box_img.size[1]) // 2
422 box_left = metr.bar_width + (
423 metr.width - metr.bar_width - box_img.size[0] - self.bleed
426 # Draw the white box.
427 img_draw = ImageDraw.Draw(img)
432 box_left + box_img.size[0],
433 box_top + box_img.size[1]
437 # Paste the contents into the white box.
438 img.paste(box_img, (box_left, box_top), box_img)
439 if self.box_bar_width:
444 box_left + metr.box_bar_width,
445 box_top + box_img.size[1]
451 def add_cut_lines(self, img):
455 metr = Metric(self, self.scale)
456 draw = ImageDraw.Draw(img)
457 for corner_x, corner_y in (
458 (0, 0), (metr.width, 0),
459 (0, metr.height), (metr.width, metr.height)
461 dir_x = 1 if corner_x == 0 else -1
462 dir_y = 1 if corner_y == 0 else -1
463 for offset in (-1, 0, 1):
467 corner_y + dir_y * metr.bleed + offset,
468 corner_x + dir_x * metr.bleed * line_ratio,
469 corner_y + dir_y * metr.bleed + offset
471 fill='black' if offset == 0 else 'white',
476 corner_x + dir_x * metr.bleed + offset,
478 corner_x + dir_x * metr.bleed + offset,
479 corner_y + dir_y * metr.bleed * line_ratio
481 fill='black' if offset == 0 else 'white',
487 metr = Metric(self, self.scale)
488 img = Image.new('RGB', (metr.width, metr.height),
489 self.background_color)
490 draw = ImageDraw.Draw(img)
492 draw.rectangle((0, 0, metr.bar_width, metr.height),
495 if self.background_img:
496 src = Image.open(self.background_img)
497 trg_size = (metr.width - metr.bar_width, metr.height)
498 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
501 int(round(src.size[1] * trg_size[0] / src.size[0]))
503 if self.background_top:
506 cut = (resized[1] - trg_size[1]) // 2
507 src = src.resize(resized, Image.Resampling.LANCZOS)
508 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
511 int(round(src.size[0] * trg_size[1] / src.size[1])),
514 cut = (resized[0] - trg_size[0]) // 2
515 src = src.resize(resized, Image.Resampling.LANCZOS)
516 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
518 img.paste(src, (metr.bar_width, 0))
521 img = self.add_box(img)
523 # img = self.add_cut_lines(img)
528 class WLNoBoxCover(WLCover):
529 def add_box(self, img):
533 class LogoWLCover(WLCover):
536 gradient_logo_height = 57
537 gradient_logo_max_width = 200
538 gradient_logo_margin_right = 30
539 gradient_logo_spacing = 40
540 gradient_color = '#000'
541 gradient_opacity = .6
543 'res/wl-logo-white.png',
544 'res/fnp-logo-white.png',
547 annotation_height = 10
550 gradient_logo_centering = False
555 def __init__(self, book_info, *args, cover_logo=None, **kwargs):
556 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
557 self.gradient_height += self.bleed
558 self.gradient_logo_margin_right += self.bleed
560 self.additional_cover_logos = [
561 BytesIO(URLOpener().open(cover_logo_url).read())
562 for cover_logo_url in book_info.cover_logo_urls
564 self.end_cover_logos = []
566 self.additional_cover_logos.append(
567 open(cover_logo, 'rb')
571 def has_gradient_logos(self):
572 return self.gradient_logos or self.additional_cover_logos or self.end_cover_logos or self.annotation or self.qrcode is not None
574 def add_gradient_logos(self, img, metr):
575 gradient = Image.new(
577 (metr.width - metr.bar_width, metr.gradient_height),
580 gradient_mask = Image.new(
582 (metr.width - metr.bar_width, metr.gradient_height)
584 draw = ImageDraw.Draw(gradient_mask)
585 for line in range(0, metr.gradient_easing):
587 (0, line, metr.width - metr.bar_width, line),
589 255 * self.gradient_opacity * line / metr.gradient_easing
593 0, metr.gradient_easing,
594 metr.width - metr.bar_width, metr.gradient_height
595 ), fill=int(255 * self.gradient_opacity))
599 (metr.bar_width, metr.height - metr.gradient_height),
603 cursor = metr.width - metr.gradient_logo_margin_right
605 cursor = metr.gradient_logo_margin_right
608 - metr.gradient_height / 2
609 - metr.gradient_logo_height / 2 - metr.bleed
613 get_resource(logo_path)
614 for logo_path in self.gradient_logos
617 logos = self.additional_cover_logos + logos + self.end_cover_logos
620 Image.open(logo_bytes).convert('RGBA')
621 for logo_bytes in logos
624 if self.qrcode is not None:
626 logos.append(qrcode.make(f'https://wolnelektury.pl/katalog/lektura/{self.slug}/?{self.qrcode}'))
631 # See if logos fit into the gradient. If not, scale down accordingly.
635 - 2 * metr.gradient_logo_margin_right + self.bleed
639 metr.gradient_logo_max_width,
640 logo.size[0] * metr.gradient_logo_height / logo.size[1]
643 taken_space = sum(widths) + (len(logos) - 1) * metr.gradient_logo_spacing
644 if taken_space > space_for_logos:
645 logo_scale = space_for_logos / taken_space
648 if self.gradient_logo_centering:
649 cursor += int((space_for_logos - taken_space) / 2)
651 space_for_logos / taken_space
652 if taken_space > space_for_logos else 1
654 #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
656 for i, logo in enumerate(logos):
661 L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
665 int(round(widths[i] * L_scale)),
667 logo.size[1] * widths[i] / logo.size[0] * L_scale
670 Image.Resampling.LANCZOS)
672 cursor -= logo.size[0]
679 #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
684 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
686 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
689 img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
690 draw = ImageDraw.Draw(img2)
691 author_font = ImageFont.truetype(
692 self.author_font_ttf, metr.annotation_height,
693 layout_engine=ImageFont.Layout.BASIC)
694 draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
696 img2 = img2.rotate(90)
699 img.alpha_composite(img2, (0, 0))
700 img = img.convert('RGB')
705 img = super(LogoWLCover, self).image()
706 metr = Metric(self, self.scale)
707 if self.has_gradient_logos:
708 img = self.add_gradient_logos(img, metr)
712 class LegimiCover(LogoWLCover):
718 author_font_ttf = get_resource('fonts/Lora-Regular.ttf')
719 author_font_size = 15
720 author_lineskip = 19.5
721 author_centering = False
722 title_font_ttf = get_resource('fonts/Lora-Bold.ttf')
724 title_lineskip = 19.5
725 title_centering = False
727 title_box_width = 210
729 box_bottom_margin = 20
731 box_padding_y = 10 # do baseline
745 box_position = 'bottom'
746 background_color = '#444'
747 author_color = '#000'
749 set_title_color = False
751 kind_box_position = {}
753 box_bottom_margin_logos_add = 10
756 gradient_logo_height = 20
757 gradient_logo_max_width = 200
758 gradient_logo_margin_right = 10
759 gradient_logo_spacing = 20
760 gradient_color = '#000'
761 gradient_opacity = .5
763 'res/wl-logo-white.png',
766 gradient_logo_centering = True
767 background_top = True
770 'Artykuł': '#bf001a',
771 'Artykuł naukowy': '#bf001a',
772 'Dziennik': '#bf001a',
774 'Felieton': '#bf001a',
775 'Kronika': '#bf001a',
777 'Manifest': '#bf001a',
779 'Pamiętnik': '#bf001a',
780 'Poradnik': '#bf001a',
781 'Praca naukowa': '#bf001a',
782 'Publicystyka': '#bf001a',
783 'Reportaż': '#bf001a',
784 'Reportaż podróżniczy': '#bf001a',
785 'Rozprawa': '#bf001a',
786 'Rozprawa polityczna': '#bf001a',
787 'Traktat': '#bf001a',
795 def __init__(self, *args, **kwargs):
796 super().__init__(*args, **kwargs)
797 if self.has_gradient_logos:
798 self.box_bottom_margin += self.box_bottom_margin_logos_add
800 def pretty_authors(self):
803 def get_variable_color(self, book_info):
804 for genre in book_info.genres:
805 if genre in self.genre_colors:
806 return self.genre_colors[genre]
807 for kind in book_info.kinds:
808 if kind in self.kind_colors:
809 return self.kind_colors[kind]
811 class LegimiCornerCover(LegimiCover):
814 corner_image = get_resource('res/book-band.png')
817 image = super().image()
818 metr = Metric(self, self.scale)
820 if self.corner_image:
821 corner = Image.open(self.corner_image).convert('RGBA')
822 corner = corner.resize(
824 int(round(metr.corner_width)),
825 int(round(corner.size[1] / corner.size[0] * metr.corner_width))
828 image.paste(corner, (
829 metr.width - int(round(metr.corner_width)),
834 class LegimiAudiobookCover(LegimiCornerCover):
836 corner_image = get_resource('res/audiobook-sticker.png')
840 class EbookpointCover(LogoWLCover):
841 gradient_logo_height = 58
842 gradient_logo_spacing = 25
844 'res/ebookpoint-logo-white.png',
845 'res/wl-logo-white.png',
846 'res/fnp-logo-white.png',
850 class VirtualoCover(Cover):
859 class PrestigioCover(Cover):
862 background_img = get_resource('res/cover-prestigio.png')
865 author_margin_left = 118
866 author_margin_right = 62
868 author_color = '#fff'
869 author_shadow = '#000'
870 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
871 author_font_size = 50
874 title_margin_left = 118
875 title_margin_right = 62
878 title_shadow = '#000'
879 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
882 def pretty_title(self):
883 return "„%s”" % self.title
886 class BookotekaCover(Cover):
889 background_img = get_resource('res/cover-bookoteka.png')
892 author_margin_left = 307
893 author_margin_right = 233
894 author_lineskip = 156
895 author_color = '#d9d919'
896 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
897 author_font_size = 130
900 title_margin_left = 307
901 title_margin_right = 233
903 title_color = '#d9d919'
904 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
905 title_font_size = 140
910 class GandalfCover(Cover):
913 background_img = get_resource('res/cover-gandalf.png')
914 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
915 author_font_size = 30
916 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
923 class KMLUCover(LogoWLCover):
924 gradient_logo_height = 58
925 gradient_logo_spacing = 25
927 'res/kmlu-logo-white.png',
928 'res/wl-logo-white.png',
929 'res/fnp-logo-white.png',
933 class MPWCover(LogoWLCover):
934 gradient_logo_height = 57
935 gradient_logo_spacing = 25
937 'res/mpw-logo-white.png',
938 'res/wl-logo-white.png',
939 'res/fnp-logo-white.png',
943 class AtriumCover(LogoWLCover):
944 gradient_logo_height = 58
945 gradient_logo_spacing = 25
947 'res/atrium-logo.png',
948 'res/wl-logo-white.png',
949 'res/fnp-logo-white.png',
953 class BNCover(LogoWLCover):
955 'res/dofinansowano.png',
958 'res/wl-logo-white.png',
960 # annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
963 class FactoryCover(LogoWLCover):
966 'res/wl-logo-white.png',
968 qrcode = 'pk_campaign=factory22'
971 def __init__(self, *args, **kwargs):
972 kwargs.setdefault('bleed', 10)
973 return super().__init__(*args, **kwargs)
978 def output_file(self, *args, **kwargs):
979 imgfile = super().output_file(*args, **kwargs)
982 with tempfile.TemporaryDirectory(prefix='factory-', dir='.') as d:
985 with open(d + '/cover.png', 'wb') as f:
986 f.write(imgfile.get_bytes())
987 shutil.copy(get_resource('res/factory-cover.svg'), d)
988 subprocess.call(['inkscape', f'--export-filename={d}/cover.pdf', d + '/factory-cover.svg'])
989 with open(d + '/cover.pdf', 'rb') as f:
990 return OutputFile.from_bytes(f.read())
994 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
997 'legacy': LogoWLCover,
1000 'atrium': AtriumCover,
1002 'legimi': LegimiCover,
1003 'legimi-corner': LegimiCornerCover,
1004 'legimi-audiobook': LegimiAudiobookCover,
1005 'factory': FactoryCover,
1007 'm-label': LabelMarquiseCover,
1008 'default': MarquiseCover,
1012 def make_cover(book_info, *args, **kwargs):
1013 cover_class_name = None
1014 if 'cover_class' in kwargs:
1015 cover_class_name = kwargs.pop('cover_class')
1016 if not cover_class_name:
1017 cover_class_name = 'default'
1018 cover_class = COVER_CLASSES[cover_class_name]
1019 return cover_class(book_info, *args, **kwargs)