8f7b6565993270be5d586c6a984cadfe987ef8d7
[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):
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.max_text_width = max_width - 2 * padding_x
43         self.padding_y = padding_y
44         self.height = padding_y
45         self.img = Image.new('RGBA', (max_width, max_height))
46         self.draw = ImageDraw.Draw(self.img)
47         self.shadow_img = None
48         self.shadow_draw = None
49
50     def skip(self, height):
51         """Skips some vertical space."""
52         self.height += height
53
54     def text(self, text, color='#000', font=None, line_height=20,
55              shadow_color=None):
56         """Writes some centered text."""
57         text = re.sub(r'\s+', ' ', text)
58         if shadow_color:
59             if not self.shadow_img:
60                 self.shadow_img = Image.new('RGBA', self.img.size)
61                 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
62         while text:
63             line = text
64             line_width = self.draw.textsize(line, font=font)[0]
65             while line_width > self.max_text_width:
66                 parts = line.rsplit(' ', 1)
67                 if len(parts) == 1:
68                     line_width = self.max_text_width
69                     break
70                 line = parts[0]
71
72                 if line[-2] == ' ':
73                     line = line[:-2]
74
75                 line_width = self.draw.textsize(line, font=font)[0]
76             line = line.strip() + ' '
77
78             pos_x = (self.max_width - line_width) // 2
79
80             if shadow_color:
81                 self.shadow_draw.text(
82                         (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
83                         line, font=font, fill=shadow_color
84                 )
85
86             self.draw.text((pos_x, self.height), line, font=font, fill=color)
87             self.height += line_height
88             # go to next line
89             text = text[len(line):]
90
91     def image(self):
92         """Creates the actual Image object."""
93         image = Image.new('RGBA', (self.max_width,
94                                    self.height + self.padding_y))
95         if self.shadow_img:
96             shadow = self.shadow_img.filter(ImageFilter.BLUR)
97             image.paste(shadow, (0, 0), shadow)
98             image.paste(self.img, (0, 0), self.img)
99         else:
100             image.paste(self.img, (0, 0))
101         return image
102
103
104 class Cover(object):
105     """Abstract base class for cover images generator."""
106     width = 600
107     height = 800
108     background_color = '#fff'
109     background_img = None
110
111     author_top = 100
112     author_margin_left = 20
113     author_margin_right = 20
114     author_lineskip = 40
115     author_color = '#000'
116     author_shadow = None
117     author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
118     author_font_size = 30
119
120     title_top = 100
121     title_margin_left = 20
122     title_margin_right = 20
123     title_lineskip = 54
124     title_color = '#000'
125     title_shadow = None
126     title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
127     title_font_size = 40
128
129     logo_bottom = None
130     logo_width = None
131     uses_dc_cover = False
132
133     format = 'JPEG'
134     scale = 1
135     scale_after = 1
136
137     exts = {
138         'JPEG': 'jpg',
139         'PNG': 'png',
140         }
141
142     mime_types = {
143         'JPEG': 'image/jpeg',
144         'PNG': 'image/png',
145         }
146
147     def __init__(self, book_info, format=None, width=None, height=None):
148         self.authors = [auth.readable() for auth in book_info.authors]
149         self.title = book_info.title
150         if format is not None:
151             self.format = format
152         if width and height:
153             self.height = int(round(height * self.width / width))
154         scale = max(float(width or 0) / self.width,
155                     float(height or 0) / self.height)
156         if scale >= 1:
157             self.scale = scale
158         elif scale:
159             self.scale_after = scale
160
161     def pretty_authors(self):
162         """Allows for decorating authors' names."""
163         return [self.authors]
164
165     def pretty_title(self):
166         """Allows for decorating title."""
167         return self.title
168
169     def image(self):
170         metr = Metric(self, self.scale)
171         img = Image.new('RGB', (metr.width, metr.height),
172                         self.background_color)
173
174         if self.background_img:
175             background = Image.open(self.background_img)
176             img.paste(background, None, background)
177             del background
178
179         # WL logo
180         if metr.logo_width:
181             logo = Image.open(get_resource('res/wl-logo.png'))
182             logo = logo.resize((
183                 metr.logo_width,
184                 int(round(logo.size[1] * metr.logo_width / logo.size[0]))
185             ))
186             img.paste(logo, (
187                 (metr.width - metr.logo_width) // 2,
188                 img.size[1] - logo.size[1] - metr.logo_bottom
189             ))
190
191         top = metr.author_top
192         tbox = TextBox(
193             metr.width - metr.author_margin_left - metr.author_margin_right,
194             metr.height - top,
195             )
196
197         author_font = ImageFont.truetype(
198             self.author_font_ttf, metr.author_font_size,
199             layout_engine=ImageFont.LAYOUT_BASIC)
200         for pa in self.pretty_authors():
201             tbox.text(pa, self.author_color, author_font, metr.author_lineskip,
202                       self.author_shadow)
203         text_img = tbox.image()
204         img.paste(text_img, (metr.author_margin_left, top), text_img)
205
206         top += text_img.size[1] + metr.title_top
207         tbox = TextBox(
208             metr.width - metr.title_margin_left - metr.title_margin_right,
209             metr.height - top,
210             )
211         title_font = ImageFont.truetype(
212             self.title_font_ttf, metr.title_font_size,
213             layout_engine=ImageFont.LAYOUT_BASIC)
214         tbox.text(self.pretty_title(), self.title_color, title_font,
215                   metr.title_lineskip, self.title_shadow)
216         text_img = tbox.image()
217         img.paste(text_img, (metr.title_margin_left, top), text_img)
218
219         return img
220
221     def final_image(self):
222         img = self.image()
223         if self.scale_after != 1:
224             img = img.resize((
225                     int(round(img.size[0] * self.scale_after)),
226                     int(round(img.size[1] * self.scale_after))),
227                 Image.ANTIALIAS)
228         return img
229
230     def mime_type(self):
231         return self.mime_types[self.format]
232
233     def ext(self):
234         return self.exts[self.format]
235
236     def save(self, *args, **kwargs):
237         default_kwargs = {
238                 'format': self.format,
239                 'quality': 95,
240         }
241         default_kwargs.update(kwargs)
242         return self.final_image().save(*args, **default_kwargs)
243
244     def output_file(self, *args, **kwargs):
245         imgstr = BytesIO()
246         self.save(imgstr, *args, **kwargs)
247         return OutputFile.from_bytes(imgstr.getvalue())
248
249
250 class WLCover(Cover):
251     """Wolne Lektury cover without logos."""
252     width = 600
253     height = 833
254     uses_dc_cover = True
255     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
256     author_font_size = 20
257     author_lineskip = 30
258     title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
259     title_font_size = 30
260     title_lineskip = 40
261     title_box_width = 350
262
263     box_top_margin = 100
264     box_bottom_margin = 100
265     box_padding_y = 20
266     box_above_line = 10
267     box_below_line = 15
268     box_line_left = 75
269     box_line_right = 275
270     box_line_width = 2
271
272     logo_top = 15
273     logo_width = 140
274
275     bar_width = 35
276     bar_color = '#000'
277     box_position = 'middle'
278     background_color = '#444'
279     author_color = '#444'
280     background_img = get_resource('res/cover.png')
281     format = 'JPEG'
282
283     epoch_colors = {
284         u'Starożytność': '#9e3610',
285         u'Średniowiecze': '#564c09',
286         u'Renesans': '#8ca629',
287         u'Barok': '#a6820a',
288         u'Oświecenie': '#f2802e',
289         u'Romantyzm': '#db4b16',
290         u'Pozytywizm': '#961060',
291         u'Modernizm': '#7784e0',
292         u'Dwudziestolecie międzywojenne': '#3044cf',
293         u'Współczesność': '#06393d',
294     }
295
296     kind_box_position = {
297         u'Liryka': 'top',
298         u'Epika': 'bottom',
299     }
300
301     def __init__(self, book_info, format=None, width=None, height=None,
302                  bleed=0):
303         super(WLCover, self).__init__(book_info, format=format, width=width,
304                                       height=height)
305         # Set box position.
306         self.box_position = book_info.cover_box_position or \
307             self.kind_box_position.get(book_info.kind, self.box_position)
308         # Set bar color.
309         if book_info.cover_bar_color == 'none':
310             self.bar_width = 0
311         else:
312             self.bar_color = book_info.cover_bar_color or \
313                 self.epoch_colors.get(book_info.epoch, self.bar_color)
314         # Set title color.
315         self.title_color = self.epoch_colors.get(book_info.epoch,
316                                                  self.title_color)
317
318         self.bleed = bleed
319         self.box_top_margin += bleed
320         self.box_bottom_margin += bleed
321         self.bar_width += bleed
322
323         if book_info.cover_url:
324             url = book_info.cover_url
325             bg_src = None
326             if bg_src is None:
327                 bg_src = URLOpener().open(url)
328             self.background_img = BytesIO(bg_src.read())
329             bg_src.close()
330
331     def pretty_authors(self):
332         return [a.upper() for a in self.authors]
333
334     def add_box(self, img):
335         if self.box_position == 'none':
336             return img
337
338         metr = Metric(self, self.scale)
339
340         # Write author name.
341         box = TextBox(metr.title_box_width, metr.height,
342                       padding_y=metr.box_padding_y)
343         author_font = ImageFont.truetype(
344             self.author_font_ttf, metr.author_font_size,
345             layout_engine=ImageFont.LAYOUT_BASIC)
346         for pa in self.pretty_authors():
347             box.text(pa, font=author_font, line_height=metr.author_lineskip,
348                      color=self.author_color, shadow_color=self.author_shadow)
349
350         box.skip(metr.box_above_line)
351         box.draw.line(
352             (metr.box_line_left, box.height, metr.box_line_right, box.height),
353             fill=self.author_color, width=metr.box_line_width
354         )
355         box.skip(metr.box_below_line)
356
357         # Write title.
358         title_font = ImageFont.truetype(
359             self.title_font_ttf, metr.title_font_size,
360             layout_engine=ImageFont.LAYOUT_BASIC)
361         box.text(self.pretty_title(),
362                  line_height=metr.title_lineskip,
363                  font=title_font,
364                  color=self.title_color,
365                  shadow_color=self.title_shadow)
366
367         box_img = box.image()
368
369         # Find box position.
370         if self.box_position == 'bottom' or box_img.size[1] + metr.box_top_margin + metr.box_bottom_margin > metr.height:
371             box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
372         elif self.box_position == 'top':
373             box_top = metr.box_top_margin
374         else:   # Middle.
375             box_top = (metr.height - box_img.size[1]) // 2
376
377         box_left = metr.bar_width + (
378             metr.width - metr.bar_width - box_img.size[0]
379         ) // 2
380
381         # Draw the white box.
382         ImageDraw.Draw(img).rectangle(
383             (
384                 box_left,
385                 box_top,
386                 box_left + box_img.size[0],
387                 box_top + box_img.size[1]
388             ),
389             fill='#fff'
390         )
391         # Paste the contents into the white box.
392         img.paste(box_img, (box_left, box_top), box_img)
393         return img
394
395     def add_cut_lines(self, img):
396         line_ratio = 0.5
397         if self.bleed == 0:
398             return img
399         metr = Metric(self, self.scale)
400         draw = ImageDraw.Draw(img)
401         for corner_x, corner_y in (
402                 (0, 0), (metr.width, 0),
403                 (0, metr.height), (metr.width, metr.height)
404                 ):
405             dir_x = 1 if corner_x == 0 else -1
406             dir_y = 1 if corner_y == 0 else -1
407             for offset in (-1, 0, 1):
408                 draw.line(
409                     (
410                         corner_x,
411                         corner_y + dir_y * metr.bleed + offset,
412                         corner_x + dir_x * metr.bleed * line_ratio,
413                         corner_y + dir_y * metr.bleed + offset
414                     ),
415                     fill='black' if offset == 0 else 'white',
416                     width=1
417                 )
418                 draw.line(
419                     (
420                         corner_x + dir_x * metr.bleed + offset,
421                         corner_y,
422                         corner_x + dir_x * metr.bleed + offset,
423                         corner_y + dir_y * metr.bleed * line_ratio
424                     ),
425                     fill='black' if offset == 0 else 'white',
426                     width=1
427                 )
428         return img
429
430     def image(self):
431         metr = Metric(self, self.scale)
432         img = Image.new('RGB', (metr.width, metr.height),
433                         self.background_color)
434         draw = ImageDraw.Draw(img)
435
436         draw.rectangle((0, 0, metr.bar_width, metr.height),
437                        fill=self.bar_color)
438
439         if self.background_img:
440             src = Image.open(self.background_img)
441             trg_size = (metr.width - metr.bar_width, metr.height)
442             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
443                 resized = (
444                     trg_size[0],
445                     int(round(src.size[1] * trg_size[0] / src.size[0]))
446                 )
447                 cut = (resized[1] - trg_size[1]) // 2
448                 src = src.resize(resized, Image.ANTIALIAS)
449                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
450             else:
451                 resized = (
452                     int(round(src.size[0] * trg_size[1] / src.size[1])),
453                     trg_size[1],
454                 )
455                 cut = (resized[0] - trg_size[0]) // 2
456                 src = src.resize(resized, Image.ANTIALIAS)
457                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
458
459             img.paste(src, (metr.bar_width, 0))
460             del src
461
462         img = self.add_box(img)
463
464         # img = self.add_cut_lines(img)
465
466         return img
467
468
469 class WLNoBoxCover(WLCover):
470     def add_box(self, img):
471         return img
472
473
474 class LogoWLCover(WLCover):
475     gradient_height = 90
476     gradient_logo_height = 60
477     gradient_logo_max_width = 1000
478     gradient_logo_margin_right = 30
479     gradient_logo_spacing = 40
480     gradient_color = '#000'
481     gradient_opacity = .6
482     gradient_logos = [
483         'res/wl-logo-white.png',
484         'res/fnp-logo-white.png',
485     ]
486     annotation = None
487     annotation_height = 10
488
489     def __init__(self, book_info, *args, **kwargs):
490         super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
491         self.gradient_height += self.bleed
492         self.gradient_logo_margin_right += self.bleed
493
494         self.additional_cover_logos = [
495             BytesIO(URLOpener().open(cover_logo_url).read())
496             for cover_logo_url in book_info.cover_logo_urls
497         ]
498
499     def image(self):
500         img = super(LogoWLCover, self).image()
501         metr = Metric(self, self.scale)
502         gradient = Image.new(
503             'RGBA',
504             (metr.width - metr.bar_width, metr.gradient_height),
505             self.gradient_color
506         )
507         gradient_mask = Image.new(
508             'L',
509             (metr.width - metr.bar_width, metr.gradient_height)
510         )
511         draw = ImageDraw.Draw(gradient_mask)
512         for line in range(0, metr.gradient_height):
513             draw.line(
514                 (0, line, metr.width - metr.bar_width, line),
515                 fill=int(
516                     255 * self.gradient_opacity * line / metr.gradient_height
517                 )
518             )
519         img.paste(gradient,
520                   (metr.bar_width, metr.height - metr.gradient_height),
521                   mask=gradient_mask)
522
523         cursor = metr.width - metr.gradient_logo_margin_right
524         logo_top = int(
525             metr.height
526             - metr.gradient_height / 2
527             - metr.gradient_logo_height / 2 - metr.bleed / 2
528         )
529
530         logos = [
531             get_resource(logo_path)
532             for logo_path in self.gradient_logos[::-1]
533         ]
534         logos = logos + self.additional_cover_logos
535         logos = [
536             Image.open(logo_bytes).convert('RGBA')
537             for logo_bytes in logos
538         ]
539
540         # See if logos fit into the gradient. If not, scale down accordingly.
541         space_for_logos = (
542             metr.width
543             - metr.bar_width
544             - 2 * metr.gradient_logo_margin_right
545         )
546         widths = [
547             min(
548                 metr.gradient_logo_max_width,
549                 logo.size[0] * metr.gradient_logo_height / logo.size[1]
550             )
551             for logo in logos]
552         taken_space = (
553             sum(widths)
554             + (len(logos) - 1) * (metr.gradient_logo_spacing)
555         )
556         logo_scale = (
557             space_for_logos / taken_space
558             if taken_space > space_for_logos else 1
559         )
560         logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
561
562         for i, logo in enumerate(logos):
563             logo = logo.resize(
564                 (
565                     int(round(widths[i] * logo_scale)),
566                     int(round(
567                         logo.size[1] * widths[i] / logo.size[0] * logo_scale
568                     ))
569                 ),
570                 Image.ANTIALIAS)
571             cursor -= logo.size[0]
572             img.paste(
573                 logo,
574                 (
575                     cursor,
576                     int(round(logo_top + (metr.gradient_logo_height - logo.size[1]) * logo_scale / 2))
577                 ),
578                 mask=logo
579             )
580             cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
581
582         if self.annotation:
583             img2 = Image.new('RGBA', (metr.height, metr.height), color=None)
584             draw = ImageDraw.Draw(img2)
585             author_font = ImageFont.truetype(
586                 self.author_font_ttf, metr.annotation_height,
587                 layout_engine=ImageFont.LAYOUT_BASIC)
588             draw.text((self.annotation_height, self.annotation_height), self.annotation, font=author_font, fill='#FFFFFF')
589             img2.show()
590             img2 = img2.rotate(90)
591             img2.show()
592             img.putalpha(0)
593             img.alpha_composite(img2, (0, 0))
594             img = img.convert('RGB')
595
596         return img
597
598
599 class EbookpointCover(LogoWLCover):
600     gradient_logo_height = 58
601     gradient_logo_spacing = 25
602     gradient_logos = [
603         'res/ebookpoint-logo-white.png',
604         'res/wl-logo-white.png',
605         'res/fnp-logo-white.png',
606     ]
607
608
609 class VirtualoCover(Cover):
610     width = 600
611     height = 730
612     author_top = 73
613     title_top = 73
614     logo_bottom = 25
615     logo_width = 250
616
617
618 class PrestigioCover(Cover):
619     width = 580
620     height = 783
621     background_img = get_resource('res/cover-prestigio.png')
622
623     author_top = 446
624     author_margin_left = 118
625     author_margin_right = 62
626     author_lineskip = 60
627     author_color = '#fff'
628     author_shadow = '#000'
629     author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
630     author_font_size = 50
631
632     title_top = 0
633     title_margin_left = 118
634     title_margin_right = 62
635     title_lineskip = 60
636     title_color = '#fff'
637     title_shadow = '#000'
638     title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
639     title_font_size = 50
640
641     def pretty_title(self):
642         return u"„%s”" % self.title
643
644
645 class BookotekaCover(Cover):
646     width = 2140
647     height = 2733
648     background_img = get_resource('res/cover-bookoteka.png')
649
650     author_top = 480
651     author_margin_left = 307
652     author_margin_right = 233
653     author_lineskip = 156
654     author_color = '#d9d919'
655     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
656     author_font_size = 130
657
658     title_top = 400
659     title_margin_left = 307
660     title_margin_right = 233
661     title_lineskip = 168
662     title_color = '#d9d919'
663     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
664     title_font_size = 140
665
666     format = 'PNG'
667
668
669 class GandalfCover(Cover):
670     width = 600
671     height = 730
672     background_img = get_resource('res/cover-gandalf.png')
673     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
674     author_font_size = 30
675     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
676     title_font_size = 40
677     logo_bottom = 25
678     logo_width = 250
679     format = 'PNG'
680
681
682 class KMLUCover(LogoWLCover):
683     gradient_logo_height = 58
684     gradient_logo_spacing = 25
685     gradient_logos = [
686         'res/kmlu-logo-white.png',
687         'res/wl-logo-white.png',
688         'res/fnp-logo-white.png',
689     ]
690
691
692 class MPWCover(LogoWLCover):
693     gradient_logo_height = 58
694     gradient_logo_spacing = 25
695     gradient_logos = [
696         'res/mpw-logo-white.png',
697         'res/wl-logo-white.png',
698         'res/fnp-logo-white.png',
699     ]
700
701
702 class AtriumCover(LogoWLCover):
703     gradient_logo_height = 58
704     gradient_logo_spacing = 25
705     gradient_logos = [
706         'res/atrium-logo.png',
707         'res/wl-logo-white.png',
708         'res/fnp-logo-white.png',
709     ]
710
711
712 class BNCover(LogoWLCover):
713     gradient_logos = [
714         'res/dofinansowano.png',
715         'res/MKIDN.jpg',
716         'res/BN.png',
717         'res/wl-logo-white.png',
718     ]
719 #    annotation = 'Zadanie „Udostępnienie publikacji w formatach cyfrowych” w ramach Narodowego Programu Rozwoju Czytelnictwa. Dofinansowano ze środków Ministra Kultury, Dziedzictwa Narodowego i Sportu.'
720
721
722 COVER_CLASSES = {
723     'default': LogoWLCover,
724     'kmlu': KMLUCover,
725     'mpw': MPWCover,
726     'atrium': AtriumCover,
727     'bn': BNCover,
728 }
729
730
731 def make_cover(book_info, *args, **kwargs):
732     if 'cover_class' in kwargs:
733         cover_class_name = kwargs.pop('cover_class')
734     else:
735         cover_class_name = book_info.cover_class
736     cover_class = COVER_CLASSES[cover_class_name]
737     return cover_class(book_info, *args, **kwargs)