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)
166 self.cover_logo = cover_logo
168 def set_size(self, width, height):
170 self.height = int(round(height * self.width / width))
171 scale = max(float(width or 0) / self.width,
172 float(height or 0) / self.height)
176 self.scale_after = scale
178 def pretty_authors(self):
179 """Allows for decorating authors' names."""
182 def pretty_title(self):
183 """Allows for decorating title."""
187 metr = Metric(self, self.scale)
188 img = Image.new('RGB', (metr.width, metr.height),
189 self.background_color)
191 if self.background_img:
192 background = Image.open(self.background_img)
193 img.paste(background, None, background)
198 logo = Image.open(get_resource('res/wl-logo.png'))
201 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
204 (metr.width - metr.logo_width) // 2,
205 img.size[1] - logo.size[1] - metr.logo_bottom
208 top = metr.author_top
210 metr.width - metr.author_margin_left - metr.author_margin_right,
214 author_font = ImageFont.truetype(
215 self.author_font_ttf, metr.author_font_size,
216 layout_engine=ImageFont.Layout.BASIC)
217 for pa in self.pretty_authors():
218 tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
220 text_img = tbox.image()
221 img.paste(text_img, (metr.author_margin_left, top), text_img)
223 top += text_img.size[1] + metr.title_top
225 metr.width - metr.title_margin_left - metr.title_margin_right,
228 title_font = ImageFont.truetype(
229 self.title_font_ttf, metr.title_font_size,
230 layout_engine=ImageFont.Layout.BASIC)
231 tbox.text(self.pretty_title(), self.title_color, title_font,
232 metr.title_lineskip, self.title_shadow)
233 text_img = tbox.image()
234 img.paste(text_img, (metr.title_margin_left, top), text_img)
238 def final_image(self):
240 if self.scale_after != 1:
242 int(round(img.size[0] * self.scale_after)),
243 int(round(img.size[1] * self.scale_after))),
244 Image.Resampling.LANCZOS)
248 return self.mime_types[self.format]
251 return self.exts[self.format]
253 def save(self, *args, **kwargs):
255 'format': self.format,
258 default_kwargs.update(kwargs)
259 return self.final_image().save(*args, **default_kwargs)
261 def output_file(self, *args, **kwargs):
263 self.save(imgstr, *args, **kwargs)
264 return OutputFile.from_bytes(imgstr.getvalue())
267 class WLCover(Cover):
268 """Wolne Lektury cover without logos."""
272 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
273 author_font_size = 20
275 author_centering = True
276 title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
279 title_box_width = 350
280 title_centering = True
283 box_bottom_margin = 100
298 box_position = 'middle'
299 background_color = '#444'
300 author_color = '#444'
301 background_img = get_resource('res/cover.png')
302 background_top = False
306 'Starożytność': '#9e3610',
307 'Średniowiecze': '#564c09',
308 'Renesans': '#8ca629',
310 'Oświecenie': '#f2802e',
311 'Romantyzm': '#db4b16',
312 'Pozytywizm': '#961060',
313 'Modernizm': '#7784e0',
314 'Dwudziestolecie międzywojenne': '#3044cf',
315 'Współczesność': '#06393d',
317 set_title_color = True
319 kind_box_position = {
324 def __init__(self, book_info, format=None, width=None, height=None,
325 bleed=0, cover_logo=None):
326 super(WLCover, self).__init__(book_info, format=format, width=width,
329 self.slug = book_info.url.slug
331 self.box_position = book_info.cover_box_position or \
332 self.kind_box_position.get(book_info.kind, self.box_position)
334 if book_info.cover_bar_color == 'none':
337 self.bar_color = book_info.cover_bar_color or \
338 self.get_variable_color(book_info) or self.bar_color
340 if self.set_title_color:
341 self.title_color = self.get_variable_color(book_info) or self.title_color
344 self.box_top_margin += bleed
345 self.box_bottom_margin += bleed
346 self.bar_width += bleed
348 if book_info.cover_url:
349 url = book_info.cover_url
355 bg_src = requests.get(url, timeout=5)
356 self.background_img = BytesIO(bg_src.content)
358 except Exception as e:
366 def get_variable_color(self, book_info):
367 return self.epoch_colors.get(book_info.epoch, None)
369 def pretty_authors(self):
370 return [a.upper() for a in self.authors]
372 def add_box(self, img):
373 if self.box_position == 'none':
376 metr = Metric(self, self.scale)
379 box = TextBox(metr.title_box_width - 2 * self.bleed, metr.height,
380 padding_y=metr.box_padding_y,
381 padding_x=metr.box_padding_x,
382 bar_width=metr.box_bar_width,
383 bar_color=self.bar_color,
385 author_font = ImageFont.truetype(
386 self.author_font_ttf, metr.author_font_size,
387 layout_engine=ImageFont.Layout.BASIC)
388 for pa in self.pretty_authors():
389 box.text(pa, font=author_font, line_height=metr.author_lineskip,
390 color=self.author_color, shadow_color=self.author_shadow,
391 centering=self.author_centering
394 box.skip(metr.box_above_line)
396 (metr.box_line_left, box.height, metr.box_line_right, box.height),
397 fill=self.author_color, width=metr.box_line_width
399 box.skip(metr.box_below_line)
402 title_font = ImageFont.truetype(
403 self.title_font_ttf, metr.title_font_size,
404 layout_engine=ImageFont.Layout.BASIC)
405 box.text(self.pretty_title(),
406 line_height=metr.title_lineskip,
408 color=self.title_color,
409 shadow_color=self.title_shadow,
410 centering=self.title_centering
413 box_img = box.image()
416 if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
417 box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
418 elif self.box_position == 'top':
419 box_top = metr.box_top_margin
421 box_top = (metr.height - box_img.size[1]) // 2
423 box_left = metr.bar_width + (
424 metr.width - metr.bar_width - box_img.size[0] - self.bleed
427 # Draw the white box.
428 img_draw = ImageDraw.Draw(img)
433 box_left + box_img.size[0],
434 box_top + box_img.size[1]
438 # Paste the contents into the white box.
439 img.paste(box_img, (box_left, box_top), box_img)
440 if self.box_bar_width:
445 box_left + metr.box_bar_width,
446 box_top + box_img.size[1]
452 def add_cut_lines(self, img):
456 metr = Metric(self, self.scale)
457 draw = ImageDraw.Draw(img)
458 for corner_x, corner_y in (
459 (0, 0), (metr.width, 0),
460 (0, metr.height), (metr.width, metr.height)
462 dir_x = 1 if corner_x == 0 else -1
463 dir_y = 1 if corner_y == 0 else -1
464 for offset in (-1, 0, 1):
468 corner_y + dir_y * metr.bleed + offset,
469 corner_x + dir_x * metr.bleed * line_ratio,
470 corner_y + dir_y * metr.bleed + offset
472 fill='black' if offset == 0 else 'white',
477 corner_x + dir_x * metr.bleed + offset,
479 corner_x + dir_x * metr.bleed + offset,
480 corner_y + dir_y * metr.bleed * line_ratio
482 fill='black' if offset == 0 else 'white',
488 metr = Metric(self, self.scale)
489 img = Image.new('RGB', (metr.width, metr.height),
490 self.background_color)
491 draw = ImageDraw.Draw(img)
493 draw.rectangle((0, 0, metr.bar_width, metr.height),
496 if self.background_img:
497 src = Image.open(self.background_img)
498 trg_size = (metr.width - metr.bar_width, metr.height)
499 if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
502 int(round(src.size[1] * trg_size[0] / src.size[0]))
504 if self.background_top:
507 cut = (resized[1] - trg_size[1]) // 2
508 src = src.resize(resized, Image.Resampling.LANCZOS)
509 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
512 int(round(src.size[0] * trg_size[1] / src.size[1])),
515 cut = (resized[0] - trg_size[0]) // 2
516 src = src.resize(resized, Image.Resampling.LANCZOS)
517 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
519 img.paste(src, (metr.bar_width, 0))
522 img = self.add_box(img)
524 # img = self.add_cut_lines(img)
529 class WLNoBoxCover(WLCover):
530 def add_box(self, img):
534 class LogoWLCover(WLCover):
537 gradient_logo_height = 57
538 gradient_logo_max_width = 200
539 gradient_logo_margin_right = 30
540 gradient_logo_spacing = 40
541 gradient_color = '#000'
542 gradient_opacity = .6
544 'res/wl-logo-white.png',
545 'res/fnp-logo-white.png',
548 annotation_height = 10
551 gradient_logo_centering = False
556 def __init__(self, book_info, *args, cover_logo=None, **kwargs):
557 super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
558 self.gradient_height += self.bleed
559 self.gradient_logo_margin_right += self.bleed
561 self.additional_cover_logos = [
562 BytesIO(URLOpener().open(cover_logo_url).read())
563 for cover_logo_url in book_info.cover_logo_urls
565 self.end_cover_logos = []
567 self.additional_cover_logos.append(
568 open(cover_logo, 'rb')
572 def has_gradient_logos(self):
573 return self.gradient_logos or self.additional_cover_logos or self.end_cover_logos or self.annotation or self.qrcode is not None
575 def add_gradient_logos(self, img, metr):
576 gradient = Image.new(
578 (metr.width - metr.bar_width, metr.gradient_height),
581 gradient_mask = Image.new(
583 (metr.width - metr.bar_width, metr.gradient_height)
585 draw = ImageDraw.Draw(gradient_mask)
586 for line in range(0, metr.gradient_easing):
588 (0, line, metr.width - metr.bar_width, line),
590 255 * self.gradient_opacity * line / metr.gradient_easing
594 0, metr.gradient_easing,
595 metr.width - metr.bar_width, metr.gradient_height
596 ), fill=int(255 * self.gradient_opacity))
600 (metr.bar_width, metr.height - metr.gradient_height),
604 cursor = metr.width - metr.gradient_logo_margin_right
606 cursor = metr.gradient_logo_margin_right
609 - metr.gradient_height / 2
610 - metr.gradient_logo_height / 2 - metr.bleed
614 get_resource(logo_path)
615 for logo_path in self.gradient_logos
618 logos = self.additional_cover_logos + logos + self.end_cover_logos
621 Image.open(logo_bytes).convert('RGBA')
622 for logo_bytes in logos
625 if self.qrcode is not None:
627 logos.append(qrcode.make(f'https://wolnelektury.pl/katalog/lektura/{self.slug}/?{self.qrcode}'))
632 # See if logos fit into the gradient. If not, scale down accordingly.
636 - 2 * metr.gradient_logo_margin_right + self.bleed
640 metr.gradient_logo_max_width,
641 logo.size[0] * metr.gradient_logo_height / logo.size[1]
644 taken_space = sum(widths) + (len(logos) - 1) * metr.gradient_logo_spacing
645 if taken_space > space_for_logos:
646 logo_scale = space_for_logos / taken_space
649 if self.gradient_logo_centering:
650 cursor += int((space_for_logos - taken_space) / 2)
652 space_for_logos / taken_space
653 if taken_space > space_for_logos else 1
655 #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
657 for i, logo in enumerate(logos):
662 L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
666 int(round(widths[i] * L_scale)),
668 logo.size[1] * widths[i] / logo.size[0] * L_scale
671 Image.Resampling.LANCZOS)
673 cursor -= logo.size[0]
680 #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
685 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
687 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
690 img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
691 draw = ImageDraw.Draw(img2)
692 author_font = ImageFont.truetype(
693 self.author_font_ttf, metr.annotation_height,
694 layout_engine=ImageFont.Layout.BASIC)
695 draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
697 img2 = img2.rotate(90)
700 img.alpha_composite(img2, (0, 0))
701 img = img.convert('RGB')
706 img = super(LogoWLCover, self).image()
707 metr = Metric(self, self.scale)
708 if self.has_gradient_logos:
709 img = self.add_gradient_logos(img, metr)
713 class LegimiCover(LogoWLCover):
719 author_font_ttf = get_resource('fonts/Lora-Regular.ttf')
720 author_font_size = 15
721 author_lineskip = 19.5
722 author_centering = False
723 title_font_ttf = get_resource('fonts/Lora-Bold.ttf')
725 title_lineskip = 19.5
726 title_centering = False
728 title_box_width = 210
730 box_bottom_margin = 20
732 box_padding_y = 10 # do baseline
746 box_position = 'bottom'
747 background_color = '#444'
748 author_color = '#000'
750 set_title_color = False
752 kind_box_position = {}
754 box_bottom_margin_logos_add = 10
757 gradient_logo_height = 20
758 gradient_logo_max_width = 200
759 gradient_logo_margin_right = 10
760 gradient_logo_spacing = 20
761 gradient_color = '#000'
762 gradient_opacity = .5
764 'res/wl-logo-white.png',
767 gradient_logo_centering = True
768 background_top = True
771 'Artykuł': '#bf001a',
772 'Artykuł naukowy': '#bf001a',
773 'Dziennik': '#bf001a',
775 'Felieton': '#bf001a',
776 'Kronika': '#bf001a',
778 'Manifest': '#bf001a',
780 'Pamiętnik': '#bf001a',
781 'Poradnik': '#bf001a',
782 'Praca naukowa': '#bf001a',
783 'Publicystyka': '#bf001a',
784 'Reportaż': '#bf001a',
785 'Reportaż podróżniczy': '#bf001a',
786 'Rozprawa': '#bf001a',
787 'Rozprawa polityczna': '#bf001a',
788 'Traktat': '#bf001a',
796 def __init__(self, *args, **kwargs):
797 super().__init__(*args, **kwargs)
798 if self.has_gradient_logos:
799 self.box_bottom_margin += self.box_bottom_margin_logos_add
801 def pretty_authors(self):
804 def get_variable_color(self, book_info):
805 for genre in book_info.genres:
806 if genre in self.genre_colors:
807 return self.genre_colors[genre]
808 for kind in book_info.kinds:
809 if kind in self.kind_colors:
810 return self.kind_colors[kind]
812 class LegimiCornerCover(LegimiCover):
815 corner_image = get_resource('res/book-band.png')
818 image = super().image()
819 metr = Metric(self, self.scale)
821 if self.corner_image:
822 corner = Image.open(self.corner_image).convert('RGBA')
823 corner = corner.resize(
825 int(round(metr.corner_width)),
826 int(round(corner.size[1] / corner.size[0] * metr.corner_width))
829 image.paste(corner, (
830 metr.width - int(round(metr.corner_width)),
835 class LegimiAudiobookCover(LegimiCornerCover):
837 corner_image = get_resource('res/audiobook-sticker.png')
841 class EbookpointCover(LogoWLCover):
842 gradient_logo_height = 58
843 gradient_logo_spacing = 25
845 'res/ebookpoint-logo-white.png',
846 'res/wl-logo-white.png',
847 'res/fnp-logo-white.png',
851 class VirtualoCover(Cover):
860 class PrestigioCover(Cover):
863 background_img = get_resource('res/cover-prestigio.png')
866 author_margin_left = 118
867 author_margin_right = 62
869 author_color = '#fff'
870 author_shadow = '#000'
871 author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
872 author_font_size = 50
875 title_margin_left = 118
876 title_margin_right = 62
879 title_shadow = '#000'
880 title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
883 def pretty_title(self):
884 return "„%s”" % self.title
887 class BookotekaCover(Cover):
890 background_img = get_resource('res/cover-bookoteka.png')
893 author_margin_left = 307
894 author_margin_right = 233
895 author_lineskip = 156
896 author_color = '#d9d919'
897 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
898 author_font_size = 130
901 title_margin_left = 307
902 title_margin_right = 233
904 title_color = '#d9d919'
905 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
906 title_font_size = 140
911 class GandalfCover(Cover):
914 background_img = get_resource('res/cover-gandalf.png')
915 author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
916 author_font_size = 30
917 title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
924 class KMLUCover(LogoWLCover):
925 gradient_logo_height = 58
926 gradient_logo_spacing = 25
928 'res/kmlu-logo-white.png',
929 'res/wl-logo-white.png',
930 'res/fnp-logo-white.png',
934 class MPWCover(LogoWLCover):
935 gradient_logo_height = 57
936 gradient_logo_spacing = 25
938 'res/mpw-logo-white.png',
939 'res/wl-logo-white.png',
940 'res/fnp-logo-white.png',
944 class AtriumCover(LogoWLCover):
945 gradient_logo_height = 58
946 gradient_logo_spacing = 25
948 'res/atrium-logo.png',
949 'res/wl-logo-white.png',
950 'res/fnp-logo-white.png',
954 class BNCover(LogoWLCover):
956 'res/dofinansowano.png',
959 'res/wl-logo-white.png',
961 # annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
964 class FactoryCover(LogoWLCover):
967 'res/wl-logo-white.png',
969 qrcode = 'pk_campaign=factory22'
972 def __init__(self, *args, **kwargs):
973 kwargs.setdefault('bleed', 10)
974 return super().__init__(*args, **kwargs)
979 def output_file(self, *args, **kwargs):
980 imgfile = super().output_file(*args, **kwargs)
983 with tempfile.TemporaryDirectory(prefix='factory-', dir='.') as d:
986 with open(d + '/cover.png', 'wb') as f:
987 f.write(imgfile.get_bytes())
988 shutil.copy(get_resource('res/factory-cover.svg'), d)
989 subprocess.call(['inkscape', f'--export-filename={d}/cover.pdf', d + '/factory-cover.svg'])
990 with open(d + '/cover.pdf', 'rb') as f:
991 return OutputFile.from_bytes(f.read())
995 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
998 'legacy': LogoWLCover,
1001 'atrium': AtriumCover,
1003 'legimi': LegimiCover,
1004 'legimi-corner': LegimiCornerCover,
1005 'legimi-audiobook': LegimiAudiobookCover,
1006 'factory': FactoryCover,
1008 'm-label': LabelMarquiseCover,
1009 'default': MarquiseCover,
1013 def make_cover(book_info, *args, **kwargs):
1014 cover_class_name = None
1015 if 'cover_class' in kwargs:
1016 cover_class_name = kwargs.pop('cover_class')
1017 if not cover_class_name:
1018 cover_class_name = 'default'
1019 cover_class = COVER_CLASSES[cover_class_name]
1020 return cover_class(book_info, *args, **kwargs)