Merge remote-tracking branch 'upstream/master'
[librarian.git] / 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 import re
7 from PIL import Image, ImageFont, ImageDraw, ImageFilter, ImageEnhance
8 from StringIO import StringIO
9 from librarian import get_resource, OutputFile, URLOpener
10
11
12 class Metric(object):
13     """Gets metrics from an object, scaling it by a factor."""
14     def __init__(self, obj, scale):
15         self._obj = obj
16         self._scale = float(scale)
17
18     def __getattr__(self, name):
19         src = getattr(self._obj, name)
20         if src and self._scale:
21             src = type(src)(self._scale * src)
22         return src
23
24
25 class TextBox(object):
26     """Creates an Image with a series of centered strings."""
27
28     SHADOW_X = 3
29     SHADOW_Y = 3
30     SHADOW_BLUR = 3
31
32     def __init__(self, max_width, max_height, padding_x=None, padding_y=None):
33         if padding_x is None:
34             padding_x = self.SHADOW_X + self.SHADOW_BLUR
35         if padding_y is None:
36             padding_y = self.SHADOW_Y + self.SHADOW_BLUR
37
38         self.max_width = max_width
39         self.max_text_width = max_width - 2 * padding_x
40         self.padding_y = padding_y
41         self.height = padding_y
42         self.img = Image.new('RGBA', (max_width, max_height))
43         self.draw = ImageDraw.Draw(self.img)
44         self.shadow_img = None
45         self.shadow_draw = None
46
47     def skip(self, height):
48         """Skips some vertical space."""
49         self.height += height
50
51     def text(self, text, color='#000', font=None, line_height=20,
52              shadow_color=None):
53         """Writes some centered text."""
54         text = re.sub(r'\s+', ' ', text)
55         if shadow_color:
56             if not self.shadow_img:
57                 self.shadow_img = Image.new('RGBA', self.img.size)
58                 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
59         while text:
60             line = text
61             line_width = self.draw.textsize(line, font=font)[0]
62             while line_width > self.max_text_width:
63                 parts = line.rsplit(' ', 1)
64                 if len(parts) == 1:
65                     line_width = self.max_text_width
66                     break
67                 line = parts[0]
68                 line_width = self.draw.textsize(line, font=font)[0]
69             line = line.strip() + ' '
70
71             pos_x = (self.max_width - line_width) / 2
72
73             if shadow_color:
74                 self.shadow_draw.text(
75                         (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
76                         line, font=font, fill=shadow_color
77                 )
78
79             self.draw.text((pos_x, self.height), line, font=font, fill=color)
80             self.height += line_height
81             # go to next line
82             text = text[len(line):]
83
84     def image(self):
85         """Creates the actual Image object."""
86         image = Image.new('RGBA', (self.max_width,
87                                    self.height + self.padding_y))
88         if self.shadow_img:
89             shadow = self.shadow_img.filter(ImageFilter.BLUR)
90             image.paste(shadow, (0, 0), shadow)
91             image.paste(self.img, (0, 0), self.img)
92         else:
93             image.paste(self.img, (0, 0))
94         return image
95
96
97 class Cover(object):
98     """Abstract base class for cover images generator."""
99     width = 600
100     height = 800
101     background_color = '#fff'
102     background_img = None
103
104     author_top = 100
105     author_margin_left = 20
106     author_margin_right = 20
107     author_lineskip = 40
108     author_color = '#000'
109     author_shadow = None
110     author_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
111     author_font_size = 30
112
113     title_top = 100
114     title_margin_left = 20
115     title_margin_right = 20
116     title_lineskip = 54
117     title_color = '#000'
118     title_shadow = None
119     title_font_ttf = get_resource('fonts/DejaVuSerif.ttf')
120     title_font_size = 40
121
122     logo_bottom = None
123     logo_width = None
124     uses_dc_cover = False
125
126     format = 'JPEG'
127     scale = 1
128     scale_after = 1
129
130     exts = {
131         'JPEG': 'jpg',
132         'PNG': 'png',
133         }
134
135     mime_types = {
136         'JPEG': 'image/jpeg',
137         'PNG': 'image/png',
138         }
139
140     def __init__(self, book_info, format=None, width=None, height=None):
141         self.author = ", ".join(auth.readable() for auth in book_info.authors)
142         self.title = book_info.title
143         if format is not None:
144             self.format = format
145         scale = max(float(width or 0) / self.width, float(height or 0) / self.height)
146         if scale >= 1:
147             self.scale = scale
148         elif scale:
149             self.scale_after = scale
150
151     def pretty_author(self):
152         """Allows for decorating author's name."""
153         return self.author
154
155     def pretty_title(self):
156         """Allows for decorating title."""
157         return self.title
158
159     def image(self):
160         metr = Metric(self, self.scale)
161         img = Image.new('RGB', (metr.width, metr.height), self.background_color)
162
163         if self.background_img:
164             background = Image.open(self.background_img)
165             img.paste(background, None, background)
166             del background
167
168         # WL logo
169         if metr.logo_width:
170             logo = Image.open(get_resource('res/wl-logo.png'))
171             logo = logo.resize((metr.logo_width, logo.size[1] * metr.logo_width / logo.size[0]))
172             img.paste(logo, ((metr.width - metr.logo_width) / 2, img.size[1] - logo.size[1] - metr.logo_bottom))
173
174         top = metr.author_top
175         tbox = TextBox(
176             metr.width - metr.author_margin_left - metr.author_margin_right,
177             metr.height - top,
178             )
179             
180         author_font = ImageFont.truetype(
181             self.author_font_ttf, metr.author_font_size)
182         tbox.text(self.pretty_author(), self.author_color, author_font,
183             metr.author_lineskip, self.author_shadow)
184         text_img = tbox.image()
185         img.paste(text_img, (metr.author_margin_left, top), text_img)
186
187         top += text_img.size[1] + metr.title_top
188         tbox = TextBox(
189             metr.width - metr.title_margin_left - metr.title_margin_right,
190             metr.height - top,
191             )
192         title_font = ImageFont.truetype(
193             self.title_font_ttf, metr.title_font_size)
194         tbox.text(self.pretty_title(), self.title_color, title_font,
195             metr.title_lineskip, self.title_shadow)
196         text_img = tbox.image()
197         img.paste(text_img, (metr.title_margin_left, top), text_img)
198
199         return img
200
201     def final_image(self):
202         img = self.image()
203         if self.scale_after != 1:
204             img = img.resize((
205                     int(round(img.size[0] * self.scale_after)),
206                     int(round(img.size[1] * self.scale_after))),
207                 Image.ANTIALIAS)
208         return img
209
210     def mime_type(self):
211         return self.mime_types[self.format]
212
213     def ext(self):
214         return self.exts[self.format]
215
216     def save(self, *args, **kwargs):
217         default_kwargs = {
218                 'format': self.format,
219                 'quality': 95,
220         }
221         default_kwargs.update(kwargs)
222         return self.final_image().save(*args, **default_kwargs)
223
224     def output_file(self, *args, **kwargs):
225         imgstr = StringIO()
226         self.save(imgstr, *args, **kwargs)
227         return OutputFile.from_string(imgstr.getvalue())
228
229
230 class WLCover(Cover):
231     """Wolne Lektury cover without logos."""
232     width = 600
233     height = 833
234     uses_dc_cover = True
235     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
236     author_font_size = 20
237     author_lineskip = 30
238     title_font_ttf = get_resource('fonts/DejaVuSerif-Bold.ttf')
239     title_font_size = 30
240     title_lineskip = 40
241     title_box_width = 350
242     
243     box_top_margin = 100
244     box_bottom_margin = 100
245     box_padding_y = 20
246     box_above_line = 10
247     box_below_line = 15
248     box_line_left = 75
249     box_line_right = 275
250     box_line_width = 2
251
252     logo_top = 15
253     logo_width = 140
254
255     bar_width = 35
256     bar_color = '#000'
257     box_position = 'middle'
258     background_color = '#444'
259     author_color = '#444'
260     background_img = get_resource('res/cover.png')
261     format = 'JPEG'
262
263     epoch_colors = {
264         u'Starożytność': '#9e3610',
265         u'Średniowiecze': '#564c09',
266         u'Renesans': '#8ca629',
267         u'Barok': '#a6820a',
268         u'Oświecenie': '#f2802e',
269         u'Romantyzm': '#db4b16',
270         u'Pozytywizm': '#961060',
271         u'Modernizm': '#7784e0',
272         u'Dwudziestolecie międzywojenne': '#3044cf',
273         u'Współczesność': '#06393d',
274     }
275
276     kind_box_position = {
277         u'Liryka': 'top',
278         u'Epika': 'bottom',
279     }
280
281     def __init__(self, book_info, format=None, width=None, height=None):
282         super(WLCover, self).__init__(book_info, format=format, width=width, height=height)
283         # Set box position.
284         self.box_position = book_info.cover_box_position or \
285             self.kind_box_position.get(book_info.kind, self.box_position)
286         # Set bar color.
287         if book_info.cover_bar_color == 'none':
288             self.bar_width = 0
289         else:
290             self.bar_color = book_info.cover_bar_color or \
291                 self.epoch_colors.get(book_info.epoch, self.bar_color)
292         # Set title color.
293         self.title_color = self.epoch_colors.get(book_info.epoch, self.title_color)
294
295         if book_info.cover_url:
296             url = book_info.cover_url
297             bg_src = None
298             if bg_src is None:
299                 bg_src = URLOpener().open(url)
300             self.background_img = StringIO(bg_src.read())
301             bg_src.close()
302
303     def pretty_author(self):
304         return self.author.upper()
305
306     def add_box(self, img):
307         if self.box_position == 'none':
308             return img
309
310         metr = Metric(self, self.scale)
311
312         # Write author name.
313         box = TextBox(metr.title_box_width, metr.height, padding_y=metr.box_padding_y)
314         author_font = ImageFont.truetype(
315             self.author_font_ttf, metr.author_font_size)
316         box.text(self.pretty_author(),
317                  font=author_font,
318                  line_height=metr.author_lineskip,
319                  color=self.author_color,
320                  shadow_color=self.author_shadow,
321                 )
322
323         box.skip(metr.box_above_line)
324         box.draw.line((metr.box_line_left, box.height, metr.box_line_right, box.height),
325                 fill=self.author_color, width=metr.box_line_width)
326         box.skip(metr.box_below_line)
327
328         # Write title.
329         title_font = ImageFont.truetype(
330             self.title_font_ttf, metr.title_font_size)
331         box.text(self.pretty_title(),
332                  line_height=metr.title_lineskip,
333                  font=title_font,
334                  color=self.title_color,
335                  shadow_color=self.title_shadow,
336                 )
337
338         box_img = box.image()
339
340         # Find box position.
341         if self.box_position == 'top':
342             box_top = metr.box_top_margin
343         elif self.box_position == 'bottom':
344             box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
345         else:   # Middle.
346             box_top = (metr.height - box_img.size[1]) / 2
347
348         box_left = metr.bar_width + (metr.width - metr.bar_width -
349                         box_img.size[0]) / 2
350
351         # Draw the white box.
352         ImageDraw.Draw(img).rectangle((box_left, box_top,
353             box_left + box_img.size[0], box_top + box_img.size[1]),
354             fill='#fff')
355         # Paste the contents into the white box.
356         img.paste(box_img, (box_left, box_top), box_img)
357         return img
358
359     def image(self):
360         metr = Metric(self, self.scale)
361         img = Image.new('RGB', (metr.width, metr.height), self.background_color)
362         draw = ImageDraw.Draw(img)
363
364         draw.rectangle((0, 0, metr.bar_width, metr.height), fill=self.bar_color)
365
366         if self.background_img:
367             src = Image.open(self.background_img)
368             trg_size = (metr.width - metr.bar_width, metr.height)
369             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
370                 resized = (
371                     trg_size[0],
372                     src.size[1] * trg_size[0] / src.size[0]
373                 )
374                 cut = (resized[1] - trg_size[1]) / 2
375                 src = src.resize(resized, Image.ANTIALIAS)
376                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
377             else:
378                 resized = (
379                     src.size[0] * trg_size[1] / src.size[1],
380                     trg_size[1],
381                 )
382                 cut = (resized[0] - trg_size[0]) / 2
383                 src = src.resize(resized, Image.ANTIALIAS)
384                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
385
386             img.paste(src, (metr.bar_width, 0))
387             del src
388
389         img = self.add_box(img)
390
391         return img
392
393
394 class LogoWLCover(WLCover):
395     gradient_height = 90
396     gradient_logo_height = 60
397     gradient_logo_margin_right = 30
398     gradient_logo_spacing = 40
399     gradient_color = '#000'
400     gradient_opacity = .6
401     gradient_logos = [
402         'res/wl-logo-white.png',
403         'res/fnp-logo-white.png',
404     ]
405
406     def image(self):
407         img = super(LogoWLCover, self).image()
408         metr = Metric(self, self.scale)
409         gradient = Image.new('RGBA', (metr.width - metr.bar_width, metr.gradient_height), self.gradient_color)
410         gradient_mask = Image.new('L', (metr.width - metr.bar_width, metr.gradient_height))
411         draw = ImageDraw.Draw(gradient_mask)
412         for line in range(0, metr.gradient_height):
413             draw.line((0, line, metr.width - metr.bar_width, line), fill=int(255 * self.gradient_opacity * line / metr.gradient_height))
414         img.paste(gradient, 
415             (metr.bar_width, metr.height - metr.gradient_height), mask=gradient_mask)
416
417         cursor = metr.width - metr.gradient_logo_margin_right
418         logo_top = metr.height - metr.gradient_height / 2  - metr.gradient_logo_height / 2
419         for logo_path in self.gradient_logos[::-1]:
420             logo = Image.open(get_resource(logo_path))
421             logo = logo.resize(
422                 (logo.size[0] * metr.gradient_logo_height / logo.size[1], metr.gradient_logo_height),
423                 Image.ANTIALIAS)
424             cursor -= logo.size[0]
425             img.paste(logo, (cursor, logo_top), mask=logo)
426             cursor -= metr.gradient_logo_spacing
427
428         return img
429
430
431 class EbookpointCover(LogoWLCover):
432     gradient_logo_height = 58
433     gradient_logo_spacing = 25
434     gradient_logos = [
435         'res/ebookpoint-logo-white.png',
436         'res/wl-logo-white.png',
437         'res/fnp-logo-white.png',
438     ]
439
440
441 class VirtualoCover(Cover):
442     width = 600
443     height = 730
444     author_top = 73
445     title_top = 73
446     logo_bottom = 25
447     logo_width = 250
448
449
450 class PrestigioCover(Cover):
451     width = 580
452     height = 783
453     background_img = get_resource('res/cover-prestigio.png')
454
455     author_top = 446
456     author_margin_left = 118
457     author_margin_right = 62
458     author_lineskip = 60
459     author_color = '#fff'
460     author_shadow = '#000'
461     author_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
462     author_font_size = 50
463
464     title_top = 0
465     title_margin_left = 118
466     title_margin_right = 62
467     title_lineskip = 60
468     title_color = '#fff'
469     title_shadow = '#000'
470     title_font_ttf = get_resource('fonts/JunicodeWL-Italic.ttf')
471     title_font_size = 50
472
473     def pretty_title(self):
474         return u"„%s”" % self.title
475
476
477 class BookotekaCover(Cover):
478     width = 2140
479     height = 2733
480     background_img = get_resource('res/cover-bookoteka.png')
481
482     author_top = 480
483     author_margin_left = 307
484     author_margin_right = 233
485     author_lineskip = 156
486     author_color = '#d9d919'
487     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
488     author_font_size = 130
489
490     title_top = 400
491     title_margin_left = 307
492     title_margin_right = 233
493     title_lineskip = 168
494     title_color = '#d9d919'
495     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
496     title_font_size = 140
497
498     format = 'PNG'
499
500
501 class GandalfCover(Cover):
502     width = 600
503     height = 730
504     background_img = get_resource('res/cover-gandalf.png')
505     author_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
506     author_font_size = 30
507     title_font_ttf = get_resource('fonts/JunicodeWL-Regular.ttf')
508     title_font_size = 40
509     logo_bottom = 25
510     logo_width = 250
511     format = 'PNG'
512
513
514 DefaultEbookCover = LogoWLCover
515