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