9cd813ad4b1f15c3c10c43d96445f7b72c790446
[librarian.git] / src / librarian / cover.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from __future__ import unicode_literals
7
8 import re
9 from PIL import Image, ImageFont, ImageDraw, ImageFilter
10 from six import BytesIO
11 from librarian import get_resource, OutputFile, URLOpener
12
13
14 class Metric(object):
15     """Gets metrics from an object, scaling it by a factor."""
16     def __init__(self, obj, scale):
17         self._obj = obj
18         self._scale = float(scale)
19
20     def __getattr__(self, name):
21         src = getattr(self._obj, name)
22         if src and self._scale:
23             return type(src)(self._scale * src)
24         else:
25             return src
26
27
28 class TextBox(object):
29     """Creates an Image with a series of centered strings."""
30
31     SHADOW_X = 3
32     SHADOW_Y = 3
33     SHADOW_BLUR = 3
34
35     def __init__(self, max_width, max_height, padding_x=None, padding_y=None, bar_width=0, bar_color=None):
36         if padding_x is None:
37             padding_x = self.SHADOW_X + self.SHADOW_BLUR
38         if padding_y is None:
39             padding_y = self.SHADOW_Y + self.SHADOW_BLUR
40
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
52
53     def skip(self, height):
54         """Skips some vertical space."""
55         self.height += height
56
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)
61         if shadow_color:
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)
65         while text:
66             line = text
67             line_width = self.draw.textsize(line, font=font)[0]
68             while line_width > self.max_text_width:
69                 parts = line.rsplit(' ', 1)
70                 if len(parts) == 1:
71                     line_width = self.max_text_width
72                     break
73                 line = parts[0]
74
75                 if len(line) > 2 and line[-2] == ' ':
76                     line = line[:-2]
77
78                 line_width = self.draw.textsize(line, font=font)[0]
79             line = line.strip() + ' '
80
81             if centering:
82                 pos_x = (self.max_width - line_width) // 2
83             else:
84                 pos_x = self.bar_width + self.padding_x
85
86             if shadow_color:
87                 self.shadow_draw.text(
88                         (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
89                         line, font=font, fill=shadow_color
90                 )
91
92             self.draw.text((pos_x, self.height), line, font=font, fill=color)
93             self.height += line_height
94             # go to next line
95             text = text[len(line):]
96
97     def image(self):
98         """Creates the actual Image object."""
99         image = Image.new('RGBA', (self.max_width,
100                                    int(round(self.height + self.padding_y))))
101
102         if self.shadow_img:
103             shadow = self.shadow_img.filter(ImageFilter.BLUR)
104             image.paste(shadow, (0, 0), shadow)
105             image.paste(self.img, (0, 0), self.img)
106         else:
107             image.paste(self.img, (0, 0))
108         return image
109
110
111 class Cover(object):
112     """Abstract base class for cover images generator."""
113     width = 600
114     height = 800
115     background_color = '#fff'
116     background_img = None
117
118     author_top = 100
119     author_margin_left = 20
120     author_margin_right = 20
121     author_lineskip = 40
122     author_color = '#000'
123     author_shadow = None
124     author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
125     author_font_size = 30
126
127     title_top = 100
128     title_margin_left = 20
129     title_margin_right = 20
130     title_lineskip = 54
131     title_color = '#000'
132     title_shadow = None
133     title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
134     title_font_size = 40
135
136     logo_bottom = None
137     logo_width = None
138     uses_dc_cover = False
139
140     format = 'JPEG'
141     scale = 1
142     scale_after = 1
143
144     exts = {
145         'JPEG': 'jpg',
146         'PNG': 'png',
147         }
148
149     mime_types = {
150         'JPEG': 'image/jpeg',
151         'PNG': 'image/png',
152         }
153
154     def __init__(self, book_info, format=None, width=None, height=None, cover_logo=None):
155         self.book_info = book_info
156
157         self.predesigned = False
158         if book_info.cover_class == 'image':
159             self.predesigned = True
160
161         # TODO: deprecated
162         if book_info.cover_box_position == 'none':
163             self.predesigned = True
164
165         self.authors = [auth.readable() for auth in book_info.authors]
166         self.title = book_info.title
167         if format is not None:
168             self.format = format
169         self.set_size(width, height)
170
171     def set_size(self, width, height):
172         if width and 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)
176         if scale >= 1:
177             self.scale = scale
178         elif scale:
179             self.scale_after = scale
180
181     def pretty_authors(self):
182         """Allows for decorating authors' names."""
183         return self.authors
184
185     def pretty_title(self):
186         """Allows for decorating title."""
187         return self.title
188
189     def image(self):
190         metr = Metric(self, self.scale)
191         img = Image.new('RGB', (metr.width, metr.height),
192                         self.background_color)
193
194         if self.background_img:
195             background = Image.open(self.background_img)
196             img.paste(background, None, background)
197             del background
198
199         # WL logo
200         if metr.logo_width:
201             logo = Image.open(get_resource('res/wl-logo.png'))
202             logo = logo.resize((
203                 metr.logo_width,
204                 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
205             ))
206             img.paste(logo, (
207                 (metr.width - metr.logo_width) // 2,
208                 img.size[1] - logo.size[1] - metr.logo_bottom
209             ))
210
211         top = metr.author_top
212         tbox = TextBox(
213             metr.width - metr.author_margin_left - metr.author_margin_right,
214             metr.height - top,
215             )
216
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,
222                       self.author_shadow)
223         text_img = tbox.image()
224         img.paste(text_img, (metr.author_margin_left, top), text_img)
225
226         top += text_img.size[1] + metr.title_top
227         tbox = TextBox(
228             metr.width - metr.title_margin_left - metr.title_margin_right,
229             metr.height - top,
230             )
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)
238
239         return img
240
241     def final_image(self):
242         img = self.image()
243         if self.scale_after != 1:
244             img = img.resize((
245                     int(round(img.size[0] * self.scale_after)),
246                     int(round(img.size[1] * self.scale_after))),
247                 Image.ANTIALIAS)
248         return img
249
250     def mime_type(self):
251         return self.mime_types[self.format]
252
253     def ext(self):
254         return self.exts[self.format]
255
256     def save(self, *args, **kwargs):
257         default_kwargs = {
258                 'format': self.format,
259                 'quality': 95,
260         }
261         default_kwargs.update(kwargs)
262         return self.final_image().save(*args, **default_kwargs)
263
264     def output_file(self, *args, **kwargs):
265         imgstr = BytesIO()
266         self.save(imgstr, *args, **kwargs)
267         return OutputFile.from_bytes(imgstr.getvalue())
268
269
270 class WLCover(Cover):
271     """Wolne Lektury cover without logos."""
272     width = 600
273     height = 833
274     uses_dc_cover = True
275     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
276     author_font_size = 20
277     author_lineskip = 30
278     author_centering = True
279     title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
280     title_font_size = 30
281     title_lineskip = 40
282     title_box_width = 350
283     title_centering = True
284
285     box_top_margin = 100
286     box_bottom_margin = 100
287     box_padding_y = 20
288     box_above_line = 10
289     box_below_line = 15
290     box_line_left = 75
291     box_line_right = 275
292     box_line_width = 2
293     box_padding_x = 0
294     box_bar_width = 0
295
296     logo_top = 15
297     logo_width = 140
298
299     bar_width = 35
300     bar_color = '#000'
301     box_position = 'middle'
302     background_color = '#444'
303     author_color = '#444'
304     background_img = get_resource('res/cover.png')
305     background_top = False
306     format = 'JPEG'
307
308     epoch_colors = {
309         u'Starożytność': '#9e3610',
310         u'Średniowiecze': '#564c09',
311         u'Renesans': '#8ca629',
312         u'Barok': '#a6820a',
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',
319     }
320     set_title_color = True
321
322     kind_box_position = {
323         u'Liryka': 'top',
324         u'Epika': 'bottom',
325     }
326
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,
330                                       height=height)
331
332         self.slug = book_info.url.slug
333         # Set box position.
334         self.box_position = book_info.cover_box_position or \
335             self.kind_box_position.get(book_info.kind, self.box_position)
336         # Set bar color.
337         if book_info.cover_bar_color == 'none':
338             self.bar_width = 0
339         else:
340             self.bar_color = book_info.cover_bar_color or \
341                 self.get_variable_color(book_info) or self.bar_color
342         # Set title color.
343         if self.set_title_color:
344             self.title_color = self.get_variable_color(book_info) or self.title_color
345
346         self.bleed = bleed
347         self.box_top_margin += bleed
348         self.box_bottom_margin += bleed
349         self.bar_width += bleed
350
351         if book_info.cover_url:
352             url = book_info.cover_url
353             bg_src = None
354             while True:
355                 try:
356                     if bg_src is None:
357                         import requests
358                         bg_src = requests.get(url, timeout=5)
359                     self.background_img = BytesIO(bg_src.content)
360                     bg_src.close()
361                 except Exception as e:
362                     bg_src = None
363                     print(e)
364                     import time
365                     time.sleep(1)
366                 else:
367                     break
368
369     def get_variable_color(self, book_info):
370         return self.epoch_colors.get(book_info.epoch, None)
371
372     def pretty_authors(self):
373         return [a.upper() for a in self.authors]
374
375     def add_box(self, img):
376         if self.box_position == 'none':
377             return img
378
379         metr = Metric(self, self.scale)
380
381         # Write author name.
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,
387                       )
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
395                      )
396
397         box.skip(metr.box_above_line)
398         box.draw.line(
399             (metr.box_line_left, box.height, metr.box_line_right, box.height),
400             fill=self.author_color, width=metr.box_line_width
401         )
402         box.skip(metr.box_below_line)
403
404         # Write title.
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,
410                  font=title_font,
411                  color=self.title_color,
412                  shadow_color=self.title_shadow,
413                  centering=self.title_centering
414                  )
415
416         box_img = box.image()
417
418         # Find box position.
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
423         else:   # Middle.
424             box_top = (metr.height - box_img.size[1]) // 2
425
426         box_left = metr.bar_width + (
427             metr.width - metr.bar_width - box_img.size[0] - self.bleed
428         ) // 2
429
430         # Draw the white box.
431         img_draw = ImageDraw.Draw(img)
432         img_draw.rectangle(
433             (
434                 box_left,
435                 box_top,
436                 box_left + box_img.size[0],
437                 box_top + box_img.size[1]
438             ),
439             fill='#fff'
440         )
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:
444             img_draw.rectangle(
445                 (
446                     box_left,
447                     box_top,
448                     box_left + metr.box_bar_width,
449                     box_top + box_img.size[1]
450                 ),
451                 fill=self.bar_color
452             )
453         return img
454
455     def add_cut_lines(self, img):
456         line_ratio = 0.5
457         if self.bleed == 0:
458             return 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)
464                 ):
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):
468                 draw.line(
469                     (
470                         corner_x,
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
474                     ),
475                     fill='black' if offset == 0 else 'white',
476                     width=1
477                 )
478                 draw.line(
479                     (
480                         corner_x + dir_x * metr.bleed + offset,
481                         corner_y,
482                         corner_x + dir_x * metr.bleed + offset,
483                         corner_y + dir_y * metr.bleed * line_ratio
484                     ),
485                     fill='black' if offset == 0 else 'white',
486                     width=1
487                 )
488         return img
489
490     def image(self):
491         metr = Metric(self, self.scale)
492         img = Image.new('RGB', (metr.width, metr.height),
493                         self.background_color)
494         draw = ImageDraw.Draw(img)
495
496         draw.rectangle((0, 0, metr.bar_width, metr.height),
497                        fill=self.bar_color)
498
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]:
503                 resized = (
504                     trg_size[0],
505                     int(round(src.size[1] * trg_size[0] / src.size[0]))
506                 )
507                 if self.background_top:
508                     cut = 0
509                 else:
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))
513             else:
514                 resized = (
515                     int(round(src.size[0] * trg_size[1] / src.size[1])),
516                     trg_size[1],
517                 )
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]))
521
522             img.paste(src, (metr.bar_width, 0))
523             del src
524
525         img = self.add_box(img)
526
527         # img = self.add_cut_lines(img)
528
529         return img
530
531
532 class WLNoBoxCover(WLCover):
533     def add_box(self, img):
534         return img
535
536
537 class LogoWLCover(WLCover):
538     gradient_height = 90
539     gradient_easing = 90
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
546     gradient_logos = [
547         'res/wl-logo-white.png',
548         'res/fnp-logo-white.png',
549     ]
550     annotation = None
551     annotation_height = 10
552
553     logos_right = True
554     gradient_logo_centering = False
555
556     qrcode = None
557
558
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
563
564         self.additional_cover_logos = [
565             BytesIO(URLOpener().open(cover_logo_url).read())
566             for cover_logo_url in book_info.cover_logo_urls
567         ]
568         self.end_cover_logos = []
569         if cover_logo:
570             self.additional_cover_logos.append(
571                     open(cover_logo, 'rb')
572                     )
573
574     @property
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
577
578     def add_gradient_logos(self, img, metr):
579         gradient = Image.new(
580             'RGBA',
581             (metr.width - metr.bar_width, metr.gradient_height),
582             self.gradient_color
583         )
584         gradient_mask = Image.new(
585             'L',
586             (metr.width - metr.bar_width, metr.gradient_height)
587         )
588         draw = ImageDraw.Draw(gradient_mask)
589         for line in range(0, metr.gradient_easing):
590             draw.line(
591                 (0, line, metr.width - metr.bar_width, line),
592                 fill=int(
593                     255 * self.gradient_opacity * line / metr.gradient_easing
594                 )
595             )
596         draw.rectangle((
597             0, metr.gradient_easing,
598             metr.width - metr.bar_width, metr.gradient_height
599         ), fill=int(255 * self.gradient_opacity))
600             
601             
602         img.paste(gradient,
603                   (metr.bar_width, metr.height - metr.gradient_height),
604                   mask=gradient_mask)
605
606         if self.logos_right:
607             cursor = metr.width - metr.gradient_logo_margin_right
608         else:
609             cursor = metr.gradient_logo_margin_right
610         logo_top = int(
611             metr.height
612             - metr.gradient_height / 2
613             - metr.gradient_logo_height / 2 - metr.bleed
614         )
615
616         logos = [
617             get_resource(logo_path)
618             for logo_path in self.gradient_logos
619         ]
620
621         logos = self.additional_cover_logos + logos + self.end_cover_logos
622
623         logos = [
624             Image.open(logo_bytes).convert('RGBA')
625             for logo_bytes in logos
626         ]
627
628         if self.qrcode is not None:
629             import qrcode
630             logos.append(qrcode.make(f'https://wolnelektury.pl/katalog/lektura/{self.slug}/?{self.qrcode}'))
631
632         if self.logos_right:
633             logos.reverse()
634
635         # See if logos fit into the gradient. If not, scale down accordingly.
636         space_for_logos = (
637             metr.width
638             - metr.bar_width
639             - 2 * metr.gradient_logo_margin_right + self.bleed
640         )
641         widths = [
642             min(
643                 metr.gradient_logo_max_width,
644                 logo.size[0] * metr.gradient_logo_height / logo.size[1]
645             )
646             for logo in logos]
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
650         else:
651             logo_scale = 1
652             if self.gradient_logo_centering:
653                 cursor += int((space_for_logos - taken_space) / 2)
654         logo_scale = (
655             space_for_logos / taken_space
656             if taken_space > space_for_logos else 1
657         )
658         #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
659
660         for i, logo in enumerate(logos):
661             if i == -1:
662                 L_scale = 1
663             else:
664                 L_scale = logo_scale
665             L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
666
667             logo = logo.resize(
668                 (
669                     int(round(widths[i] * L_scale)),
670                     int(round(
671                         logo.size[1] * widths[i] / logo.size[0] * L_scale
672                     ))
673                 ),
674                 Image.ANTIALIAS)
675             if self.logos_right:
676                 cursor -= logo.size[0]
677
678             img.paste(
679                 logo,
680                 (
681                     cursor,
682                     L_top
683                     #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
684                 ),
685                 mask=logo
686             )
687             if self.logos_right:
688                 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
689             else:
690                 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
691
692         if self.annotation:
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')
699             img2.show()
700             img2 = img2.rotate(90)
701             img2.show()
702             img.putalpha(0)
703             img.alpha_composite(img2, (0, 0))
704             img = img.convert('RGB')
705
706         return img
707     
708     def image(self):
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)
713         return img
714
715
716 class LegimiCover(LogoWLCover):
717     width = 210
718     height = 297
719     bar_width = 0
720     # Other bar
721
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')
727     title_font_size = 15
728     title_lineskip = 19.5
729     title_centering = False
730     
731     title_box_width = 210
732
733     box_bottom_margin = 20
734     box_padding_x = 20
735     box_padding_y = 10   # do baseline
736     box_above_line = 6
737     box_below_line = 0
738     box_line_left = 0
739     box_line_right = 0
740
741     box_line_width = 0
742
743     box_bar_width = 20
744
745     #logo_top = 15
746     #logo_width = 140
747
748     bar_color = '#000'
749     box_position = 'bottom'
750     background_color = '#444'
751     author_color = '#000'
752     title_color = '#000'
753     set_title_color = False
754
755     kind_box_position = {}
756
757     box_bottom_margin_logos_add = 10
758     gradient_height = 30
759     gradient_easing = 0
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
766     gradient_logos = [
767         'res/wl-logo-white.png',
768     ]
769     logos_right = False
770     gradient_logo_centering = True
771     background_top = True
772
773     genre_colors = {
774         'Artykuł': '#bf001a',
775         'Artykuł naukowy': '#bf001a',
776         'Dziennik': '#bf001a',
777         'Esej': '#bf001a',
778         'Felieton': '#bf001a',
779         'Kronika': '#bf001a',
780         'List': '#bf001a',
781         'Manifest': '#bf001a',
782         'Odczyt': '#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',
792     }
793     kind_colors = {
794         'Epika': '#9bbb2b',
795         'Liryka': '#3e626f',
796         'Dramat': '#ecbe00',
797     }
798
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
803
804     def pretty_authors(self):
805         return self.authors
806
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]
814
815 class LegimiCornerCover(LegimiCover):
816     gradient_logos = []
817     corner_width = 120
818     corner_image = get_resource('res/book-band.png')
819     
820     def image(self):
821         image = super().image()
822         metr = Metric(self, self.scale)
823
824         if self.corner_image:
825             corner = Image.open(self.corner_image).convert('RGBA')
826             corner = corner.resize(
827                 (
828                     int(round(metr.corner_width)),
829                     int(round(corner.size[1] / corner.size[0] * metr.corner_width))
830                 )
831             )
832             image.paste(corner, (
833                 metr.width - int(round(metr.corner_width)),
834                 0,
835             ), corner)
836         return image
837
838 class LegimiAudiobookCover(LegimiCornerCover):
839     corner_width = 82.5
840     corner_image = get_resource('res/audiobook-sticker.png')
841     height = 210
842
843
844 class EbookpointCover(LogoWLCover):
845     gradient_logo_height = 58
846     gradient_logo_spacing = 25
847     gradient_logos = [
848         'res/ebookpoint-logo-white.png',
849         'res/wl-logo-white.png',
850         'res/fnp-logo-white.png',
851     ]
852
853
854 class VirtualoCover(Cover):
855     width = 600
856     height = 730
857     author_top = 73
858     title_top = 73
859     logo_bottom = 25
860     logo_width = 250
861
862
863 class PrestigioCover(Cover):
864     width = 580
865     height = 783
866     background_img = get_resource('res/cover-prestigio.png')
867
868     author_top = 446
869     author_margin_left = 118
870     author_margin_right = 62
871     author_lineskip = 60
872     author_color = '#fff'
873     author_shadow = '#000'
874     author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
875     author_font_size = 50
876
877     title_top = 0
878     title_margin_left = 118
879     title_margin_right = 62
880     title_lineskip = 60
881     title_color = '#fff'
882     title_shadow = '#000'
883     title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
884     title_font_size = 50
885
886     def pretty_title(self):
887         return u"„%s”" % self.title
888
889
890 class BookotekaCover(Cover):
891     width = 2140
892     height = 2733
893     background_img = get_resource('res/cover-bookoteka.png')
894
895     author_top = 480
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
902
903     title_top = 400
904     title_margin_left = 307
905     title_margin_right = 233
906     title_lineskip = 168
907     title_color = '#d9d919'
908     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
909     title_font_size = 140
910
911     format = 'PNG'
912
913
914 class GandalfCover(Cover):
915     width = 600
916     height = 730
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')
921     title_font_size = 40
922     logo_bottom = 25
923     logo_width = 250
924     format = 'PNG'
925
926
927 class KMLUCover(LogoWLCover):
928     gradient_logo_height = 58
929     gradient_logo_spacing = 25
930     gradient_logos = [
931         'res/kmlu-logo-white.png',
932         'res/wl-logo-white.png',
933         'res/fnp-logo-white.png',
934     ]
935
936
937 class MPWCover(LogoWLCover):
938     gradient_logo_height = 57
939     gradient_logo_spacing = 25
940     gradient_logos = [
941         'res/mpw-logo-white.png',
942         'res/wl-logo-white.png',
943         'res/fnp-logo-white.png',
944     ]
945
946
947 class AtriumCover(LogoWLCover):
948     gradient_logo_height = 58
949     gradient_logo_spacing = 25
950     gradient_logos = [
951         'res/atrium-logo.png',
952         'res/wl-logo-white.png',
953         'res/fnp-logo-white.png',
954     ]
955
956
957 class BNCover(LogoWLCover):
958     gradient_logos = [
959         'res/dofinansowano.png',
960         'res/MKIDN.jpg',
961         'res/BN.png',
962         'res/wl-logo-white.png',
963     ]
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.'
965
966
967 class FactoryCover(LogoWLCover):
968     gradient_logos = [
969         'res/factory.jpg',
970         'res/wl-logo-white.png',
971     ]
972     qrcode = 'pk_campaign=factory22'
973     format = 'PNG'
974
975     def __init__(self, *args, **kwargs):
976         kwargs.setdefault('bleed', 10)
977         return super().__init__(*args, **kwargs)
978
979     def ext(self):
980         return 'pdf'
981
982     def output_file(self, *args, **kwargs):
983         imgfile = super().output_file(*args, **kwargs)
984         import subprocess
985         import tempfile
986         with tempfile.TemporaryDirectory(prefix='factory-', dir='.') as d:
987             import os
988             import shutil
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())
995
996
997
998 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
999
1000 COVER_CLASSES = {
1001     'legacy': LogoWLCover,
1002     'kmlu': KMLUCover,
1003     'mpw': MPWCover,
1004     'atrium': AtriumCover,
1005     'bn': BNCover,
1006     'legimi': LegimiCover,
1007     'legimi-corner': LegimiCornerCover,
1008     'legimi-audiobook': LegimiAudiobookCover,
1009     'factory': FactoryCover,
1010     'm': MarquiseCover,
1011     'm-label': LabelMarquiseCover,
1012     'default': MarquiseCover,
1013 }
1014
1015
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)