#2044: handle weird whitespace for covers
[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 import Image, ImageFont, ImageDraw, ImageFilter
8 from librarian import get_resource
9
10
11 class TextBox(object):
12     """Creates an Image with a series of centered strings."""
13
14     SHADOW_X = 3
15     SHADOW_Y = 3
16     SHADOW_BLUR = 3
17
18     def __init__(self, max_width, max_height, padding_x=None, padding_y=None):
19         if padding_x is None:
20             padding_x = self.SHADOW_X + self.SHADOW_BLUR
21         if padding_y is None:
22             padding_y = self.SHADOW_Y + self.SHADOW_BLUR
23
24         self.max_width = max_width
25         self.max_text_width = max_width - 2 * padding_x
26         self.padding_y = padding_y
27         self.height = padding_y
28         self.img = Image.new('RGBA', (max_width, max_height))
29         self.draw = ImageDraw.Draw(self.img)
30         self.shadow_img = None
31         self.shadow_draw = None
32
33     def skip(self, height):
34         """Skips some vertical space."""
35         self.height += height
36
37     def text(self, text, color='#000', font=None, line_height=20,
38              shadow_color=None):
39         """Writes some centered text."""
40         text = re.sub(r'\s+', ' ', text)
41         if shadow_color:
42             if not self.shadow_img:
43                 self.shadow_img = Image.new('RGBA', self.img.size)
44                 self.shadow_draw = ImageDraw.Draw(self.shadow_img)
45         while text:
46             line = text
47             line_width = self.draw.textsize(line, font=font)[0]
48             while line_width > self.max_text_width:
49                 parts = line.rsplit(' ', 1)
50                 if len(parts) == 1:
51                     line_width = self.max_text_width
52                     break
53                 line = parts[0]
54                 line_width = self.draw.textsize(line, font=font)[0]
55             line = line.strip() + ' '
56
57             pos_x = (self.max_width - line_width) / 2
58
59             if shadow_color:
60                 self.shadow_draw.text(
61                         (pos_x + self.SHADOW_X, self.height + self.SHADOW_Y),
62                         line, font=font, fill=shadow_color
63                 )
64
65             self.draw.text((pos_x, self.height), line, font=font, fill=color)
66             self.height += line_height
67             # go to next line
68             text = text[len(line):]
69
70     def image(self):
71         """Creates the actual Image object."""
72         image = Image.new('RGBA', (self.max_width,
73                                    self.height + self.padding_y))
74         if self.shadow_img:
75             shadow = self.shadow_img.filter(ImageFilter.BLUR)
76             image.paste(shadow, (0, 0), shadow)
77             image.paste(self.img, (0, 0), self.img)
78         else:
79             image.paste(self.img, (0, 0))
80         return image
81
82
83 class Cover(object):
84     """Abstract base class for cover images generator."""
85     width = 600
86     height = 800
87     background_color = '#fff'
88     background_img = None
89
90     author_top = 100
91     author_margin_left = 20
92     author_margin_right = 20
93     author_lineskip = 40
94     author_color = '#000'
95     author_shadow = None
96     author_font = None
97
98     title_top = 100
99     title_margin_left = 20
100     title_margin_right = 20
101     title_lineskip = 54
102     title_color = '#000'
103     title_shadow = None
104     title_font = None
105
106     logo_bottom = None
107     logo_width = None
108     uses_dc_cover = False
109
110     format = 'JPEG'
111
112     exts = {
113         'JPEG': 'jpg',
114         'PNG': 'png',
115         }
116
117     mime_types = {
118         'JPEG': 'image/jpeg',
119         'PNG': 'image/png',
120         }
121
122     def __init__(self, book_info):
123         self.author = ", ".join(auth.readable() for auth in book_info.authors)
124         self.title = book_info.title
125
126     def pretty_author(self):
127         """Allows for decorating author's name."""
128         return self.author
129
130     def pretty_title(self):
131         """Allows for decorating title."""
132         return self.title
133
134     def image(self):
135         img = Image.new('RGB', (self.width, self.height), self.background_color)
136
137         if self.background_img:
138             background = Image.open(self.background_img)
139             img.paste(background, None, background)
140             del background
141
142         # WL logo
143         if self.logo_width:
144             logo = Image.open(get_resource('res/wl-logo.png'))
145             logo = logo.resize((self.logo_width, logo.size[1] * self.logo_width / logo.size[0]))
146             img.paste(logo, ((self.width - self.logo_width) / 2, img.size[1] - logo.size[1] - self.logo_bottom))
147
148         top = self.author_top
149         tbox = TextBox(
150             self.width - self.author_margin_left - self.author_margin_right,
151             self.height - top,
152             )
153         author_font = self.author_font or ImageFont.truetype(
154             get_resource('fonts/DejaVuSerif.ttf'), 30)
155         tbox.text(self.pretty_author(), self.author_color, author_font,
156             self.author_lineskip, self.author_shadow)
157         text_img = tbox.image()
158         img.paste(text_img, (self.author_margin_left, top), text_img)
159
160         top += text_img.size[1] + self.title_top
161         tbox = TextBox(
162             self.width - self.title_margin_left - self.title_margin_right,
163             self.height - top,
164             )
165         title_font = self.author_font or ImageFont.truetype(
166             get_resource('fonts/DejaVuSerif.ttf'), 40)
167         tbox.text(self.pretty_title(), self.title_color, title_font,
168             self.title_lineskip, self.title_shadow)
169         text_img = tbox.image()
170         img.paste(text_img, (self.title_margin_left, top), text_img)
171
172         return img
173
174     def mime_type(self):
175         return self.mime_types[self.format]
176
177     def ext(self):
178         return self.exts[self.format]
179
180     def save(self, *args, **kwargs):
181         return self.image().save(format=self.format, *args, **kwargs)
182
183
184 class WLCover(Cover):
185     """Default Wolne Lektury cover generator."""
186     uses_dc_cover = True
187     author_font = ImageFont.truetype(
188         get_resource('fonts/JunicodeWL-Regular.ttf'), 20)
189     author_lineskip = 30
190     title_font = ImageFont.truetype(
191         get_resource('fonts/DejaVuSerif-Bold.ttf'), 30)
192     title_lineskip = 40
193     title_box_width = 350
194     bar_width = 35
195     background_color = '#444'
196     author_color = '#444'
197     default_background = get_resource('res/cover.png')
198     format = 'JPEG'
199
200     epoch_colors = {
201         u'Starożytność': '#9e3610',
202         u'Średniowiecze': '#564c09',
203         u'Renesans': '#8ca629',
204         u'Barok': '#a6820a',
205         u'Oświecenie': '#f2802e',
206         u'Romantyzm': '#db4b16',
207         u'Pozytywizm': '#961060',
208         u'Modernizm': '#7784e0',
209         u'Dwudziestolecie międzywojenne': '#3044cf',
210         u'Współczesność': '#06393d',
211     }
212
213     def __init__(self, book_info):
214         super(WLCover, self).__init__(book_info)
215         self.kind = book_info.kind
216         self.epoch = book_info.epoch
217         if book_info.cover_url:
218             from urllib2 import urlopen
219             from StringIO import StringIO
220
221             bg_src = urlopen(book_info.cover_url)
222             self.background_img = StringIO(bg_src.read())
223             bg_src.close()
224         else:
225             self.background_img = self.default_background
226
227     def pretty_author(self):
228         return self.author.upper()
229
230     def image(self):
231         img = Image.new('RGB', (self.width, self.height), self.background_color)
232         draw = ImageDraw.Draw(img)
233
234         if self.epoch in self.epoch_colors:
235             epoch_color = self.epoch_colors[self.epoch]
236         else:
237             epoch_color = '#000'
238         draw.rectangle((0, 0, self.bar_width, self.height), fill=epoch_color)
239
240         if self.background_img:
241             src = Image.open(self.background_img)
242             trg_size = (self.width - self.bar_width, self.height)
243             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
244                 resized = (
245                     trg_size[0],
246                     src.size[1] * trg_size[0] / src.size[0]
247                 )
248                 cut = (resized[1] - trg_size[1]) / 2
249                 src = src.resize(resized)
250                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
251             else:
252                 resized = (
253                     src.size[0] * trg_size[1] / src.size[1],
254                     trg_size[1],
255                 )
256                 cut = (resized[0] - trg_size[0]) / 2
257                 src = src.resize(resized)
258                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
259
260             img.paste(src, (self.bar_width, 0))
261             del src
262
263         box = TextBox(self.title_box_width, self.height, padding_y=20)
264         box.text(self.pretty_author(),
265                  font=self.author_font,
266                  line_height=self.author_lineskip,
267                  color=self.author_color,
268                  shadow_color=self.author_shadow,
269                 )
270
271         box.skip(10)
272         box.draw.line((75, box.height, 275, box.height),
273                 fill=self.author_color, width=2)
274         box.skip(15)
275
276         box.text(self.pretty_title(),
277                  line_height=self.title_lineskip,
278                  font=self.title_font,
279                  color=epoch_color,
280                  shadow_color=self.title_shadow,
281                 )
282         box_img = box.image()
283
284         if self.kind == 'Liryka':
285             # top
286             box_top = 100
287         elif self.kind == 'Epika':
288             # bottom
289             box_top = self.height - 100 - box_img.size[1]
290         else:
291             # center
292             box_top = (self.height - box_img.size[1]) / 2
293
294         box_left = self.bar_width + (self.width - self.bar_width -
295                         box_img.size[0]) / 2
296         draw.rectangle((box_left, box_top,
297             box_left + box_img.size[0], box_top + box_img.size[1]),
298             fill='#fff')
299         img.paste(box_img, (box_left, box_top), box_img)
300
301         return img
302
303
304
305 class VirtualoCover(Cover):
306     width = 600
307     height = 730
308     author_top = 73
309     title_top = 73
310     logo_bottom = 25
311     logo_width = 250
312
313
314 class PrestigioCover(Cover):
315     width = 580
316     height = 783
317     background_img = get_resource('res/cover-prestigio.png')
318
319     author_top = 446
320     author_margin_left = 118
321     author_margin_right = 62
322     author_lineskip = 60
323     author_color = '#fff'
324     author_shadow = '#000'
325     author_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Italic.ttf'), 50)
326
327     title_top = 0
328     title_margin_left = 118
329     title_margin_right = 62
330     title_lineskip = 60
331     title_color = '#fff'
332     title_shadow = '#000'
333     title_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Italic.ttf'), 50)
334
335     def pretty_title(self):
336         return u"„%s”" % self.title
337
338
339 class BookotekaCover(Cover):
340     width = 2140
341     height = 2733
342     background_img = get_resource('res/cover-bookoteka.png')
343
344     author_top = 480
345     author_margin_left = 307
346     author_margin_right = 233
347     author_lineskip = 156
348     author_color = '#d9d919'
349     author_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Regular.ttf'), 130)
350
351     title_top = 400
352     title_margin_left = 307
353     title_margin_right = 233
354     title_lineskip = 168
355     title_color = '#d9d919'
356     title_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Regular.ttf'), 140)
357
358     format = 'PNG'
359
360
361 class GandalfCover(Cover):
362     width = 600
363     height = 730
364     background_img = get_resource('res/cover-gandalf.png')
365     author_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Regular.ttf'), 30)
366     title_font = ImageFont.truetype(get_resource('fonts/JunicodeWL-Regular.ttf'), 40)
367     logo_bottom = 25
368     logo_width = 250
369     format = 'PNG'