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