a3bd5cddda3e7a05c58f811ae080ce24bb939e8b
[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
167     def set_size(self, width, height):
168         if width and height:
169             self.height = int(round(height * self.width / width))
170         scale = max(float(width or 0) / self.width,
171                     float(height or 0) / self.height)
172         if scale >= 1:
173             self.scale = scale
174         elif scale:
175             self.scale_after = scale
176
177     def pretty_authors(self):
178         """Allows for decorating authors' names."""
179         return self.authors
180
181     def pretty_title(self):
182         """Allows for decorating title."""
183         return self.title
184
185     def image(self):
186         metr = Metric(self, self.scale)
187         img = Image.new('RGB', (metr.width, metr.height),
188                         self.background_color)
189
190         if self.background_img:
191             background = Image.open(self.background_img)
192             img.paste(background, None, background)
193             del background
194
195         # WL logo
196         if metr.logo_width:
197             logo = Image.open(get_resource('res/wl-logo.png'))
198             logo = logo.resize((
199                 metr.logo_width,
200                 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
201             ))
202             img.paste(logo, (
203                 (metr.width - metr.logo_width) // 2,
204                 img.size[1] - logo.size[1] - metr.logo_bottom
205             ))
206
207         top = metr.author_top
208         tbox = TextBox(
209             metr.width - metr.author_margin_left - metr.author_margin_right,
210             metr.height - top,
211             )
212
213         author_font = ImageFont.truetype(
214             self.author_font_ttf, metr.author_font_size,
215             layout_engine=ImageFont.Layout.BASIC)
216         for pa in self.pretty_authors():
217             tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
218                       self.author_shadow)
219         text_img = tbox.image()
220         img.paste(text_img, (metr.author_margin_left, top), text_img)
221
222         top += text_img.size[1] + metr.title_top
223         tbox = TextBox(
224             metr.width - metr.title_margin_left - metr.title_margin_right,
225             metr.height - top,
226             )
227         title_font = ImageFont.truetype(
228             self.title_font_ttf, metr.title_font_size,
229             layout_engine=ImageFont.Layout.BASIC)
230         tbox.text(self.pretty_title(), self.title_color, title_font,
231                   metr.title_lineskip, self.title_shadow)
232         text_img = tbox.image()
233         img.paste(text_img, (metr.title_margin_left, top), text_img)
234
235         return img
236
237     def final_image(self):
238         img = self.image()
239         if self.scale_after != 1:
240             img = img.resize((
241                     int(round(img.size[0] * self.scale_after)),
242                     int(round(img.size[1] * self.scale_after))),
243                 Image.Resampling.LANCZOS)
244         return img
245
246     def mime_type(self):
247         return self.mime_types[self.format]
248
249     def ext(self):
250         return self.exts[self.format]
251
252     def save(self, *args, **kwargs):
253         default_kwargs = {
254                 'format': self.format,
255                 'quality': 95,
256         }
257         default_kwargs.update(kwargs)
258         return self.final_image().save(*args, **default_kwargs)
259
260     def output_file(self, *args, **kwargs):
261         imgstr = BytesIO()
262         self.save(imgstr, *args, **kwargs)
263         return OutputFile.from_bytes(imgstr.getvalue())
264
265
266 class WLCover(Cover):
267     """Wolne Lektury cover without logos."""
268     width = 600
269     height = 833
270     uses_dc_cover = True
271     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
272     author_font_size = 20
273     author_lineskip = 30
274     author_centering = True
275     title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
276     title_font_size = 30
277     title_lineskip = 40
278     title_box_width = 350
279     title_centering = True
280
281     box_top_margin = 100
282     box_bottom_margin = 100
283     box_padding_y = 20
284     box_above_line = 10
285     box_below_line = 15
286     box_line_left = 75
287     box_line_right = 275
288     box_line_width = 2
289     box_padding_x = 0
290     box_bar_width = 0
291
292     logo_top = 15
293     logo_width = 140
294
295     bar_width = 35
296     bar_color = '#000'
297     box_position = 'middle'
298     background_color = '#444'
299     author_color = '#444'
300     background_img = get_resource('res/cover.png')
301     background_top = False
302     format = 'JPEG'
303
304     epoch_colors = {
305         'Starożytność': '#9e3610',
306         'Średniowiecze': '#564c09',
307         'Renesans': '#8ca629',
308         'Barok': '#a6820a',
309         'Oświecenie': '#f2802e',
310         'Romantyzm': '#db4b16',
311         'Pozytywizm': '#961060',
312         'Modernizm': '#7784e0',
313         'Dwudziestolecie międzywojenne': '#3044cf',
314         'Współczesność': '#06393d',
315     }
316     set_title_color = True
317
318     kind_box_position = {
319         'Liryka': 'top',
320         'Epika': 'bottom',
321     }
322
323     def __init__(self, book_info, format=None, width=None, height=None,
324                  bleed=0, cover_logo=None):
325         super(WLCover, self).__init__(book_info, format=format, width=width,
326                                       height=height)
327
328         self.slug = book_info.url.slug
329         # Set box position.
330         self.box_position = book_info.cover_box_position or \
331             self.kind_box_position.get(book_info.kind, self.box_position)
332         # Set bar color.
333         if book_info.cover_bar_color == 'none':
334             self.bar_width = 0
335         else:
336             self.bar_color = book_info.cover_bar_color or \
337                 self.get_variable_color(book_info) or self.bar_color
338         # Set title color.
339         if self.set_title_color:
340             self.title_color = self.get_variable_color(book_info) or self.title_color
341
342         self.bleed = bleed
343         self.box_top_margin += bleed
344         self.box_bottom_margin += bleed
345         self.bar_width += bleed
346
347         if book_info.cover_url:
348             url = book_info.cover_url
349             bg_src = None
350             while True:
351                 try:
352                     if bg_src is None:
353                         import requests
354                         bg_src = requests.get(url, timeout=5)
355                     self.background_img = BytesIO(bg_src.content)
356                     bg_src.close()
357                 except Exception as e:
358                     bg_src = None
359                     print(e)
360                     import time
361                     time.sleep(1)
362                 else:
363                     break
364
365     def get_variable_color(self, book_info):
366         return self.epoch_colors.get(book_info.epoch, None)
367
368     def pretty_authors(self):
369         return [a.upper() for a in self.authors]
370
371     def add_box(self, img):
372         if self.box_position == 'none':
373             return img
374
375         metr = Metric(self, self.scale)
376
377         # Write author name.
378         box = TextBox(metr.title_box_width - 2 * self.bleed, metr.height,
379                       padding_y=metr.box_padding_y,
380                       padding_x=metr.box_padding_x,
381                       bar_width=metr.box_bar_width,
382                       bar_color=self.bar_color,
383                       )
384         author_font = ImageFont.truetype(
385             self.author_font_ttf, metr.author_font_size,
386             layout_engine=ImageFont.Layout.BASIC)
387         for pa in self.pretty_authors():
388             box.text(pa, font=author_font, line_height=metr.author_lineskip,
389                      color=self.author_color, shadow_color=self.author_shadow,
390                      centering=self.author_centering
391                      )
392
393         box.skip(metr.box_above_line)
394         box.draw.line(
395             (metr.box_line_left, box.height, metr.box_line_right, box.height),
396             fill=self.author_color, width=metr.box_line_width
397         )
398         box.skip(metr.box_below_line)
399
400         # Write title.
401         title_font = ImageFont.truetype(
402             self.title_font_ttf, metr.title_font_size,
403             layout_engine=ImageFont.Layout.BASIC)
404         box.text(self.pretty_title(),
405                  line_height=metr.title_lineskip,
406                  font=title_font,
407                  color=self.title_color,
408                  shadow_color=self.title_shadow,
409                  centering=self.title_centering
410                  )
411
412         box_img = box.image()
413
414         # Find box position.
415         if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
416             box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
417         elif self.box_position == 'top':
418             box_top = metr.box_top_margin
419         else:   # Middle.
420             box_top = (metr.height - box_img.size[1]) // 2
421
422         box_left = metr.bar_width + (
423             metr.width - metr.bar_width - box_img.size[0] - self.bleed
424         ) // 2
425
426         # Draw the white box.
427         img_draw = ImageDraw.Draw(img)
428         img_draw.rectangle(
429             (
430                 box_left,
431                 box_top,
432                 box_left + box_img.size[0],
433                 box_top + box_img.size[1]
434             ),
435             fill='#fff'
436         )
437         # Paste the contents into the white box.
438         img.paste(box_img, (box_left, box_top), box_img)
439         if self.box_bar_width:
440             img_draw.rectangle(
441                 (
442                     box_left,
443                     box_top,
444                     box_left + metr.box_bar_width,
445                     box_top + box_img.size[1]
446                 ),
447                 fill=self.bar_color
448             )
449         return img
450
451     def add_cut_lines(self, img):
452         line_ratio = 0.5
453         if self.bleed == 0:
454             return img
455         metr = Metric(self, self.scale)
456         draw = ImageDraw.Draw(img)
457         for corner_x, corner_y in (
458                 (0, 0), (metr.width, 0),
459                 (0, metr.height), (metr.width, metr.height)
460                 ):
461             dir_x = 1 if corner_x == 0 else -1
462             dir_y = 1 if corner_y == 0 else -1
463             for offset in (-1, 0, 1):
464                 draw.line(
465                     (
466                         corner_x,
467                         corner_y + dir_y * metr.bleed + offset,
468                         corner_x + dir_x * metr.bleed * line_ratio,
469                         corner_y + dir_y * metr.bleed + offset
470                     ),
471                     fill='black' if offset == 0 else 'white',
472                     width=1
473                 )
474                 draw.line(
475                     (
476                         corner_x + dir_x * metr.bleed + offset,
477                         corner_y,
478                         corner_x + dir_x * metr.bleed + offset,
479                         corner_y + dir_y * metr.bleed * line_ratio
480                     ),
481                     fill='black' if offset == 0 else 'white',
482                     width=1
483                 )
484         return img
485
486     def image(self):
487         metr = Metric(self, self.scale)
488         img = Image.new('RGB', (metr.width, metr.height),
489                         self.background_color)
490         draw = ImageDraw.Draw(img)
491
492         draw.rectangle((0, 0, metr.bar_width, metr.height),
493                        fill=self.bar_color)
494
495         if self.background_img:
496             src = Image.open(self.background_img)
497             trg_size = (metr.width - metr.bar_width, metr.height)
498             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
499                 resized = (
500                     trg_size[0],
501                     int(round(src.size[1] * trg_size[0] / src.size[0]))
502                 )
503                 if self.background_top:
504                     cut = 0
505                 else:
506                     cut = (resized[1] - trg_size[1]) // 2
507                 src = src.resize(resized, Image.Resampling.LANCZOS)
508                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
509             else:
510                 resized = (
511                     int(round(src.size[0] * trg_size[1] / src.size[1])),
512                     trg_size[1],
513                 )
514                 cut = (resized[0] - trg_size[0]) // 2
515                 src = src.resize(resized, Image.Resampling.LANCZOS)
516                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
517
518             img.paste(src, (metr.bar_width, 0))
519             del src
520
521         img = self.add_box(img)
522
523         # img = self.add_cut_lines(img)
524
525         return img
526
527
528 class WLNoBoxCover(WLCover):
529     def add_box(self, img):
530         return img
531
532
533 class LogoWLCover(WLCover):
534     gradient_height = 90
535     gradient_easing = 90
536     gradient_logo_height = 57
537     gradient_logo_max_width = 200
538     gradient_logo_margin_right = 30
539     gradient_logo_spacing = 40
540     gradient_color = '#000'
541     gradient_opacity = .6
542     gradient_logos = [
543         'res/wl-logo-white.png',
544         'res/fnp-logo-white.png',
545     ]
546     annotation = None
547     annotation_height = 10
548
549     logos_right = True
550     gradient_logo_centering = False
551
552     qrcode = None
553
554
555     def __init__(self, book_info, *args, cover_logo=None, **kwargs):
556         super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
557         self.gradient_height += self.bleed
558         self.gradient_logo_margin_right += self.bleed
559
560         self.additional_cover_logos = [
561             BytesIO(URLOpener().open(cover_logo_url).read())
562             for cover_logo_url in book_info.cover_logo_urls
563         ]
564         self.end_cover_logos = []
565         if cover_logo:
566             self.additional_cover_logos.append(
567                     open(cover_logo, 'rb')
568                     )
569
570     @property
571     def has_gradient_logos(self):
572         return self.gradient_logos or self.additional_cover_logos or self.end_cover_logos or self.annotation or self.qrcode is not None
573
574     def add_gradient_logos(self, img, metr):
575         gradient = Image.new(
576             'RGBA',
577             (metr.width - metr.bar_width, metr.gradient_height),
578             self.gradient_color
579         )
580         gradient_mask = Image.new(
581             'L',
582             (metr.width - metr.bar_width, metr.gradient_height)
583         )
584         draw = ImageDraw.Draw(gradient_mask)
585         for line in range(0, metr.gradient_easing):
586             draw.line(
587                 (0, line, metr.width - metr.bar_width, line),
588                 fill=int(
589                     255 * self.gradient_opacity * line / metr.gradient_easing
590                 )
591             )
592         draw.rectangle((
593             0, metr.gradient_easing,
594             metr.width - metr.bar_width, metr.gradient_height
595         ), fill=int(255 * self.gradient_opacity))
596             
597             
598         img.paste(gradient,
599                   (metr.bar_width, metr.height - metr.gradient_height),
600                   mask=gradient_mask)
601
602         if self.logos_right:
603             cursor = metr.width - metr.gradient_logo_margin_right
604         else:
605             cursor = metr.gradient_logo_margin_right
606         logo_top = int(
607             metr.height
608             - metr.gradient_height / 2
609             - metr.gradient_logo_height / 2 - metr.bleed
610         )
611
612         logos = [
613             get_resource(logo_path)
614             for logo_path in self.gradient_logos
615         ]
616
617         logos = self.additional_cover_logos + logos + self.end_cover_logos
618
619         logos = [
620             Image.open(logo_bytes).convert('RGBA')
621             for logo_bytes in logos
622         ]
623
624         if self.qrcode is not None:
625             import qrcode
626             logos.append(qrcode.make(f'https://wolnelektury.pl/katalog/lektura/{self.slug}/?{self.qrcode}'))
627
628         if self.logos_right:
629             logos.reverse()
630
631         # See if logos fit into the gradient. If not, scale down accordingly.
632         space_for_logos = (
633             metr.width
634             - metr.bar_width
635             - 2 * metr.gradient_logo_margin_right + self.bleed
636         )
637         widths = [
638             min(
639                 metr.gradient_logo_max_width,
640                 logo.size[0] * metr.gradient_logo_height / logo.size[1]
641             )
642             for logo in logos]
643         taken_space = sum(widths) + (len(logos) - 1) * metr.gradient_logo_spacing
644         if taken_space > space_for_logos:
645             logo_scale = space_for_logos / taken_space
646         else:
647             logo_scale = 1
648             if self.gradient_logo_centering:
649                 cursor += int((space_for_logos - taken_space) / 2)
650         logo_scale = (
651             space_for_logos / taken_space
652             if taken_space > space_for_logos else 1
653         )
654         #logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
655
656         for i, logo in enumerate(logos):
657             if i == -1:
658                 L_scale = 1
659             else:
660                 L_scale = logo_scale
661             L_top = logo_top + int(metr.gradient_logo_height * (1 - L_scale) / 2)
662
663             logo = logo.resize(
664                 (
665                     int(round(widths[i] * L_scale)),
666                     int(round(
667                         logo.size[1] * widths[i] / logo.size[0] * L_scale
668                     ))
669                 ),
670                 Image.Resampling.LANCZOS)
671             if self.logos_right:
672                 cursor -= logo.size[0]
673
674             img.paste(
675                 logo,
676                 (
677                     cursor,
678                     L_top
679                     #int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * L_scale / 2))
680                 ),
681                 mask=logo
682             )
683             if self.logos_right:
684                 cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
685             else:
686                 cursor += int(round(metr.gradient_logo_spacing * logo_scale)) + logo.size[0]
687
688         if self.annotation:
689             img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
690             draw = ImageDraw.Draw(img2)
691             author_font = ImageFont.truetype(
692                 self.author_font_ttf, metr.annotation_height,
693                 layout_engine=ImageFont.Layout.BASIC)
694             draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
695             img2.show()
696             img2 = img2.rotate(90)
697             img2.show()
698             img.putalpha(0)
699             img.alpha_composite(img2, (0, 0))
700             img = img.convert('RGB')
701
702         return img
703     
704     def image(self):
705         img = super(LogoWLCover, self).image()
706         metr = Metric(self, self.scale)
707         if self.has_gradient_logos:
708             img = self.add_gradient_logos(img, metr)
709         return img
710
711
712 class LegimiCover(LogoWLCover):
713     width = 210
714     height = 297
715     bar_width = 0
716     # Other bar
717
718     author_font_ttf = get_resource('fonts/Lora-Regular.ttf')
719     author_font_size = 15
720     author_lineskip = 19.5
721     author_centering = False
722     title_font_ttf = get_resource('fonts/Lora-Bold.ttf')
723     title_font_size = 15
724     title_lineskip = 19.5
725     title_centering = False
726     
727     title_box_width = 210
728
729     box_bottom_margin = 20
730     box_padding_x = 20
731     box_padding_y = 10   # do baseline
732     box_above_line = 6
733     box_below_line = 0
734     box_line_left = 0
735     box_line_right = 0
736
737     box_line_width = 0
738
739     box_bar_width = 20
740
741     #logo_top = 15
742     #logo_width = 140
743
744     bar_color = '#000'
745     box_position = 'bottom'
746     background_color = '#444'
747     author_color = '#000'
748     title_color = '#000'
749     set_title_color = False
750
751     kind_box_position = {}
752
753     box_bottom_margin_logos_add = 10
754     gradient_height = 30
755     gradient_easing = 0
756     gradient_logo_height = 20
757     gradient_logo_max_width = 200
758     gradient_logo_margin_right = 10
759     gradient_logo_spacing = 20
760     gradient_color = '#000'
761     gradient_opacity = .5
762     gradient_logos = [
763         'res/wl-logo-white.png',
764     ]
765     logos_right = False
766     gradient_logo_centering = True
767     background_top = True
768
769     genre_colors = {
770         'Artykuł': '#bf001a',
771         'Artykuł naukowy': '#bf001a',
772         'Dziennik': '#bf001a',
773         'Esej': '#bf001a',
774         'Felieton': '#bf001a',
775         'Kronika': '#bf001a',
776         'List': '#bf001a',
777         'Manifest': '#bf001a',
778         'Odczyt': '#bf001a',
779         'Pamiętnik': '#bf001a',
780         'Poradnik': '#bf001a',
781         'Praca naukowa': '#bf001a',
782         'Publicystyka': '#bf001a',
783         'Reportaż': '#bf001a',
784         'Reportaż podróżniczy': '#bf001a',
785         'Rozprawa': '#bf001a',
786         'Rozprawa polityczna': '#bf001a',
787         'Traktat': '#bf001a',
788     }
789     kind_colors = {
790         'Epika': '#9bbb2b',
791         'Liryka': '#3e626f',
792         'Dramat': '#ecbe00',
793     }
794
795     def __init__(self, *args, **kwargs):
796         super().__init__(*args, **kwargs)
797         if self.has_gradient_logos:
798             self.box_bottom_margin += self.box_bottom_margin_logos_add
799
800     def pretty_authors(self):
801         return self.authors
802
803     def get_variable_color(self, book_info):
804         for genre in book_info.genres:
805             if genre in self.genre_colors:
806                 return self.genre_colors[genre]
807         for kind in book_info.kinds:
808             if kind in self.kind_colors:
809                 return self.kind_colors[kind]
810
811 class LegimiCornerCover(LegimiCover):
812     gradient_logos = []
813     corner_width = 120
814     corner_image = get_resource('res/book-band.png')
815     
816     def image(self):
817         image = super().image()
818         metr = Metric(self, self.scale)
819
820         if self.corner_image:
821             corner = Image.open(self.corner_image).convert('RGBA')
822             corner = corner.resize(
823                 (
824                     int(round(metr.corner_width)),
825                     int(round(corner.size[1] / corner.size[0] * metr.corner_width))
826                 )
827             )
828             image.paste(corner, (
829                 metr.width - int(round(metr.corner_width)),
830                 0,
831             ), corner)
832         return image
833
834 class LegimiAudiobookCover(LegimiCornerCover):
835     corner_width = 82.5
836     corner_image = get_resource('res/audiobook-sticker.png')
837     height = 210
838
839
840 class EbookpointCover(LogoWLCover):
841     gradient_logo_height = 58
842     gradient_logo_spacing = 25
843     gradient_logos = [
844         'res/ebookpoint-logo-white.png',
845         'res/wl-logo-white.png',
846         'res/fnp-logo-white.png',
847     ]
848
849
850 class VirtualoCover(Cover):
851     width = 600
852     height = 730
853     author_top = 73
854     title_top = 73
855     logo_bottom = 25
856     logo_width = 250
857
858
859 class PrestigioCover(Cover):
860     width = 580
861     height = 783
862     background_img = get_resource('res/cover-prestigio.png')
863
864     author_top = 446
865     author_margin_left = 118
866     author_margin_right = 62
867     author_lineskip = 60
868     author_color = '#fff'
869     author_shadow = '#000'
870     author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
871     author_font_size = 50
872
873     title_top = 0
874     title_margin_left = 118
875     title_margin_right = 62
876     title_lineskip = 60
877     title_color = '#fff'
878     title_shadow = '#000'
879     title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
880     title_font_size = 50
881
882     def pretty_title(self):
883         return "„%s”" % self.title
884
885
886 class BookotekaCover(Cover):
887     width = 2140
888     height = 2733
889     background_img = get_resource('res/cover-bookoteka.png')
890
891     author_top = 480
892     author_margin_left = 307
893     author_margin_right = 233
894     author_lineskip = 156
895     author_color = '#d9d919'
896     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
897     author_font_size = 130
898
899     title_top = 400
900     title_margin_left = 307
901     title_margin_right = 233
902     title_lineskip = 168
903     title_color = '#d9d919'
904     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
905     title_font_size = 140
906
907     format = 'PNG'
908
909
910 class GandalfCover(Cover):
911     width = 600
912     height = 730
913     background_img = get_resource('res/cover-gandalf.png')
914     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
915     author_font_size = 30
916     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
917     title_font_size = 40
918     logo_bottom = 25
919     logo_width = 250
920     format = 'PNG'
921
922
923 class KMLUCover(LogoWLCover):
924     gradient_logo_height = 58
925     gradient_logo_spacing = 25
926     gradient_logos = [
927         'res/kmlu-logo-white.png',
928         'res/wl-logo-white.png',
929         'res/fnp-logo-white.png',
930     ]
931
932
933 class MPWCover(LogoWLCover):
934     gradient_logo_height = 57
935     gradient_logo_spacing = 25
936     gradient_logos = [
937         'res/mpw-logo-white.png',
938         'res/wl-logo-white.png',
939         'res/fnp-logo-white.png',
940     ]
941
942
943 class AtriumCover(LogoWLCover):
944     gradient_logo_height = 58
945     gradient_logo_spacing = 25
946     gradient_logos = [
947         'res/atrium-logo.png',
948         'res/wl-logo-white.png',
949         'res/fnp-logo-white.png',
950     ]
951
952
953 class BNCover(LogoWLCover):
954     gradient_logos = [
955         'res/dofinansowano.png',
956         'res/MKIDN.jpg',
957         'res/BN.png',
958         'res/wl-logo-white.png',
959     ]
960 #    annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
961
962
963 class FactoryCover(LogoWLCover):
964     gradient_logos = [
965         'res/factory.jpg',
966         'res/wl-logo-white.png',
967     ]
968     qrcode = 'pk_campaign=factory22'
969     format = 'PNG'
970
971     def __init__(self, *args, **kwargs):
972         kwargs.setdefault('bleed', 10)
973         return super().__init__(*args, **kwargs)
974
975     def ext(self):
976         return 'pdf'
977
978     def output_file(self, *args, **kwargs):
979         imgfile = super().output_file(*args, **kwargs)
980         import subprocess
981         import tempfile
982         with tempfile.TemporaryDirectory(prefix='factory-', dir='.') as d:
983             import os
984             import shutil
985             with open(d + '/cover.png', 'wb') as f:
986                 f.write(imgfile.get_bytes())
987             shutil.copy(get_resource('res/factory-cover.svg'), d)
988             subprocess.call(['inkscape', f'--export-filename={d}/cover.pdf', d + '/factory-cover.svg'])
989             with open(d + '/cover.pdf', 'rb') as f:
990                 return OutputFile.from_bytes(f.read())
991
992
993
994 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
995
996 COVER_CLASSES = {
997     'legacy': LogoWLCover,
998     'kmlu': KMLUCover,
999     'mpw': MPWCover,
1000     'atrium': AtriumCover,
1001     'bn': BNCover,
1002     'legimi': LegimiCover,
1003     'legimi-corner': LegimiCornerCover,
1004     'legimi-audiobook': LegimiAudiobookCover,
1005     'factory': FactoryCover,
1006     'm': MarquiseCover,
1007     'm-label': LabelMarquiseCover,
1008     'default': MarquiseCover,
1009 }
1010
1011
1012 def make_cover(book_info, *args, **kwargs):
1013     cover_class_name = None
1014     if 'cover_class' in kwargs:
1015         cover_class_name = kwargs.pop('cover_class')
1016     if not cover_class_name:
1017         cover_class_name = 'default'
1018     cover_class = COVER_CLASSES[cover_class_name]
1019     return cover_class(book_info, *args, **kwargs)