Drop lots of legacy code. Support Python 3.7-3.11.
[librarian.git] / src / librarian / elements / figures / ilustr.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import io
5 import urllib.parse
6 import urllib.request
7 from PIL import Image
8 from ..base import WLElement
9
10
11 class Ilustr(WLElement):
12     SHOULD_HAVE_ID = True
13
14     EPUB_TAG = HTML_TAG = 'img'
15
16     def get_html_attr(self, builder):
17         ## TODO: thumbnail.
18
19         url = urllib.parse.urljoin(
20             builder.base_url,
21             self.get('src')
22         )
23         
24         imgfile = urllib.request.urlopen(url)
25         img = Image.open(imgfile)
26         th_format, ext, media_type = {
27             'GIF': ('GIF', 'gif', 'image/gif'),
28             'PNG': ('PNG', 'png', 'image/png'),
29         }.get(img.format, ('JPEG', 'jpg', 'image/jpeg'))
30
31         width = 1200
32         if img.size[0] < width:
33             th = img
34         else:
35             th = img.resize((width, round(width * img.size[1] / img.size[0])))
36
37         buffer = io.BytesIO()
38         th.save(buffer, format=th_format)
39         imgfile.close()
40         file_name = 'image%d.%s' % (
41             builder.assign_image_number(),
42             ext
43         )
44
45         builder.add_file(
46             content=buffer.getvalue(),
47             file_name=file_name,
48             media_type=media_type,
49         )
50         
51         return {
52             'src': file_name,
53             'alt': self.attrib.get('alt', ''),
54             'title': self.attrib.get('alt', ''),
55         }
56
57     get_epub_attr = get_html_attr