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
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.authors = [auth.readable() for auth in book_info.authors]
156 self.title = book_info.title
157 if format is not None:
160 self.height = int(round(height * self.width / width))
161 scale = max(float(width or 0) / self.width,
162 float(height or 0) / self.height)
166 self.scale_after = scale
168 def pretty_authors(self):
169 """Allows for decorating authors' names."""
170 return [self.authors]
172 def pretty_title(self):
173 """Allows for decorating title."""
177 metr = Metric(self, self.scale)
178 img = Image.new('RGB', (metr.width, metr.height),
179 self.background_color)
181 if self.background_img:
182 background = Image.open(self.background_img)
183 img.paste(background, None, background)
188 logo = Image.open(get_resource('res/wl-logo.png'))
191 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
194 (metr.width - metr.logo_width) // 2,
195 img.size[1] - logo.size[1] - metr.logo_bottom
198 top = metr.author_top
200 metr.width - metr.author_margin_left - metr.author_margin_right,
204 author_font = ImageFont.truetype(
205 self.author_font_ttf, metr.author_font_size,
206 layout_engine=ImageFont.LAYOUT_BASIC)
207 for pa in self.pretty_authors():
208 tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
210 text_img = tbox.image()
211 img.paste(text_img, (metr.author_margin_left, top), text_img)
213 top += text_img.size[1] + metr.title_top
215 metr.width - metr.title_margin_left - metr.title_margin_right,
218 title_font = ImageFont.truetype(
219 self.title_font_ttf, metr.title_font_size,
220 layout_engine=ImageFont.LAYOUT_BASIC)
221 tbox.text(self.pretty_title(), self.title_color, title_font,
222 metr.title_lineskip, self.title_shadow)
223 text_img = tbox.image()
224 img.paste(text_img, (metr.title_margin_left, top), text_img)
228 def final_image(self):
230 if self.scale_after != 1:
232 int(round(img.size[0] * self.scale_after)),
233 int(round(img.size[1] * self.scale_after))),
238 return self.mime_types[self.format]
241 return self.exts[self.format]
243 def save(self, *args, **kwargs):
245 'format': self.format,
248 default_kwargs.update(kwargs)
249 return self.final_image().save(*args, **default_kwargs)
251 def output_file(self, *args, **kwargs):
253 self.save(imgstr, *args, **kwargs)
254 return OutputFile.from_bytes(imgstr.getvalue())
257 class WLCover(Cover):
258 """Wolne Lektury cover without logos."""
262 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
263 author_font_size = 20
265 author_centering = True
266 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
269 title_box_width = 350
270 title_centering = True
273 box_bottom_margin = 100
288 box_position = 'middle'
289 background_color = '#444'
290 author_color = '#444'
291 background_img = get_resource('res/cover.png')
295 u'Starożytność': '#9e3610',
296 u'Średniowiecze': '#564c09',
297 u'Renesans': '#8ca629',
299 u'Oświecenie': '#f2802e',
300 u'Romantyzm': '#db4b16',
301 u'Pozytywizm': '#961060',
302 u'Modernizm': '#7784e0',
303 u'Dwudziestolecie międzywojenne': '#3044cf',
304 u'Współczesność': '#06393d',
306 set_title_color = True
308 kind_box_position = {
313 def __init__(self, book_info, format=None, width=None, height=None,
314 bleed=0, cover_logo=None):
315 super(WLCover, self).__init__(book_info, format=format, width=width,
318 self.box_position = book_info.cover_box_position or \
319 self.kind_box_position.get(book_info.kind, self.box_position)
321 if book_info.cover_bar_color == 'none':
324 self.bar_color = book_info.cover_bar_color or \
325 self.get_variable_color(book_info) or self.bar_color
327 if self.set_title_color:
328 self.title_color = self.get_variable_color(book_info) or self.title_color
331 self.box_top_margin += bleed
332 self.box_bottom_margin += bleed
333 self.bar_width += bleed
335 if book_info.cover_url:
336 url = book_info.cover_url
339 bg_src = URLOpener().open(url)
340 self.background_img = BytesIO(bg_src.read())
343 def get_variable_color(self, book_info):
344 return self.epoch_colors.get(book_info.epoch, None)
346 def pretty_authors(self):
347 return [a.upper() for a in self.authors]
349 def add_box(self, img):
350 if self.box_position == 'none':
353 metr = Metric(self, self.scale)
356 box = TextBox(metr.title_box_width, metr.height,
357 padding_y=metr.box_padding_y,
358 padding_x=metr.box_padding_x,
359 bar_width=metr.box_bar_width,
360 bar_color=self.bar_color,
362 author_font = ImageFont.truetype(
363 self.author_font_ttf, metr.author_font_size,
364 layout_engine=ImageFont.LAYOUT_BASIC)
365 for pa in self.pretty_authors():
366 box.text(pa, font=author_font, line_height=metr.author_lineskip,
367 color=self.author_color, shadow_color=self.author_shadow,
368 centering=self.author_centering
371 box.skip(metr.box_above_line)
373 (metr.box_line_left, box.height, metr.box_line_right, box.height),
374 fill=self.author_color, width=metr.box_line_width
376 box.skip(metr.box_below_line)
379 title_font = ImageFont.truetype(
380 self.title_font_ttf, metr.title_font_size,
381 layout_engine=ImageFont.LAYOUT_BASIC)
382 box.text(self.pretty_title(),
383 line_height=metr.title_lineskip,
385 color=self.title_color,
386 shadow_color=self.title_shadow,
387 centering=self.title_centering
390 box_img = box.image()
393 if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
394 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
395 elif self.box_position == 'top':
396 box_top = metr.box_top_margin
398 box_top = (metr.height - box_img.size[1]) // 2
400 box_left = metr.bar_width + (
401 metr.width - metr.bar_width - box_img.size[0]
404 # Draw the white box.
405 img_draw = ImageDraw.Draw(img)
410 box_left + box_img.size[0],
411 box_top + box_img.size[1]
415 # Paste the contents into the white box.
416 img.paste(box_img, (box_left, box_top), box_img)
417 if self.box_bar_width:
422 box_left + metr.box_bar_width,
423 box_top + box_img.size[1]
429 def add_cut_lines(self, img):
433 metr = Metric(self, self.scale)
434 draw = ImageDraw.Draw(img)
435 for corner_x, corner_y in (
436 (0, 0), (metr.width, 0),
437 (0, metr.height), (metr.width, metr.height)
439 dir_x = 1 if corner_x == 0 else -1
440 dir_y = 1 if corner_y == 0 else -1
441 for offset in (-1, 0, 1):
445 corner_y + dir_y * metr.bleed + offset,
446 corner_x + dir_x * metr.bleed * line_ratio,
447 corner_y + dir_y * metr.bleed + offset
449 fill='black' if offset == 0 else 'white',
454 corner_x + dir_x * metr.bleed + offset,
456 corner_x + dir_x * metr.bleed + offset,
457 corner_y + dir_y * metr.bleed * line_ratio
459 fill='black' if offset == 0 else 'white',
465 metr = Metric(self, self.scale)
466 img = Image.new('RGB', (metr.width, metr.height),
467 self.background_color)
468 draw = ImageDraw.Draw(img)
470 draw.rectangle((0, 0, metr.bar_width, metr.height),
473 if self.background_img:
474 src = Image.open(self.background_img)
475 trg_size = (metr.width - metr.bar_width, metr.height)
476 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
479 int(round(src.size[1] * trg_size[0] / src.size[0]))
481 cut = (resized[1] - trg_size[1]) // 2
482 src = src.resize(resized, Image.ANTIALIAS)
483 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
486 int(round(src.size[0] * trg_size[1] / src.size[1])),
489 cut = (resized[0] - trg_size[0]) // 2
490 src = src.resize(resized, Image.ANTIALIAS)
491 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
493 img.paste(src, (metr.bar_width, 0))
496 img = self.add_box(img)
498 # img = self.add_cut_lines(img)
503 class WLNoBoxCover(WLCover):
504 def add_box(self, img):
508 class LogoWLCover(WLCover):
511 gradient_logo_height = 57
512 gradient_logo_max_width = 200
513 gradient_logo_margin_right = 30
514 gradient_logo_spacing = 40
515 gradient_color = '#000'
516 gradient_opacity = .6
518 'res/wl-logo-white.png',
519 'res/fnp-logo-white.png',
522 annotation_height = 10
525 gradient_logo_centering = False
528 def __init__(self, book_info, *args, cover_logo=None, **kwargs):
529 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
530 self.gradient_height += self.bleed
531 self.gradient_logo_margin_right += self.bleed
533 self.additional_cover_logos = [
534 BytesIO(URLOpener().open(cover_logo_url).read())
535 for cover_logo_url in book_info.cover_logo_urls
537 self.end_cover_logos = []
539 self.additional_cover_logos.append(
540 open(cover_logo, 'rb')
544 def has_gradient_logos(self):
545 return self.gradient_logos or self.additional_cover_logos or self.end_cover_logos or self.annotation
547 def add_gradient_logos(self, img, metr):
548 gradient = Image.new(
550 (metr.width - metr.bar_width, metr.gradient_height),
553 gradient_mask = Image.new(
555 (metr.width - metr.bar_width, metr.gradient_height)
557 draw = ImageDraw.Draw(gradient_mask)
558 for line in range(0, metr.gradient_easing):
560 (0, line, metr.width - metr.bar_width, line),
562 255 * self.gradient_opacity * line / metr.gradient_easing
566 0, metr.gradient_easing,
567 metr.width - metr.bar_width, metr.gradient_height
568 ), fill=int(255 * self.gradient_opacity))
572 (metr.bar_width, metr.height - metr.gradient_height),
576 cursor = metr.width - metr.gradient_logo_margin_right
578 cursor = metr.gradient_logo_margin_right
581 - metr.gradient_height / 2
582 - metr.gradient_logo_height / 2 - metr.bleed / 2
586 get_resource(logo_path)
587 for logo_path in self.gradient_logos
590 logos = self.additional_cover_logos + logos + self.end_cover_logos
596 Image.open(logo_bytes).convert('RGBA')
597 for logo_bytes in logos
600 # See if logos fit into the gradient. If not, scale down accordingly.
604 - 2 * metr.gradient_logo_margin_right
608 metr.gradient_logo_max_width,
609 logo.size[0] * metr.gradient_logo_height / logo.size[1]
612 taken_space = sum(widths) + (len(logos) - 1) * metr.gradient_logo_spacing
613 if taken_space > space_for_logos:
614 logo_scale = space_for_logos / taken_space
617 if self.gradient_logo_centering:
618 cursor += int((space_for_logos - taken_space) / 2)
620 space_for_logos / taken_space
621 if taken_space > space_for_logos else 1
623 #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
625 for i, logo in enumerate(logos):
630 L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
634 int(round(widths[i] * L_scale)),
636 logo.size[1] * widths[i] / logo.size[0] * L_scale
641 cursor -= logo.size[0]
648 #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
653 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
655 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
658 img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
659 draw = ImageDraw.Draw(img2)
660 author_font = ImageFont.truetype(
661 self.author_font_ttf, metr.annotation_height,
662 layout_engine=ImageFont.LAYOUT_BASIC)
663 draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
665 img2 = img2.rotate(90)
668 img.alpha_composite(img2, (0, 0))
669 img = img.convert('RGB')
674 img = super(LogoWLCover, self).image()
675 metr = Metric(self, self.scale)
676 if self.has_gradient_logos:
677 img = self.add_gradient_logos(img, metr)
681 class LegimiCover(LogoWLCover):
687 author_font_ttf = get_resource('fonts/Lora-Regular.ttf')
688 author_font_size = 15
689 author_lineskip = 19.5
690 author_centering = False
691 title_font_ttf = get_resource('fonts/Lora-Bold.ttf')
693 title_lineskip = 19.5
694 title_centering = False
696 title_box_width = 210
698 box_bottom_margin = 20
700 box_padding_y = 10 # do baseline
714 box_position = 'bottom'
715 background_color = '#444'
716 author_color = '#000'
718 set_title_color = False
720 kind_box_position = {}
722 box_bottom_margin_logos_add = 10
725 gradient_logo_height = 20
726 gradient_logo_max_width = 200
727 gradient_logo_margin_right = 10
728 gradient_logo_spacing = 20
729 gradient_color = '#000'
730 gradient_opacity = .5
732 'res/wl-logo-white.png',
735 gradient_logo_centering = True
738 'Artykuł': '#bf001a',
739 'Artykuł naukowy': '#bf001a',
740 'Dziennik': '#bf001a',
742 'Felieton': '#bf001a',
743 'Kronika': '#bf001a',
745 'Manifest': '#bf001a',
747 'Pamiętnik': '#bf001a',
748 'Poradnik': '#bf001a',
749 'Praca naukowa': '#bf001a',
750 'Publicystyka': '#bf001a',
751 'Reportaż': '#bf001a',
752 'Reportaż podróżniczy': '#bf001a',
753 'Rozprawa': '#bf001a',
754 'Rozprawa polityczna': '#bf001a',
755 'Traktat': '#bf001a',
763 def __init__(self, *args, **kwargs):
764 super().__init__(*args, **kwargs)
765 if self.has_gradient_logos:
766 self.box_bottom_margin += self.box_bottom_margin_logos_add
768 def pretty_authors(self):
771 def get_variable_color(self, book_info):
772 for genre in book_info.genres:
773 if genre in self.genre_colors:
774 return self.genre_colors[genre]
775 for kind in book_info.kinds:
776 if kind in self.kind_colors:
777 return self.kind_colors[kind]
779 class LegimiCornerCover(LegimiCover):
782 corner_image = get_resource('res/book-band.png')
785 image = super().image()
786 metr = Metric(self, self.scale)
788 if self.corner_image:
789 corner = Image.open(self.corner_image).convert('RGBA')
790 corner = corner.resize(
792 int(round(metr.corner_width)),
793 int(round(corner.size[1] / corner.size[0] * metr.corner_width))
796 image.paste(corner, (
797 metr.width - int(round(metr.corner_width)),
802 class LegimiAudiobookCover(LegimiCornerCover):
804 corner_image = get_resource('res/audiobook-sticker.png')
808 class EbookpointCover(LogoWLCover):
809 gradient_logo_height = 58
810 gradient_logo_spacing = 25
812 'res/ebookpoint-logo-white.png',
813 'res/wl-logo-white.png',
814 'res/fnp-logo-white.png',
818 class VirtualoCover(Cover):
827 class PrestigioCover(Cover):
830 background_img = get_resource('res/cover-prestigio.png')
833 author_margin_left = 118
834 author_margin_right = 62
836 author_color = '#fff'
837 author_shadow = '#000'
838 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
839 author_font_size = 50
842 title_margin_left = 118
843 title_margin_right = 62
846 title_shadow = '#000'
847 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
850 def pretty_title(self):
851 return u"„%s”" % self.title
854 class BookotekaCover(Cover):
857 background_img = get_resource('res/cover-bookoteka.png')
860 author_margin_left = 307
861 author_margin_right = 233
862 author_lineskip = 156
863 author_color = '#d9d919'
864 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
865 author_font_size = 130
868 title_margin_left = 307
869 title_margin_right = 233
871 title_color = '#d9d919'
872 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
873 title_font_size = 140
878 class GandalfCover(Cover):
881 background_img = get_resource('res/cover-gandalf.png')
882 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
883 author_font_size = 30
884 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
891 class KMLUCover(LogoWLCover):
892 gradient_logo_height = 58
893 gradient_logo_spacing = 25
895 'res/kmlu-logo-white.png',
896 'res/wl-logo-white.png',
897 'res/fnp-logo-white.png',
901 class MPWCover(LogoWLCover):
902 gradient_logo_height = 57
903 gradient_logo_spacing = 25
905 'res/mpw-logo-white.png',
906 'res/wl-logo-white.png',
907 'res/fnp-logo-white.png',
911 class AtriumCover(LogoWLCover):
912 gradient_logo_height = 58
913 gradient_logo_spacing = 25
915 'res/atrium-logo.png',
916 'res/wl-logo-white.png',
917 'res/fnp-logo-white.png',
921 class BNCover(LogoWLCover):
923 'res/dofinansowano.png',
926 'res/wl-logo-white.png',
928 # annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
932 'default': LogoWLCover,
935 'atrium': AtriumCover,
937 'legimi': LegimiCover,
938 'legimi-corner': LegimiCornerCover,
939 'legimi-audiobook': LegimiAudiobookCover,
943 def make_cover(book_info, *args, **kwargs):
944 if 'cover_class' in kwargs:
945 cover_class_name = kwargs.pop('cover_class')
947 cover_class_name = book_info.cover_class
948 cover_class = COVER_CLASSES[cover_class_name]
949 return cover_class(book_info, *args, **kwargs)