Drop lots of legacy code. Support Python 3.7-3.11.
[librarian.git] / src / librarian / builders / epub.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 from datetime import date
5 import io
6 import os
7 import tempfile
8 from ebooklib import epub
9 from lxml import etree
10 from librarian import functions, OutputFile, get_resource, XHTMLNS
11 from librarian.cover import make_cover
12 from librarian.embeds.mathml import MathML
13 from librarian.fonts import strip_font
14
15
16 class Xhtml:
17     def __init__(self):
18         self.element = etree.XML('''<html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" href="style.css" type="text/css"/><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>WolneLektury.pl</title></head><body/></html>''')
19
20     @property
21     def title(self):
22         return self.element.find('.//' + XHTMLNS('title'))
23         
24     @property
25     def body(self):
26         return self.element.find('.//' + XHTMLNS('body'))
27
28
29 class Builder:
30     file_extension = None
31
32     def __init__(self, base_url=None, fundraising=None, cover=None):
33         self._base_url = base_url or 'file:///home/rczajka/for/fnp/librarian/temp~/maly/img/'
34         self.fundraising = fundraising
35         self.footnotes = etree.Element('div', id='footnotes')
36         self.make_cover = cover or make_cover
37
38         self.cursors = {
39 #            None: None,
40 #            'header': self.header,
41             'footnotes': self.footnotes,
42         }
43         self.current_cursors = []
44
45         self.toc_base = 0
46
47     @property
48     def cursor(self):
49         return self.current_cursors[-1]
50
51     def enter_fragment(self, fragment):
52         self.current_cursors.append(self.cursors[fragment])
53
54     def exit_fragment(self):
55         self.current_cursors.pop()
56
57     def create_fragment(self, name, element):
58         assert name not in self.cursors
59         self.cursors[name] = element
60
61     def forget_fragment(self, name):
62         del self.cursors[name]
63
64     @property
65     def base_url(self):
66         if self._base_url is not None:
67             return self._base_url
68         else:
69             return 'https://wolnelektury.pl/media/book/pictures/{}/'.format(self.document.meta.url.slug)
70
71
72     # Base URL should be on Document level, not builder.
73     def build(self, document, **kwargs):
74         """Should return an OutputFile with the output."""
75         raise NotImplementedError()
76
77
78 class EpubBuilder(Builder):
79     file_extension = 'epub'
80     isbn_field = 'isbn_epub'
81     orphans = True
82
83     def __init__(self, *args, **kwargs):
84         self.chars = set()
85         self.fundr = 0
86         super().__init__(*args, **kwargs)
87     
88     def build(self, document, **kwargs):
89         # replace_characters -- nie, robimy to na poziomie elementów
90         
91         # hyphenator (\00ad w odp. miejscach) -- jeśli już, to też powinno to się dziać na poziomie elementów
92         # spójniki (\u00a0 po)-- jeśli już, to na poziomie elementów
93         # trick na dywizy: &#xad;&#8288;-
94
95         # do toc trafia:
96         #   początek z KAŻDEGO PLIKU xml
97         
98         # zliczamy zbiór użytych znaków
99
100         # flagi:
101         # mieliśmy taką flagę less-advertising, używaną tylko dla Prestigio; już nie używamy.
102
103         # @editors = document.editors() (jako str)
104         # @funders = join(meta.funders)
105         # @thanks = meta.thanks
106
107
108         self.output = output = epub.EpubBook()
109         self.document = document
110
111         self.set_metadata()
112         
113         self.add_cover()
114         
115         self.add_title_page()
116         self.add_toc()
117
118
119
120         self.start_chunk()
121
122         self.add_toc_entry(
123             None,
124             'Początek utworu', # i18n
125             0
126         )
127         self.output.guide.append({
128             "type": "text",
129             "title": "Początek",
130             "href": "part1.xhtml"
131         })
132
133
134         self.build_document(self.document)
135
136         
137         self.close_chunk()
138
139         self.add_annotations()
140         self.add_support_page()
141         self.add_last_page()
142
143         if self.fundraising:
144             e = len(self.output.spine) - 3 - 3
145             nfunds = len(self.fundraising)
146             if e > 4 * nfunds:
147                 nfunds *= 2
148
149             # COUNTING CHARACTERS?
150             for f in range(nfunds):
151                 spine_index = int(4 + (f / nfunds * e) + f)
152
153                 h = Xhtml()
154                 h.body.append(
155                     etree.XML('<div id="book-text"><div class="fundraising">' + self.fundraising[f % len(self.fundraising)] + '</div></div>')
156                 )
157                 self.add_html(h.element, file_name='fund%d.xhtml' % f, spine=spine_index)
158
159         self.add_fonts()
160
161         output_file = tempfile.NamedTemporaryFile(
162             prefix='librarian', suffix='.epub',
163             delete=False)
164         output_file.close()
165         epub.write_epub(output_file.name, output, {'epub3_landmark': False})
166         return OutputFile.from_filename(output_file.name)
167
168     def build_document(self, document):
169         self.toc_precedences = []
170
171         self.start_chunk()
172
173
174         document.tree.getroot().epub_build(self)
175         if document.meta.parts:
176             self.start_chunk()
177
178             self.start_element('div', {'class': 'title-page'})
179             self.start_element('h1', {'class': 'title'})
180             self.push_text(document.meta.title)
181             self.end_element()
182             self.end_element()
183
184             ######
185             # 160
186             # translators
187             # working copy?
188             # ta lektura
189             # tanks
190             # utwor opracowany
191             # isbn
192             # logo
193
194             for child in document.children:
195                 self.start_chunk()
196                 self.add_toc_entry(None, child.meta.title, 0)
197                 self.build_document(child)
198
199         self.shift_toc_base()
200             
201     
202     def add_title_page(self):
203         html = Xhtml()
204         html.title.text = "Strona tytułowa"
205         bt = etree.SubElement(html.body, 'div', **{'id': 'book-text'})
206         tp = etree.SubElement(bt, 'div', **{'class': 'title-page'})
207
208         # Tak jak jest teraz – czy może być jednocześnie
209         # no „autor_utworu”
210         # i „dzieło nadrzędne”
211         # wcześniej mogło być dzieło nadrzędne,
212
213         e = self.document.tree.find('//autor_utworu')
214         if e is not None:
215             etree.SubElement(tp, 'h2', **{'class': 'author'}).text = e.raw_printable_text(self)
216         e = self.document.tree.find('//nazwa_utworu')
217         if e is not None:
218             etree.SubElement(tp, 'h1', **{'class': 'title'}).text = e.raw_printable_text(self)
219
220         if not len(tp):
221             for author in self.document.meta.authors:
222                 etree.SubElement(tp, 'h2', **{'class': 'author'}).text = author.readable()
223             etree.SubElement(tp, 'h1', **{'class': 'title'}).text = self.document.meta.title
224
225 #                <xsl:apply-templates select="//nazwa_utworu | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
226 #        else:
227 #                            <xsl:apply-templates select="//dc:creator" mode="poczatek"/>
228 #                <xsl:apply-templates select="//dc:title | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
229
230         etree.SubElement(tp, 'p', **{"class": "info"}).text = '\u00a0'
231
232         if self.document.meta.translators:
233             p = etree.SubElement(tp, 'p', **{'class': 'info'})
234             p.text = 'tłum. ' + ', '.join(t.readable() for t in self.document.meta.translators)
235                 
236         #<p class="info">[Kopia robocza]</p>
237
238         p = etree.XML("""<p class="info">
239               <a>Ta lektura</a>, podobnie jak tysiące innych, jest dostępna on-line na stronie
240               <a href="https://wolnelektury.pl/">wolnelektury.pl</a>.
241             </p>""")
242         p[0].attrib['href'] = str(self.document.meta.url)
243         tp.append(p)
244
245         if self.document.meta.thanks:
246             etree.SubElement(tp, 'p', **{'class': 'info'}).text = self.document.meta.thanks
247         
248         tp.append(etree.XML("""
249           <p class="info">
250             Utwór opracowany został w&#160;ramach projektu<a href="https://wolnelektury.pl/"> Wolne Lektury</a> przez<a href="https://fundacja.wolnelektury.pl/"> fundację Wolne Lektury</a>.
251           </p>
252         """))
253
254         if getattr(self.document.meta, self.isbn_field):
255             etree.SubElement(tp, 'p', **{"class": "info"}).text = getattr(self.document.meta, self.isbn_field)
256
257         tp.append(etree.XML("""<p class="footer info">
258             <a href="https://wolnelektury.pl/"><img src="logo_wolnelektury.png" alt="WolneLektury.pl" /></a>
259         </p>"""))
260
261         self.add_html(
262             html.element,
263             file_name='title.xhtml',
264             spine=True,
265             toc='Strona tytułowa' # TODO: i18n
266         )
267
268         self.add_file(
269             get_resource('res/wl-logo-small.png'),
270             file_name='logo_wolnelektury.png',
271             media_type='image/png'
272         )
273     
274     def set_metadata(self):
275         self.output.set_identifier(
276             str(self.document.meta.url))
277         self.output.set_language(
278             functions.lang_code_3to2(self.document.meta.language)
279         )
280         self.output.set_title(self.document.meta.title)
281
282         for i, author in enumerate(self.document.meta.authors):
283             self.output.add_author(
284                 author.readable(),
285                 file_as=str(author),
286                 uid='creator{}'.format(i)
287             )
288         for translator in self.document.meta.translators:
289             self.output.add_author(
290                 translator.readable(),
291                 file_as=str(translator),
292                 role='trl',
293                 uid='translator{}'.format(i)
294             )
295         for publisher in self.document.meta.publisher:
296             self.output.add_metadata("DC", "publisher", publisher)
297
298         self.output.add_metadata("DC", "date", self.document.meta.created_at)
299
300         
301
302
303     def add_toc(self):
304         item = epub.EpubNav()
305         item.add_link(href='style.css', rel='stylesheet', type='text/css')
306         self.output.add_item(item)
307         self.output.spine.append(item)
308         self.output.add_item(epub.EpubNcx())
309
310         self.output.toc.append(
311             epub.Link(
312                 "nav.xhtml",
313                 "Spis treści",
314                 "nav"
315             )
316         )
317
318     
319
320     def add_support_page(self):
321         self.add_file(
322             get_resource('res/epub/support.xhtml'),
323             spine=True,
324             toc='Wesprzyj Wolne Lektury'
325         )
326
327         self.add_file(
328             get_resource('res/jedenprocent.png'),
329             media_type='image/png'
330         )
331         self.add_file(
332             get_resource('res/epub/style.css'),
333             media_type='text/css'
334         )
335
336
337     def add_file(self, path=None, content=None,
338                  media_type='application/xhtml+xml',
339                  file_name=None, uid=None,
340                  spine=False, toc=None):
341
342         # update chars?
343         # jakieś tam ścieśnianie białych znaków?
344
345         if content is None:
346             with open(path, 'rb') as f:
347                 content = f.read()
348             if file_name is None:
349                 file_name = path.rsplit('/', 1)[-1]
350
351         if uid is None:
352             uid = file_name.split('.', 1)[0]
353
354         item = epub.EpubItem(
355             uid=uid,
356             file_name=file_name,
357             media_type=media_type,
358             content=content
359         )
360
361         self.output.add_item(item)
362         if spine:
363             if spine is True:
364                 self.output.spine.append(item)
365             else:
366                 self.output.spine.insert(spine, item)
367
368         if toc:
369             self.output.toc.append(
370                 epub.Link(
371                     file_name,
372                     toc,
373                     uid
374                 )
375             )
376
377     def add_html(self, html_tree, **kwargs):
378         html = etree.tostring(
379             html_tree, pretty_print=True, xml_declaration=True,
380             encoding="utf-8",
381             doctype='<!DOCTYPE html>'
382         )
383
384         self.add_file(
385             content=html,
386             **kwargs
387         )
388             
389         
390     def add_fonts(self):
391         for fname in ('DejaVuSerif.ttf', 'DejaVuSerif-Bold.ttf',
392                       'DejaVuSerif-Italic.ttf', 'DejaVuSerif-BoldItalic.ttf'):
393             self.add_file(
394                 content=strip_font(
395                     get_resource('fonts/' + fname),
396                     self.chars
397                 ),
398                 file_name=fname,
399                 media_type='font/ttf'
400             )
401
402     def start_chunk(self):
403         if getattr(self, 'current_chunk', None) is not None:
404             if not len(self.current_chunk):
405                 return
406             self.close_chunk()
407         self.current_chunk = etree.Element(
408             'div',
409             id="book-text"
410         )
411         self.cursors[None] = self.current_chunk
412         self.current_cursors.append(self.current_chunk)
413
414         self.section_number = 0
415         
416
417     def close_chunk(self):
418         assert self.cursor is self.current_chunk
419         ###### -- what if we're inside?
420
421         chunk_no = getattr(
422             self,
423             'chunk_counter',
424             1
425         )
426         self.chunk_counter = chunk_no + 1
427
428         html = Xhtml()
429         html.body.append(self.current_chunk)
430         
431         self.add_html(
432             ## html container from template.
433             #self.current_chunk,
434             html.element,
435             file_name='part%d.xhtml' % chunk_no,
436             spine=True,
437             
438         )
439         self.current_chunk = None
440         self.current_cursors.pop()
441
442     def start_element(self, tag, attr):
443         self.current_cursors.append(
444             etree.SubElement(self.cursor, tag, **attr)
445         )
446         
447     def end_element(self):
448         self.current_cursors.pop()
449         
450     def push_text(self, text):
451         self.chars.update(text)
452         if len(self.cursor):
453             self.cursor[-1].tail = (self.cursor[-1].tail or '') + text
454         else:
455             self.cursor.text = (self.cursor.text or '') + text
456
457
458     def assign_image_number(self):
459         image_number = getattr(self, 'image_number', 0)
460         self.image_number = image_number + 1
461         return image_number
462
463     def assign_footnote_number(self):
464         number = getattr(self, 'footnote_number', 1)
465         self.footnote_number = number + 1
466         return number
467
468     def assign_section_number(self):
469         number = getattr(self, 'section_number', 1)
470         self.section_number = number + 1
471         return number
472
473     def assign_mathml_number(self):
474         number = getattr(self, 'mathml_number', 0)
475         self.mathml_number = number + 1
476         return number
477
478     
479     def add_toc_entry(self, fragment, name, precedence):
480         if precedence:
481             while self.toc_precedences and self.toc_precedences[-1] >= precedence:
482                 self.toc_precedences.pop()
483         else:
484             self.toc_precedences = []
485
486         real_level = self.toc_base + len(self.toc_precedences)
487         if precedence:
488             self.toc_precedences.append(precedence)
489         else:
490             self.toc_base += 1
491         
492         part_number = getattr(
493             self,
494             'chunk_counter',
495             1
496         )
497         filename = 'part%d.xhtml' % part_number
498         uid = filename.split('.')[0]
499         if fragment:
500             filename += '#' + fragment
501             uid += '-' + fragment
502
503         toc = self.output.toc
504         for l in range(1, real_level):
505             if isinstance(toc[-1], epub.Link):
506                 toc[-1] = [toc[-1], []]
507             toc = toc[-1][1]
508
509         toc.append(
510             epub.Link(
511                 filename,
512                 name,
513                 uid
514             )
515         )
516
517     def shift_toc_base(self):
518         self.toc_base -= 1
519         
520
521     def add_last_page(self):
522         html = Xhtml()
523         m = self.document.meta
524         
525         html.title.text = 'Strona redakcyjna'
526         d = etree.SubElement(html.body, 'div', id='book-text')
527
528         newp = lambda: etree.SubElement(d, 'p', {'class': 'info'})
529
530         p = newp()
531         p.text = (
532             "Wszystkie zasoby Wolnych Lektur możesz swobodnie wykorzystywać, "
533             "publikować i rozpowszechniać pod warunkiem zachowania warunków "
534             "licencji i zgodnie z "
535         )
536         a = etree.SubElement(p, "a", href="https://wolnelektury.pl/info/zasady-wykorzystania/")
537         a.text = "Zasadami wykorzystania Wolnych Lektur"
538         a.tail = "."
539
540         etree.SubElement(p, "br")
541         
542
543         if m.license:
544             p[-1].tail = "Ten utwór jest udostępniony na licencji "
545             etree.SubElement(p, 'a', href=m.license).text = m.license_description
546         else:
547             p[-1].tail = 'Ten utwór jest w domenie publicznej.'
548
549         etree.SubElement(p, "br")
550         
551         p[-1].tail = (
552             "Wszystkie materiały dodatkowe (przypisy, motywy literackie) są "
553             "udostępnione na "
554             )
555         etree.SubElement(p, 'a', href='https://artlibre.org/licence/lal/pl/').text = 'Licencji Wolnej Sztuki 1.3'
556         p[-1].tail = '.'
557         etree.SubElement(p, "br")
558         p[-1].tail = (
559             "Fundacja Wolne Lektury zastrzega sobie prawa do wydania "
560             "krytycznego zgodnie z art. Art.99(2) Ustawy o prawach autorskich "
561             "i prawach pokrewnych. Wykorzystując zasoby z Wolnych Lektur, "
562             "należy pamiętać o zapisach licencji oraz zasadach, które "
563             "spisaliśmy w "
564         )
565
566         etree.SubElement(p, 'a', href='https://wolnelektury.pl/info/zasady-wykorzystania/').text = 'Zasadach wykorzystania Wolnych Lektur'
567         p[-1].tail = '. Zapoznaj się z nimi, zanim udostępnisz dalej nasze książki.'
568
569         p = newp()
570         p.text = 'E-book można pobrać ze strony: '
571         etree.SubElement(
572             p, 'a', href=str(m.url),
573             title=', '.join((
574                 ', '.join(p.readable() for p in m.authors),
575                 m.title
576             ))
577         ).text = str(m.url)
578
579         if m.source_name:
580             newp().text = 'Tekst opracowany na podstawie: ' + m.source_name
581
582         newp().text = """
583               Wydawca:
584               """ + ", ".join(p for p in m.publisher)
585
586         if m.description:
587             newp().text = m.description
588
589
590         editors = self.document.editors()
591         if editors:
592             newp().text = 'Opracowanie redakcyjne i przypisy: %s.' % (
593                 ', '.join(e.readable() for e in sorted(editors))
594             )
595
596         if m.funders:
597             etree.SubElement(d, 'p', {'class': 'minor-info'}).text = '''Publikację wsparli i wsparły:
598             %s.''' % (', '.join(m.funders))
599
600         if m.cover_by:
601             p = newp()
602             p.text = 'Okładka na podstawie: '
603             if m.cover_source:
604                 etree.SubElement(
605                     p,
606                     'a',
607                     href=m.cover_source
608                 ).text = m.cover_by
609             else:
610                 p.text += m.cover_by
611             
612         if getattr(m, self.isbn_field):
613             newp().text = getattr(m, self.isbn_field)
614
615         newp().text = '\u00a0'
616
617         p = newp()
618         p.attrib['class'] = 'minor-info'
619         p.text = '''
620               Plik wygenerowany dnia '''
621         span = etree.SubElement(p, 'span', id='file_date')
622         span.text = str(date.today())
623         span.tail = '''.
624           '''
625         
626         self.add_html(
627             html.element,
628             file_name='last.xhtml',
629             toc='Strona redakcyjna',
630             spine=True
631         )
632
633
634     def add_annotations(self):
635         if not len(self.footnotes):
636             return
637
638         html = Xhtml()
639         html.title.text = 'Przypisy'
640         d = etree.SubElement(
641             etree.SubElement(
642                 html.body,
643                 'div',
644                 id='book-text'
645             ),
646             'div',
647             id='footnotes'
648         )
649         
650         etree.SubElement(
651             d,
652             'h2',
653         ).text = 'Przypisy:'
654
655         d.extend(self.footnotes)
656         
657         self.add_html(
658             html.element,
659             file_name='annotations.xhtml',
660             spine=True,
661             toc='Przypisy'
662         )
663
664     def add_cover(self):
665         # TODO: allow other covers
666
667         cover_maker = self.make_cover
668
669         cover_file = io.BytesIO()
670         cover = cover_maker(self.document.meta, width=600)
671         cover.save(cover_file)
672         cover_name = 'cover.%s' % cover.ext()
673
674         self.output.set_cover(
675             file_name=cover_name,
676             content=cover_file.getvalue(),
677             create_page = False
678         )
679         ci = ('''<?xml version="1.0" encoding="UTF-8"?>
680 <!DOCTYPE html>
681 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
682  <head>
683   <title>Okładka</title>
684   <style>
685     body { margin: 0em; padding: 0em; }
686     img { width: 100%%; }
687   </style>
688  </head>
689  <body>
690    <img src="cover.%s" alt="Okładka" />
691  </body>
692 </html>''' % cover.ext()).encode('utf-8')
693         self.add_file(file_name='cover.xhtml', content=ci)
694
695         self.output.spine.append(('cover', 'no'))
696         self.output.guide.append({
697             'type': 'cover',
698             'href': 'cover.xhtml',
699             'title': 'Okładka'
700         })
701
702     def mathml(self, element):
703         name = "math%d.png" % self.assign_mathml_number()
704         self.add_file(
705             content=MathML(element).to_latex().to_png().data,
706             media_type='image/png',
707             file_name=name
708         )
709         return name