1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import unicode_literals
9 from PIL import Image, ImageFont, ImageDraw, ImageFilter
10 from six import BytesIO
11 from librarian import get_resource, OutputFile, URLOpener
15 """Gets metrics from an object, scaling it by a factor."""
16 def __init__(self, obj, scale):
18 self._scale = float(scale)
20 def __getattr__(self, name):
21 src = getattr(self._obj, name)
22 if src and self._scale:
23 return type(src)(self._scale * src)
28 class TextBox(object):
29 """Creates an Image with a series of centered strings."""
35 def __init__(self, max_width, max_height, padding_x=None, padding_y=None, bar_width=0, bar_color=None):
37 padding_x = self.SHADOW_X + self.SHADOW_BLUR
39 padding_y = self.SHADOW_Y + self.SHADOW_BLUR
41 self.max_width = max_width
42 self.bar_width = bar_width
43 self.bar_color = bar_color
44 self.max_text_width = max_width - 2 * padding_x - bar_width
45 self.padding_x = padding_x
46 self.padding_y = padding_y
47 self.height = padding_y
48 self.img = Image.new('RGBA', (max_width, max_height))
49 self.draw = ImageDraw.Draw(self.img)
50 self.shadow_img = None
51 self.shadow_draw = None
53 def skip(self, height):
54 """Skips some vertical space."""
57 def text(self, text, color='#000', font=None, line_height=20,
58 shadow_color=None, centering=True):
59 """Writes some centered text."""
60 text = re.sub(r'\s+', ' ', text)
62 if not self.shadow_img:
63 self.shadow_img = Image.new('RGBA', self.img.size)
64 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
67 line_width = self.draw.textsize(line, font=font)[0]
68 while line_width > self.max_text_width:
69 parts = line.rsplit(' ', 1)
71 line_width = self.max_text_width
75 if len(line) > 2 and line[-2] == ' ':
78 line_width = self.draw.textsize(line, font=font)[0]
79 line = line.strip() + ' '
82 pos_x = (self.max_width - line_width) // 2
84 pos_x = self.bar_width + self.padding_x
87 self.shadow_draw.text(
88 (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
89 line, font=font, fill=shadow_color
92 self.draw.text((pos_x, self.height), line, font=font, fill=color)
93 self.height += line_height
95 text = text[len(line):]
98 """Creates the actual Image object."""
99 image = Image.new('RGBA', (self.max_width,
100 int(round(self.height + self.padding_y))))
103 shadow = self.shadow_img.filter(ImageFilter.BLUR)
104 image.paste(shadow, (0, 0), shadow)
105 image.paste(self.img, (0, 0), self.img)
107 image.paste(self.img, (0, 0))
112 """Abstract base class for cover images generator."""
115 background_color = '#fff'
116 background_img = None
119 author_margin_left = 20
120 author_margin_right = 20
122 author_color = '#000'
124 author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
125 author_font_size = 30
128 title_margin_left = 20
129 title_margin_right = 20
133 title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
138 uses_dc_cover = False
150 'JPEG': 'image/jpeg',
154 def __init__(self, book_info, format=None, width=None, height=None, cover_logo=None):
155 self.book_info = book_info
157 self.predesigned = False
158 if book_info.cover_class == 'image':
159 self.predesigned = True
162 if book_info.cover_box_position == 'none':
163 self.predesigned = True
165 self.authors = [auth.readable() for auth in book_info.authors]
166 self.title = book_info.title
167 if format is not None:
169 self.set_size(width, height)
171 def set_size(self, width, height):
173 self.height = int(round(height * self.width / width))
174 scale = max(float(width or 0) / self.width,
175 float(height or 0) / self.height)
179 self.scale_after = scale
181 def pretty_authors(self):
182 """Allows for decorating authors' names."""
185 def pretty_title(self):
186 """Allows for decorating title."""
190 metr = Metric(self, self.scale)
191 img = Image.new('RGB', (metr.width, metr.height),
192 self.background_color)
194 if self.background_img:
195 background = Image.open(self.background_img)
196 img.paste(background, None, background)
201 logo = Image.open(get_resource('res/wl-logo.png'))
204 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
207 (metr.width - metr.logo_width) // 2,
208 img.size[1] - logo.size[1] - metr.logo_bottom
211 top = metr.author_top
213 metr.width - metr.author_margin_left - metr.author_margin_right,
217 author_font = ImageFont.truetype(
218 self.author_font_ttf, metr.author_font_size,
219 layout_engine=ImageFont.LAYOUT_BASIC)
220 for pa in self.pretty_authors():
221 tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
223 text_img = tbox.image()
224 img.paste(text_img, (metr.author_margin_left, top), text_img)
226 top += text_img.size[1] + metr.title_top
228 metr.width - metr.title_margin_left - metr.title_margin_right,
231 title_font = ImageFont.truetype(
232 self.title_font_ttf, metr.title_font_size,
233 layout_engine=ImageFont.LAYOUT_BASIC)
234 tbox.text(self.pretty_title(), self.title_color, title_font,
235 metr.title_lineskip, self.title_shadow)
236 text_img = tbox.image()
237 img.paste(text_img, (metr.title_margin_left, top), text_img)
241 def final_image(self):
243 if self.scale_after != 1:
245 int(round(img.size[0] * self.scale_after)),
246 int(round(img.size[1] * self.scale_after))),
251 return self.mime_types[self.format]
254 return self.exts[self.format]
256 def save(self, *args, **kwargs):
258 'format': self.format,
261 default_kwargs.update(kwargs)
262 return self.final_image().save(*args, **default_kwargs)
264 def output_file(self, *args, **kwargs):
266 self.save(imgstr, *args, **kwargs)
267 return OutputFile.from_bytes(imgstr.getvalue())
270 class WLCover(Cover):
271 """Wolne Lektury cover without logos."""
275 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
276 author_font_size = 20
278 author_centering = True
279 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
282 title_box_width = 350
283 title_centering = True
286 box_bottom_margin = 100
301 box_position = 'middle'
302 background_color = '#444'
303 author_color = '#444'
304 background_img = get_resource('res/cover.png')
305 background_top = False
309 u'Starożytność': '#9e3610',
310 u'Średniowiecze': '#564c09',
311 u'Renesans': '#8ca629',
313 u'Oświecenie': '#f2802e',
314 u'Romantyzm': '#db4b16',
315 u'Pozytywizm': '#961060',
316 u'Modernizm': '#7784e0',
317 u'Dwudziestolecie międzywojenne': '#3044cf',
318 u'Współczesność': '#06393d',
320 set_title_color = True
322 kind_box_position = {
327 def __init__(self, book_info, format=None, width=None, height=None,
328 bleed=0, cover_logo=None):
329 super(WLCover, self).__init__(book_info, format=format, width=width,
332 self.slug = book_info.url.slug
334 self.box_position = book_info.cover_box_position or \
335 self.kind_box_position.get(book_info.kind, self.box_position)
337 if book_info.cover_bar_color == 'none':
340 self.bar_color = book_info.cover_bar_color or \
341 self.get_variable_color(book_info) or self.bar_color
343 if self.set_title_color:
344 self.title_color = self.get_variable_color(book_info) or self.title_color
347 self.box_top_margin += bleed
348 self.box_bottom_margin += bleed
349 self.bar_width += bleed
351 if book_info.cover_url:
352 url = book_info.cover_url
358 bg_src = requests.get(url, timeout=5)
359 self.background_img = BytesIO(bg_src.content)
361 except Exception as e:
369 def get_variable_color(self, book_info):
370 return self.epoch_colors.get(book_info.epoch, None)
372 def pretty_authors(self):
373 return [a.upper() for a in self.authors]
375 def add_box(self, img):
376 if self.box_position == 'none':
379 metr = Metric(self, self.scale)
382 box = TextBox(metr.title_box_width - 2 * self.bleed, metr.height,
383 padding_y=metr.box_padding_y,
384 padding_x=metr.box_padding_x,
385 bar_width=metr.box_bar_width,
386 bar_color=self.bar_color,
388 author_font = ImageFont.truetype(
389 self.author_font_ttf, metr.author_font_size,
390 layout_engine=ImageFont.LAYOUT_BASIC)
391 for pa in self.pretty_authors():
392 box.text(pa, font=author_font, line_height=metr.author_lineskip,
393 color=self.author_color, shadow_color=self.author_shadow,
394 centering=self.author_centering
397 box.skip(metr.box_above_line)
399 (metr.box_line_left, box.height, metr.box_line_right, box.height),
400 fill=self.author_color, width=metr.box_line_width
402 box.skip(metr.box_below_line)
405 title_font = ImageFont.truetype(
406 self.title_font_ttf, metr.title_font_size,
407 layout_engine=ImageFont.LAYOUT_BASIC)
408 box.text(self.pretty_title(),
409 line_height=metr.title_lineskip,
411 color=self.title_color,
412 shadow_color=self.title_shadow,
413 centering=self.title_centering
416 box_img = box.image()
419 if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
420 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
421 elif self.box_position == 'top':
422 box_top = metr.box_top_margin
424 box_top = (metr.height - box_img.size[1]) // 2
426 box_left = metr.bar_width + (
427 metr.width - metr.bar_width - box_img.size[0] - self.bleed
430 # Draw the white box.
431 img_draw = ImageDraw.Draw(img)
436 box_left + box_img.size[0],
437 box_top + box_img.size[1]
441 # Paste the contents into the white box.
442 img.paste(box_img, (box_left, box_top), box_img)
443 if self.box_bar_width:
448 box_left + metr.box_bar_width,
449 box_top + box_img.size[1]
455 def add_cut_lines(self, img):
459 metr = Metric(self, self.scale)
460 draw = ImageDraw.Draw(img)
461 for corner_x, corner_y in (
462 (0, 0), (metr.width, 0),
463 (0, metr.height), (metr.width, metr.height)
465 dir_x = 1 if corner_x == 0 else -1
466 dir_y = 1 if corner_y == 0 else -1
467 for offset in (-1, 0, 1):
471 corner_y + dir_y * metr.bleed + offset,
472 corner_x + dir_x * metr.bleed * line_ratio,
473 corner_y + dir_y * metr.bleed + offset
475 fill='black' if offset == 0 else 'white',
480 corner_x + dir_x * metr.bleed + offset,
482 corner_x + dir_x * metr.bleed + offset,
483 corner_y + dir_y * metr.bleed * line_ratio
485 fill='black' if offset == 0 else 'white',
491 metr = Metric(self, self.scale)
492 img = Image.new('RGB', (metr.width, metr.height),
493 self.background_color)
494 draw = ImageDraw.Draw(img)
496 draw.rectangle((0, 0, metr.bar_width, metr.height),
499 if self.background_img:
500 src = Image.open(self.background_img)
501 trg_size = (metr.width - metr.bar_width, metr.height)
502 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
505 int(round(src.size[1] * trg_size[0] / src.size[0]))
507 if self.background_top:
510 cut = (resized[1] - trg_size[1]) // 2
511 src = src.resize(resized, Image.ANTIALIAS)
512 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
515 int(round(src.size[0] * trg_size[1] / src.size[1])),
518 cut = (resized[0] - trg_size[0]) // 2
519 src = src.resize(resized, Image.ANTIALIAS)
520 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
522 img.paste(src, (metr.bar_width, 0))
525 img = self.add_box(img)
527 # img = self.add_cut_lines(img)
532 class WLNoBoxCover(WLCover):
533 def add_box(self, img):
537 class LogoWLCover(WLCover):
540 gradient_logo_height = 57
541 gradient_logo_max_width = 200
542 gradient_logo_margin_right = 30
543 gradient_logo_spacing = 40
544 gradient_color = '#000'
545 gradient_opacity = .6
547 'res/wl-logo-white.png',
548 'res/fnp-logo-white.png',
551 annotation_height = 10
554 gradient_logo_centering = False
559 def __init__(self, book_info, *args, cover_logo=None, **kwargs):
560 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
561 self.gradient_height += self.bleed
562 self.gradient_logo_margin_right += self.bleed
564 self.additional_cover_logos = [
565 BytesIO(URLOpener().open(cover_logo_url).read())
566 for cover_logo_url in book_info.cover_logo_urls
568 self.end_cover_logos = []
570 self.additional_cover_logos.append(
571 open(cover_logo, 'rb')
575 def has_gradient_logos(self):
576 return self.gradient_logos or self.additional_cover_logos or self.end_cover_logos or self.annotation or self.qrcode is not None
578 def add_gradient_logos(self, img, metr):
579 gradient = Image.new(
581 (metr.width - metr.bar_width, metr.gradient_height),
584 gradient_mask = Image.new(
586 (metr.width - metr.bar_width, metr.gradient_height)
588 draw = ImageDraw.Draw(gradient_mask)
589 for line in range(0, metr.gradient_easing):
591 (0, line, metr.width - metr.bar_width, line),
593 255 * self.gradient_opacity * line / metr.gradient_easing
597 0, metr.gradient_easing,
598 metr.width - metr.bar_width, metr.gradient_height
599 ), fill=int(255 * self.gradient_opacity))
603 (metr.bar_width, metr.height - metr.gradient_height),
607 cursor = metr.width - metr.gradient_logo_margin_right
609 cursor = metr.gradient_logo_margin_right
612 - metr.gradient_height / 2
613 - metr.gradient_logo_height / 2 - metr.bleed
617 get_resource(logo_path)
618 for logo_path in self.gradient_logos
621 logos = self.additional_cover_logos + logos + self.end_cover_logos
624 Image.open(logo_bytes).convert('RGBA')
625 for logo_bytes in logos
628 if self.qrcode is not None:
630 logos.append(qrcode.make(f'https://wolnelektury.pl/katalog/lektura/{self.slug}/?{self.qrcode}'))
635 # See if logos fit into the gradient. If not, scale down accordingly.
639 - 2 * metr.gradient_logo_margin_right + self.bleed
643 metr.gradient_logo_max_width,
644 logo.size[0] * metr.gradient_logo_height / logo.size[1]
647 taken_space = sum(widths) + (len(logos) - 1) * metr.gradient_logo_spacing
648 if taken_space > space_for_logos:
649 logo_scale = space_for_logos / taken_space
652 if self.gradient_logo_centering:
653 cursor += int((space_for_logos - taken_space) / 2)
655 space_for_logos / taken_space
656 if taken_space > space_for_logos else 1
658 #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
660 for i, logo in enumerate(logos):
665 L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
669 int(round(widths[i] * L_scale)),
671 logo.size[1] * widths[i] / logo.size[0] * L_scale
676 cursor -= logo.size[0]
683 #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
688 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
690 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
693 img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
694 draw = ImageDraw.Draw(img2)
695 author_font = ImageFont.truetype(
696 self.author_font_ttf, metr.annotation_height,
697 layout_engine=ImageFont.LAYOUT_BASIC)
698 draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
700 img2 = img2.rotate(90)
703 img.alpha_composite(img2, (0, 0))
704 img = img.convert('RGB')
709 img = super(LogoWLCover, self).image()
710 metr = Metric(self, self.scale)
711 if self.has_gradient_logos:
712 img = self.add_gradient_logos(img, metr)
716 class LegimiCover(LogoWLCover):
722 author_font_ttf = get_resource('fonts/Lora-Regular.ttf')
723 author_font_size = 15
724 author_lineskip = 19.5
725 author_centering = False
726 title_font_ttf = get_resource('fonts/Lora-Bold.ttf')
728 title_lineskip = 19.5
729 title_centering = False
731 title_box_width = 210
733 box_bottom_margin = 20
735 box_padding_y = 10 # do baseline
749 box_position = 'bottom'
750 background_color = '#444'
751 author_color = '#000'
753 set_title_color = False
755 kind_box_position = {}
757 box_bottom_margin_logos_add = 10
760 gradient_logo_height = 20
761 gradient_logo_max_width = 200
762 gradient_logo_margin_right = 10
763 gradient_logo_spacing = 20
764 gradient_color = '#000'
765 gradient_opacity = .5
767 'res/wl-logo-white.png',
770 gradient_logo_centering = True
771 background_top = True
774 'Artykuł': '#bf001a',
775 'Artykuł naukowy': '#bf001a',
776 'Dziennik': '#bf001a',
778 'Felieton': '#bf001a',
779 'Kronika': '#bf001a',
781 'Manifest': '#bf001a',
783 'Pamiętnik': '#bf001a',
784 'Poradnik': '#bf001a',
785 'Praca naukowa': '#bf001a',
786 'Publicystyka': '#bf001a',
787 'Reportaż': '#bf001a',
788 'Reportaż podróżniczy': '#bf001a',
789 'Rozprawa': '#bf001a',
790 'Rozprawa polityczna': '#bf001a',
791 'Traktat': '#bf001a',
799 def __init__(self, *args, **kwargs):
800 super().__init__(*args, **kwargs)
801 if self.has_gradient_logos:
802 self.box_bottom_margin += self.box_bottom_margin_logos_add
804 def pretty_authors(self):
807 def get_variable_color(self, book_info):
808 for genre in book_info.genres:
809 if genre in self.genre_colors:
810 return self.genre_colors[genre]
811 for kind in book_info.kinds:
812 if kind in self.kind_colors:
813 return self.kind_colors[kind]
815 class LegimiCornerCover(LegimiCover):
818 corner_image = get_resource('res/book-band.png')
821 image = super().image()
822 metr = Metric(self, self.scale)
824 if self.corner_image:
825 corner = Image.open(self.corner_image).convert('RGBA')
826 corner = corner.resize(
828 int(round(metr.corner_width)),
829 int(round(corner.size[1] / corner.size[0] * metr.corner_width))
832 image.paste(corner, (
833 metr.width - int(round(metr.corner_width)),
838 class LegimiAudiobookCover(LegimiCornerCover):
840 corner_image = get_resource('res/audiobook-sticker.png')
844 class EbookpointCover(LogoWLCover):
845 gradient_logo_height = 58
846 gradient_logo_spacing = 25
848 'res/ebookpoint-logo-white.png',
849 'res/wl-logo-white.png',
850 'res/fnp-logo-white.png',
854 class VirtualoCover(Cover):
863 class PrestigioCover(Cover):
866 background_img = get_resource('res/cover-prestigio.png')
869 author_margin_left = 118
870 author_margin_right = 62
872 author_color = '#fff'
873 author_shadow = '#000'
874 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
875 author_font_size = 50
878 title_margin_left = 118
879 title_margin_right = 62
882 title_shadow = '#000'
883 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
886 def pretty_title(self):
887 return u"„%s”" % self.title
890 class BookotekaCover(Cover):
893 background_img = get_resource('res/cover-bookoteka.png')
896 author_margin_left = 307
897 author_margin_right = 233
898 author_lineskip = 156
899 author_color = '#d9d919'
900 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
901 author_font_size = 130
904 title_margin_left = 307
905 title_margin_right = 233
907 title_color = '#d9d919'
908 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
909 title_font_size = 140
914 class GandalfCover(Cover):
917 background_img = get_resource('res/cover-gandalf.png')
918 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
919 author_font_size = 30
920 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
927 class KMLUCover(LogoWLCover):
928 gradient_logo_height = 58
929 gradient_logo_spacing = 25
931 'res/kmlu-logo-white.png',
932 'res/wl-logo-white.png',
933 'res/fnp-logo-white.png',
937 class MPWCover(LogoWLCover):
938 gradient_logo_height = 57
939 gradient_logo_spacing = 25
941 'res/mpw-logo-white.png',
942 'res/wl-logo-white.png',
943 'res/fnp-logo-white.png',
947 class AtriumCover(LogoWLCover):
948 gradient_logo_height = 58
949 gradient_logo_spacing = 25
951 'res/atrium-logo.png',
952 'res/wl-logo-white.png',
953 'res/fnp-logo-white.png',
957 class BNCover(LogoWLCover):
959 'res/dofinansowano.png',
962 'res/wl-logo-white.png',
964 # annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
967 class FactoryCover(LogoWLCover):
970 'res/wl-logo-white.png',
972 qrcode = 'pk_campaign=factory22'
975 def __init__(self, *args, **kwargs):
976 kwargs.setdefault('bleed', 10)
977 return super().__init__(*args, **kwargs)
982 def output_file(self, *args, **kwargs):
983 imgfile = super().output_file(*args, **kwargs)
986 with tempfile.TemporaryDirectory(prefix='factory-', dir='.') as d:
989 with open(d + '/cover.png', 'wb') as f:
990 f.write(imgfile.get_bytes())
991 shutil.copy(get_resource('res/factory-cover.svg'), d)
992 subprocess.call(['inkscape', f'--export-filename={d}/cover.pdf', d + '/factory-cover.svg'])
993 with open(d + '/cover.pdf', 'rb') as f:
994 return OutputFile.from_bytes(f.read())
998 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
1001 'legacy': LogoWLCover,
1004 'atrium': AtriumCover,
1006 'legimi': LegimiCover,
1007 'legimi-corner': LegimiCornerCover,
1008 'legimi-audiobook': LegimiAudiobookCover,
1009 'factory': FactoryCover,
1011 'm-label': LabelMarquiseCover,
1012 'default': MarquiseCover,
1016 def make_cover(book_info, *args, **kwargs):
1017 cover_class_name = None
1018 if 'cover_class' in kwargs:
1019 cover_class_name = kwargs.pop('cover_class')
1020 if not cover_class_name:
1021 cover_class_name = 'default'
1022 cover_class = COVER_CLASSES[cover_class_name]
1023 return cover_class(book_info, *args, **kwargs)