Epub: only attach images referenced in the text.
[librarian.git] / librarian / cover.py
index d1b2cc0..95c5cdc 100644 (file)
@@ -3,9 +3,11 @@
 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
+from __future__ import unicode_literals
+
 import re
 import re
-from PIL import Image, ImageFont, ImageDraw, ImageFilter, ImageEnhance
-from StringIO import StringIO
+from PIL import Image, ImageFont, ImageDraw, ImageFilter
+from six import BytesIO
 from librarian import get_resource, OutputFile, URLOpener
 
 
 from librarian import get_resource, OutputFile, URLOpener
 
 
@@ -18,8 +20,9 @@ class Metric(object):
     def __getattr__(self, name):
         src = getattr(self._obj, name)
         if src and self._scale:
     def __getattr__(self, name):
         src = getattr(self._obj, name)
         if src and self._scale:
-            src = type(src)(self._scale * src)
-        return src
+            return type(src)(self._scale * src)
+        else:
+            return src
 
 
 class TextBox(object):
 
 
 class TextBox(object):
@@ -68,7 +71,7 @@ class TextBox(object):
                 line_width = self.draw.textsize(line, font=font)[0]
             line = line.strip() + ' '
 
                 line_width = self.draw.textsize(line, font=font)[0]
             line = line.strip() + ' '
 
-            pos_x = (self.max_width - line_width) / 2
+            pos_x = (self.max_width - line_width) // 2
 
             if shadow_color:
                 self.shadow_draw.text(
 
             if shadow_color:
                 self.shadow_draw.text(
@@ -142,6 +145,8 @@ class Cover(object):
         self.title = book_info.title
         if format is not None:
             self.format = format
         self.title = book_info.title
         if format is not None:
             self.format = format
+        if width and height:
+            self.height = int(round(height * self.width / width))
         scale = max(float(width or 0) / self.width, float(height or 0) / self.height)
         if scale >= 1:
             self.scale = scale
         scale = max(float(width or 0) / self.width, float(height or 0) / self.height)
         if scale >= 1:
             self.scale = scale
@@ -168,8 +173,8 @@ class Cover(object):
         # WL logo
         if metr.logo_width:
             logo = Image.open(get_resource('res/wl-logo.png'))
         # WL logo
         if metr.logo_width:
             logo = Image.open(get_resource('res/wl-logo.png'))
-            logo = logo.resize((metr.logo_width, logo.size[1] * metr.logo_width / logo.size[0]))
-            img.paste(logo, ((metr.width - metr.logo_width) / 2, img.size[1] - logo.size[1] - metr.logo_bottom))
+            logo = logo.resize((metr.logo_width, int(round(logo.size[1] * metr.logo_width / logo.size[0]))))
+            img.paste(logo, ((metr.width - metr.logo_width) // 2, img.size[1] - logo.size[1] - metr.logo_bottom))
 
         top = metr.author_top
         tbox = TextBox(
 
         top = metr.author_top
         tbox = TextBox(
@@ -179,8 +184,7 @@ class Cover(object):
             
         author_font = ImageFont.truetype(
             self.author_font_ttf, metr.author_font_size)
             
         author_font = ImageFont.truetype(
             self.author_font_ttf, metr.author_font_size)
-        tbox.text(self.pretty_author(), self.author_color, author_font,
-            metr.author_lineskip, self.author_shadow)
+        tbox.text(self.pretty_author(), self.author_color, author_font, metr.author_lineskip, self.author_shadow)
         text_img = tbox.image()
         img.paste(text_img, (metr.author_margin_left, top), text_img)
 
         text_img = tbox.image()
         img.paste(text_img, (metr.author_margin_left, top), text_img)
 
@@ -191,8 +195,7 @@ class Cover(object):
             )
         title_font = ImageFont.truetype(
             self.title_font_ttf, metr.title_font_size)
             )
         title_font = ImageFont.truetype(
             self.title_font_ttf, metr.title_font_size)
-        tbox.text(self.pretty_title(), self.title_color, title_font,
-            metr.title_lineskip, self.title_shadow)
+        tbox.text(self.pretty_title(), self.title_color, title_font, metr.title_lineskip, self.title_shadow)
         text_img = tbox.image()
         img.paste(text_img, (metr.title_margin_left, top), text_img)
 
         text_img = tbox.image()
         img.paste(text_img, (metr.title_margin_left, top), text_img)
 
@@ -214,12 +217,17 @@ class Cover(object):
         return self.exts[self.format]
 
     def save(self, *args, **kwargs):
         return self.exts[self.format]
 
     def save(self, *args, **kwargs):
-        return self.final_image().save(format=self.format, quality=95, *args, **kwargs)
+        default_kwargs = {
+                'format': self.format,
+                'quality': 95,
+        }
+        default_kwargs.update(kwargs)
+        return self.final_image().save(*args, **default_kwargs)
 
     def output_file(self, *args, **kwargs):
 
     def output_file(self, *args, **kwargs):
-        imgstr = StringIO()
+        imgstr = BytesIO()
         self.save(imgstr, *args, **kwargs)
         self.save(imgstr, *args, **kwargs)
-        return OutputFile.from_string(imgstr.getvalue())
+        return OutputFile.from_bytes(imgstr.getvalue())
 
 
 class WLCover(Cover):
 
 
 class WLCover(Cover):
@@ -234,7 +242,7 @@ class WLCover(Cover):
     title_font_size = 30
     title_lineskip = 40
     title_box_width = 350
     title_font_size = 30
     title_lineskip = 40
     title_box_width = 350
-    
+
     box_top_margin = 100
     box_bottom_margin = 100
     box_padding_y = 20
     box_top_margin = 100
     box_bottom_margin = 100
     box_padding_y = 20
@@ -248,9 +256,11 @@ class WLCover(Cover):
     logo_width = 140
 
     bar_width = 35
     logo_width = 140
 
     bar_width = 35
+    bar_color = '#000'
+    box_position = 'middle'
     background_color = '#444'
     author_color = '#444'
     background_color = '#444'
     author_color = '#444'
-    default_background = get_resource('res/cover.png')
+    background_img = get_resource('res/cover.png')
     format = 'JPEG'
 
     epoch_colors = {
     format = 'JPEG'
 
     epoch_colors = {
@@ -266,34 +276,114 @@ class WLCover(Cover):
         u'Współczesność': '#06393d',
     }
 
         u'Współczesność': '#06393d',
     }
 
-    def __init__(self, book_info, format=None, width=None, height=None, with_logo=False):
+    kind_box_position = {
+        u'Liryka': 'top',
+        u'Epika': 'bottom',
+    }
+
+    def __init__(self, book_info, format=None, width=None, height=None, bleed=0):
         super(WLCover, self).__init__(book_info, format=format, width=width, height=height)
         super(WLCover, self).__init__(book_info, format=format, width=width, height=height)
-        self.kind = book_info.kind
-        self.epoch = book_info.epoch
-        self.with_logo = with_logo
+        # Set box position.
+        self.box_position = book_info.cover_box_position or \
+            self.kind_box_position.get(book_info.kind, self.box_position)
+        # Set bar color.
+        if book_info.cover_bar_color == 'none':
+            self.bar_width = 0
+        else:
+            self.bar_color = book_info.cover_bar_color or \
+                self.epoch_colors.get(book_info.epoch, self.bar_color)
+        # Set title color.
+        self.title_color = self.epoch_colors.get(book_info.epoch, self.title_color)
+
+        self.bleed = bleed
+        self.box_top_margin += bleed
+        self.box_bottom_margin += bleed
+        self.bar_width += bleed
+
         if book_info.cover_url:
             url = book_info.cover_url
             bg_src = None
             if bg_src is None:
                 bg_src = URLOpener().open(url)
         if book_info.cover_url:
             url = book_info.cover_url
             bg_src = None
             if bg_src is None:
                 bg_src = URLOpener().open(url)
-            self.background_img = StringIO(bg_src.read())
+            self.background_img = BytesIO(bg_src.read())
             bg_src.close()
             bg_src.close()
-        else:
-            self.background_img = self.default_background
 
     def pretty_author(self):
         return self.author.upper()
 
 
     def pretty_author(self):
         return self.author.upper()
 
+    def add_box(self, img):
+        if self.box_position == 'none':
+            return img
+
+        metr = Metric(self, self.scale)
+
+        # Write author name.
+        box = TextBox(metr.title_box_width, metr.height, padding_y=metr.box_padding_y)
+        author_font = ImageFont.truetype(
+            self.author_font_ttf, metr.author_font_size)
+        box.text(self.pretty_author(),
+                 font=author_font,
+                 line_height=metr.author_lineskip,
+                 color=self.author_color,
+                 shadow_color=self.author_shadow)
+
+        box.skip(metr.box_above_line)
+        box.draw.line((metr.box_line_left, box.height, metr.box_line_right, box.height),
+                      fill=self.author_color, width=metr.box_line_width)
+        box.skip(metr.box_below_line)
+
+        # Write title.
+        title_font = ImageFont.truetype(
+            self.title_font_ttf, metr.title_font_size)
+        box.text(self.pretty_title(),
+                 line_height=metr.title_lineskip,
+                 font=title_font,
+                 color=self.title_color,
+                 shadow_color=self.title_shadow)
+
+        box_img = box.image()
+
+        # Find box position.
+        if self.box_position == 'top':
+            box_top = metr.box_top_margin
+        elif self.box_position == 'bottom':
+            box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
+        else:   # Middle.
+            box_top = (metr.height - box_img.size[1]) // 2
+
+        box_left = metr.bar_width + (metr.width - metr.bar_width - box_img.size[0]) // 2
+
+        # Draw the white box.
+        ImageDraw.Draw(img).rectangle(
+            (box_left, box_top, box_left + box_img.size[0], box_top + box_img.size[1]), fill='#fff')
+        # Paste the contents into the white box.
+        img.paste(box_img, (box_left, box_top), box_img)
+        return img
+
+    def add_cut_lines(self, img):
+        line_ratio = 0.5
+        if self.bleed == 0:
+            return img
+        metr = Metric(self, self.scale)
+        draw = ImageDraw.Draw(img)
+        for corner_x, corner_y in ((0, 0), (metr.width, 0), (0, metr.height), (metr.width, metr.height)):
+            dir_x = 1 if corner_x == 0 else -1
+            dir_y = 1 if corner_y == 0 else -1
+            for offset in (-1, 0, 1):
+                draw.line((corner_x, corner_y + dir_y * metr.bleed + offset,
+                           corner_x + dir_x * metr.bleed * line_ratio, corner_y + dir_y * metr.bleed + offset),
+                          fill='black' if offset == 0 else 'white', width=1)
+                draw.line((corner_x + dir_x * metr.bleed + offset, corner_y,
+                           corner_x + dir_x * metr.bleed + offset, corner_y + dir_y * metr.bleed * line_ratio),
+                          fill='black' if offset == 0 else 'white', width=1)
+        return img
+
     def image(self):
         metr = Metric(self, self.scale)
         img = Image.new('RGB', (metr.width, metr.height), self.background_color)
         draw = ImageDraw.Draw(img)
 
     def image(self):
         metr = Metric(self, self.scale)
         img = Image.new('RGB', (metr.width, metr.height), self.background_color)
         draw = ImageDraw.Draw(img)
 
-        if self.epoch in self.epoch_colors:
-            epoch_color = self.epoch_colors[self.epoch]
-        else:
-            epoch_color = '#000'
-        draw.rectangle((0, 0, metr.bar_width, metr.height), fill=epoch_color)
+        draw.rectangle((0, 0, metr.bar_width, metr.height), fill=self.bar_color)
 
         if self.background_img:
             src = Image.open(self.background_img)
 
         if self.background_img:
             src = Image.open(self.background_img)
@@ -301,79 +391,32 @@ class WLCover(Cover):
             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
                 resized = (
                     trg_size[0],
             if src.size[0] * trg_size[1] < src.size[1] * trg_size[0]:
                 resized = (
                     trg_size[0],
-                    src.size[1] * trg_size[0] / src.size[0]
+                    int(round(src.size[1] * trg_size[0] / src.size[0]))
                 )
                 )
-                cut = (resized[1] - trg_size[1]) / 2
+                cut = (resized[1] - trg_size[1]) // 2
                 src = src.resize(resized, Image.ANTIALIAS)
                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
             else:
                 resized = (
                 src = src.resize(resized, Image.ANTIALIAS)
                 src = src.crop((0, cut, src.size[0], src.size[1] - cut))
             else:
                 resized = (
-                    src.size[0] * trg_size[1] / src.size[1],
+                    int(round(src.size[0] * trg_size[1] / src.size[1])),
                     trg_size[1],
                 )
                     trg_size[1],
                 )
-                cut = (resized[0] - trg_size[0]) / 2
+                cut = (resized[0] - trg_size[0]) // 2
                 src = src.resize(resized, Image.ANTIALIAS)
                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
 
             img.paste(src, (metr.bar_width, 0))
             del src
 
                 src = src.resize(resized, Image.ANTIALIAS)
                 src = src.crop((cut, 0, src.size[0] - cut, src.size[1]))
 
             img.paste(src, (metr.bar_width, 0))
             del src
 
-        box = TextBox(metr.title_box_width, metr.height, padding_y=metr.box_padding_y)
-        author_font = ImageFont.truetype(
-            self.author_font_ttf, metr.author_font_size)
-        box.text(self.pretty_author(),
-                 font=author_font,
-                 line_height=metr.author_lineskip,
-                 color=self.author_color,
-                 shadow_color=self.author_shadow,
-                )
-
-        box.skip(metr.box_above_line)
-        box.draw.line((metr.box_line_left, box.height, metr.box_line_right, box.height),
-                fill=self.author_color, width=metr.box_line_width)
-        box.skip(metr.box_below_line)
-
-        title_font = ImageFont.truetype(
-            self.title_font_ttf, metr.title_font_size)
-        box.text(self.pretty_title(),
-                 line_height=metr.title_lineskip,
-                 font=title_font,
-                 color=epoch_color,
-                 shadow_color=self.title_shadow,
-                )
+        img = self.add_box(img)
 
 
-        if self.with_logo:
-            logo = Image.open(get_resource('res/wl-logo-mono.png'))
-            logo = logo.resize((metr.logo_width, logo.size[1] * metr.logo_width / logo.size[0]), Image.ANTIALIAS)
-            alpha = logo.split()[3]
-            alpha = ImageEnhance.Brightness(alpha).enhance(.75)
-            logo.putalpha(alpha)
-            box.skip(metr.logo_top + logo.size[1])
+        # img = self.add_cut_lines(img)
 
 
-        box_img = box.image()
-
-        if self.kind == 'Liryka':
-            # top
-            box_top = metr.box_top_margin
-        elif self.kind == 'Epika':
-            # bottom
-            box_top = metr.height - metr.box_bottom_margin - box_img.size[1]
-        else:
-            # center
-            box_top = (metr.height - box_img.size[1]) / 2
-
-        box_left = metr.bar_width + (metr.width - metr.bar_width -
-                        box_img.size[0]) / 2
-        draw.rectangle((box_left, box_top,
-            box_left + box_img.size[0], box_top + box_img.size[1]),
-            fill='#fff')
-        img.paste(box_img, (box_left, box_top), box_img)
+        return img
 
 
-        if self.with_logo:
-            img.paste(logo, 
-                (box_left + (box_img.size[0] - logo.size[0]) / 2,
-                    box_top + box_img.size[1] - metr.box_padding_y - logo.size[1]), mask=logo)
 
 
+class WLNoBoxCover(WLCover):
+    def add_box(self, img):
         return img
 
 
         return img
 
 
@@ -389,6 +432,16 @@ class LogoWLCover(WLCover):
         'res/fnp-logo-white.png',
     ]
 
         'res/fnp-logo-white.png',
     ]
 
+    def __init__(self, book_info, *args, **kwargs):
+        super(LogoWLCover, self).__init__(book_info, *args, **kwargs)
+        self.gradient_height += self.bleed
+        self.gradient_logo_margin_right += self.bleed
+
+        self.additional_cover_logos = [
+            BytesIO(URLOpener().open(cover_logo_url).read())
+            for cover_logo_url in book_info.cover_logo_urls
+        ]
+
     def image(self):
         img = super(LogoWLCover, self).image()
         metr = Metric(self, self.scale)
     def image(self):
         img = super(LogoWLCover, self).image()
         metr = Metric(self, self.scale)
@@ -396,20 +449,35 @@ class LogoWLCover(WLCover):
         gradient_mask = Image.new('L', (metr.width - metr.bar_width, metr.gradient_height))
         draw = ImageDraw.Draw(gradient_mask)
         for line in range(0, metr.gradient_height):
         gradient_mask = Image.new('L', (metr.width - metr.bar_width, metr.gradient_height))
         draw = ImageDraw.Draw(gradient_mask)
         for line in range(0, metr.gradient_height):
-            draw.line((0, line, metr.width - metr.bar_width, line), fill=int(255 * self.gradient_opacity * line / metr.gradient_height))
-        img.paste(gradient, 
-            (metr.bar_width, metr.height - metr.gradient_height), mask=gradient_mask)
+            draw.line(
+                (0, line, metr.width - metr.bar_width, line),
+                fill=int(255 * self.gradient_opacity * line / metr.gradient_height))
+        img.paste(gradient, (metr.bar_width, metr.height - metr.gradient_height), mask=gradient_mask)
 
         cursor = metr.width - metr.gradient_logo_margin_right
 
         cursor = metr.width - metr.gradient_logo_margin_right
-        logo_top = metr.height - metr.gradient_height / 2  - metr.gradient_logo_height / 2
-        for logo_path in self.gradient_logos[::-1]:
-            logo = Image.open(get_resource(logo_path))
+        logo_top = int(metr.height - metr.gradient_height / 2 - metr.gradient_logo_height / 2 - metr.bleed / 2)
+
+        logos = [get_resource(logo_path) for logo_path in self.gradient_logos[::-1]]
+        logos = logos + self.additional_cover_logos
+        logos = [Image.open(logo_bytes).convert('RGBA') for logo_bytes in logos]
+
+        # See if logos fit into the gradient. If not, scale down accordingly.
+        space_for_logos = metr.width - metr.bar_width - 2 * metr.gradient_logo_margin_right
+        widths = [logo.size[0] * metr.gradient_logo_height / logo.size[1] for logo in logos]
+        taken_space = sum(widths) + (len(logos) - 1) * (metr.gradient_logo_spacing)
+        logo_scale = space_for_logos / taken_space if taken_space > space_for_logos else 1
+        logo_top += int(metr.gradient_logo_height * (1 - logo_scale) / 2)
+
+        for i, logo in enumerate(logos):
             logo = logo.resize(
             logo = logo.resize(
-                (logo.size[0] * metr.gradient_logo_height / logo.size[1], metr.gradient_logo_height),
+                (
+                    int(round(widths[i] * logo_scale)),
+                    int(round(metr.gradient_logo_height * logo_scale))
+                ),
                 Image.ANTIALIAS)
             cursor -= logo.size[0]
             img.paste(logo, (cursor, logo_top), mask=logo)
                 Image.ANTIALIAS)
             cursor -= logo.size[0]
             img.paste(logo, (cursor, logo_top), mask=logo)
-            cursor -= metr.gradient_logo_spacing
+            cursor -= int(round(metr.gradient_logo_spacing * logo_scale))
 
         return img
 
 
         return img
 
@@ -497,5 +565,48 @@ class GandalfCover(Cover):
     format = 'PNG'
 
 
     format = 'PNG'
 
 
-DefaultEbookCover = LogoWLCover
+class KMLUCover(LogoWLCover):
+    gradient_logo_height = 58
+    gradient_logo_spacing = 25
+    gradient_logos = [
+        'res/kmlu-logo-white.png',
+        'res/wl-logo-white.png',
+        'res/fnp-logo-white.png',
+    ]
+
+
+class MPWCover(LogoWLCover):
+    gradient_logo_height = 58
+    gradient_logo_spacing = 25
+    gradient_logos = [
+        'res/mpw-logo-white.png',
+        'res/wl-logo-white.png',
+        'res/fnp-logo-white.png',
+    ]
+
+
+class AtriumCover(LogoWLCover):
+    gradient_logo_height = 58
+    gradient_logo_spacing = 25
+    gradient_logos = [
+        'res/atrium-logo.png',
+        'res/wl-logo-white.png',
+        'res/fnp-logo-white.png',
+    ]
+
+
+COVER_CLASSES = {
+    'default': LogoWLCover,
+    'kmlu': KMLUCover,
+    'mpw': MPWCover,
+    'atrium': AtriumCover,
+}
+
 
 
+def make_cover(book_info, *args, **kwargs):
+    if 'cover_class' in kwargs:
+        cover_class_name = kwargs.pop('cover_class')
+    else:
+        cover_class_name = book_info.cover_class
+    cover_class = COVER_CLASSES[cover_class_name]
+    return cover_class(book_info, *args, **kwargs)