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