1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from datetime import date
9 from ebooklib import epub
10 from lxml import etree
11 from librarian import functions, OutputFile, get_resource, XHTMLNS
12 from librarian.cover import make_cover
13 from librarian.embeds.mathml import MathML
14 from librarian.fonts import strip_font
19 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>''')
23 return self.element.find('.//' + XHTMLNS('title'))
27 return self.element.find('.//' + XHTMLNS('body'))
33 def __init__(self, base_url=None, fundraising=None, cover=None):
34 self._base_url = base_url or 'file:///home/rczajka/for/fnp/librarian/temp~/maly/img/'
35 self.fundraising = fundraising
36 self.footnotes = etree.Element('div', id='footnotes')
37 self.make_cover = cover or make_cover
41 # 'header': self.header,
42 'footnotes': self.footnotes,
44 self.current_cursors = []
50 return self.current_cursors[-1]
52 def enter_fragment(self, fragment):
53 self.current_cursors.append(self.cursors[fragment])
55 def exit_fragment(self):
56 self.current_cursors.pop()
58 def create_fragment(self, name, element):
59 assert name not in self.cursors
60 self.cursors[name] = element
62 def forget_fragment(self, name):
63 del self.cursors[name]
67 if self._base_url is not None:
70 return 'https://wolnelektury.pl/media/book/pictures/{}/'.format(self.document.meta.url.slug)
73 # Base URL should be on Document level, not builder.
74 def build(self, document, **kwargs):
75 """Should return an OutputFile with the output."""
76 raise NotImplementedError()
79 class EpubBuilder(Builder):
80 file_extension = 'epub'
81 isbn_field = 'isbn_epub'
84 def __init__(self, *args, debug=False, **kwargs):
89 super().__init__(*args, **kwargs)
91 def build(self, document, **kwargs):
92 # replace_characters -- nie, robimy to na poziomie elementów
94 # hyphenator (\00ad w odp. miejscach) -- jeśli już, to też powinno to się dziać na poziomie elementów
95 # spójniki (\u00a0 po)-- jeśli już, to na poziomie elementów
96 # trick na dywizy: ­⁠-
99 # początek z KAŻDEGO PLIKU xml
101 # zliczamy zbiór użytych znaków
104 # mieliśmy taką flagę less-advertising, używaną tylko dla Prestigio; już nie używamy.
106 # @editors = document.editors() (jako str)
107 # @funders = join(meta.funders)
108 # @thanks = meta.thanks
111 self.output = output = epub.EpubBook()
112 self.document = document
118 self.add_title_page()
127 'Początek utworu', # i18n
130 self.output.guide.append({
133 "href": "part1.xhtml"
137 self.build_document(self.document)
142 self.add_annotations()
143 self.add_support_page()
147 e = len(self.output.spine) - 3 - 3
148 nfunds = len(self.fundraising)
152 # COUNTING CHARACTERS?
153 for f in range(nfunds):
154 spine_index = int(4 + (f / nfunds * e) + f)
158 etree.XML('<div id="book-text"><div class="fundraising">' + self.fundraising[f % len(self.fundraising)] + '</div></div>')
160 self.add_html(h.element, file_name='fund%d.xhtml' % f, spine=spine_index)
164 output_file = tempfile.NamedTemporaryFile(
165 prefix='librarian', suffix='.epub',
168 epub.write_epub(output_file.name, output, {'epub3_landmark': False})
169 return OutputFile.from_filename(output_file.name)
171 def build_document(self, document):
172 self.toc_precedences = []
177 document.tree.getroot().epub_build(self)
178 if document.meta.parts:
181 self.start_element('div', {'class': 'title-page'})
182 self.start_element('h1', {'class': 'title'})
183 self.push_text(document.meta.title)
197 for child in document.children:
199 self.add_toc_entry(None, child.meta.title, 0)
200 self.build_document(child)
202 self.shift_toc_base()
205 def add_title_page(self):
207 html.title.text = "Strona tytułowa"
208 bt = etree.SubElement(html.body, 'div', **{'id': 'book-text'})
209 tp = etree.SubElement(bt, 'div', **{'class': 'title-page'})
211 # Tak jak jest teraz – czy może być jednocześnie
213 # i „dzieło nadrzędne”
214 # wcześniej mogło być dzieło nadrzędne,
216 e = self.document.tree.find('//autor_utworu')
218 etree.SubElement(tp, 'h2', **{'class': 'author'}).text = e.raw_printable_text(self)
219 e = self.document.tree.find('//nazwa_utworu')
221 etree.SubElement(tp, 'h1', **{'class': 'title'}).text = e.raw_printable_text(self)
224 for author in self.document.meta.authors:
225 etree.SubElement(tp, 'h2', **{'class': 'author'}).text = author.readable()
226 etree.SubElement(tp, 'h1', **{'class': 'title'}).text = self.document.meta.title
228 # <xsl:apply-templates select="//nazwa_utworu | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
230 # <xsl:apply-templates select="//dc:creator" mode="poczatek"/>
231 # <xsl:apply-templates select="//dc:title | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
233 etree.SubElement(tp, 'p', **{"class": "info"}).text = '\u00a0'
235 if self.document.meta.translators:
236 p = etree.SubElement(tp, 'p', **{'class': 'info'})
237 p.text = 'tłum. ' + ', '.join(t.readable() for t in self.document.meta.translators)
239 #<p class="info">[Kopia robocza]</p>
241 p = etree.XML("""<p class="info">
242 <a>Ta lektura</a>, podobnie jak tysiące innych, jest dostępna on-line na stronie
243 <a href="https://wolnelektury.pl/">wolnelektury.pl</a>.
245 p[0].attrib['href'] = str(self.document.meta.url)
248 if self.document.meta.thanks:
249 etree.SubElement(tp, 'p', **{'class': 'info'}).text = self.document.meta.thanks
251 tp.append(etree.XML("""
253 Utwór opracowany został w ramach projektu<a href="https://wolnelektury.pl/"> Wolne Lektury</a> przez<a href="https://fundacja.wolnelektury.pl/"> fundację Wolne Lektury</a>.
257 if getattr(self.document.meta, self.isbn_field):
258 etree.SubElement(tp, 'p', **{"class": "info"}).text = getattr(self.document.meta, self.isbn_field)
260 tp.append(etree.XML("""<p class="footer info">
261 <a href="https://wolnelektury.pl/"><img src="logo_wolnelektury.png" alt="WolneLektury.pl" /></a>
266 file_name='title.xhtml',
268 toc='Strona tytułowa' # TODO: i18n
272 get_resource('res/wl-logo-small.png'),
273 file_name='logo_wolnelektury.png',
274 media_type='image/png'
277 def set_metadata(self):
278 self.output.set_identifier(
279 str(self.document.meta.url))
280 self.output.set_language(
281 functions.lang_code_3to2(self.document.meta.language)
283 self.output.set_title(self.document.meta.title)
285 for i, author in enumerate(self.document.meta.authors):
286 self.output.add_author(
289 uid='creator{}'.format(i)
291 for translator in self.document.meta.translators:
292 self.output.add_author(
293 translator.readable(),
294 file_as=str(translator),
296 uid='translator{}'.format(i)
298 for publisher in self.document.meta.publisher:
299 self.output.add_metadata("DC", "publisher", publisher)
301 self.output.add_metadata("DC", "date", self.document.meta.created_at)
307 item = epub.EpubNav()
308 item.add_link(href='style.css', rel='stylesheet', type='text/css')
309 self.output.add_item(item)
310 self.output.spine.append(item)
311 self.output.add_item(epub.EpubNcx())
313 self.output.toc.append(
323 def add_support_page(self):
325 get_resource('res/epub/support.xhtml'),
327 toc='Wesprzyj Wolne Lektury'
331 get_resource('res/jedenprocent.png'),
332 media_type='image/png'
335 get_resource('res/epub/style.css'),
336 media_type='text/css'
340 def add_file(self, path=None, content=None,
341 media_type='application/xhtml+xml',
342 file_name=None, uid=None,
343 spine=False, toc=None):
346 # jakieś tam ścieśnianie białych znaków?
349 with open(path, 'rb') as f:
351 if file_name is None:
352 file_name = path.rsplit('/', 1)[-1]
355 uid = file_name.split('.', 1)[0]
357 item = epub.EpubItem(
360 media_type=media_type,
364 self.output.add_item(item)
367 self.output.spine.append(item)
369 self.output.spine.insert(spine, item)
372 self.output.toc.append(
380 def add_html(self, html_tree, **kwargs):
381 html = etree.tostring(
382 html_tree, pretty_print=True, xml_declaration=True,
384 doctype='<!DOCTYPE html>'
394 for fname in ('DejaVuSerif.ttf', 'DejaVuSerif-Bold.ttf',
395 'DejaVuSerif-Italic.ttf', 'DejaVuSerif-BoldItalic.ttf'):
398 get_resource('fonts/' + fname),
402 media_type='font/ttf'
405 def start_chunk(self):
406 if getattr(self, 'current_chunk', None) is not None:
407 if not len(self.current_chunk):
410 self.current_chunk = etree.Element(
414 self.cursors[None] = self.current_chunk
415 self.current_cursors.append(self.current_chunk)
417 self.section_number = 0
420 def close_chunk(self):
421 assert self.cursor is self.current_chunk
422 ###### -- what if we're inside?
429 self.chunk_counter = chunk_no + 1
432 html.body.append(self.current_chunk)
435 ## html container from template.
438 file_name='part%d.xhtml' % chunk_no,
442 self.current_chunk = None
443 self.current_cursors.pop()
445 def start_element(self, tag, attr):
446 self.current_cursors.append(
447 etree.SubElement(self.cursor, tag, **attr)
450 def end_element(self):
451 self.current_cursors.pop()
453 def push_text(self, text):
454 self.chars.update(text)
456 self.cursor[-1].tail = (self.cursor[-1].tail or '') + text
458 self.cursor.text = (self.cursor.text or '') + text
461 def assign_image_number(self):
462 image_number = getattr(self, 'image_number', 0)
463 self.image_number = image_number + 1
466 def assign_footnote_number(self):
467 number = getattr(self, 'footnote_number', 1)
468 self.footnote_number = number + 1
471 def assign_section_number(self):
472 number = getattr(self, 'section_number', 1)
473 self.section_number = number + 1
476 def assign_mathml_number(self):
477 number = getattr(self, 'mathml_number', 0)
478 self.mathml_number = number + 1
482 def add_toc_entry(self, fragment, name, precedence):
484 while self.toc_precedences and self.toc_precedences[-1] >= precedence:
485 self.toc_precedences.pop()
487 self.toc_precedences = []
489 real_level = self.toc_base + len(self.toc_precedences)
491 self.toc_precedences.append(precedence)
495 part_number = getattr(
500 filename = 'part%d.xhtml' % part_number
501 uid = filename.split('.')[0]
503 filename += '#' + fragment
504 uid += '-' + fragment
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], []]
520 def shift_toc_base(self):
524 def add_last_page(self):
526 m = self.document.meta
528 html.title.text = 'Strona redakcyjna'
529 d = etree.SubElement(html.body, 'div', id='book-text')
531 newp = lambda: etree.SubElement(d, 'p', {'class': 'info'})
535 "Wszystkie zasoby Wolnych Lektur możesz swobodnie wykorzystywać, "
536 "publikować i rozpowszechniać pod warunkiem zachowania warunków "
537 "licencji i zgodnie z "
539 a = etree.SubElement(p, "a", href="https://wolnelektury.pl/info/zasady-wykorzystania/")
540 a.text = "Zasadami wykorzystania Wolnych Lektur"
543 etree.SubElement(p, "br")
547 p[-1].tail = "Ten utwór jest udostępniony na licencji "
548 etree.SubElement(p, 'a', href=m.license).text = m.license_description
550 p[-1].tail = 'Ten utwór jest w domenie publicznej.'
552 etree.SubElement(p, "br")
555 "Wszystkie materiały dodatkowe (przypisy, motywy literackie) są "
558 etree.SubElement(p, 'a', href='https://artlibre.org/licence/lal/pl/').text = 'Licencji Wolnej Sztuki 1.3'
560 etree.SubElement(p, "br")
562 "Fundacja Wolne Lektury 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 "
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.'
573 p.text = 'E-book można pobrać ze strony: '
575 p, 'a', href=str(m.url),
577 ', '.join(p.readable() for p in m.authors),
583 newp().text = 'Tekst opracowany na podstawie: ' + m.source_name
587 """ + ", ".join(p for p in m.publisher)
590 newp().text = m.description
593 editors = self.document.editors()
595 newp().text = 'Opracowanie redakcyjne i przypisy: %s.' % (
596 ', '.join(e.readable() for e in sorted(editors))
600 etree.SubElement(d, 'p', {'class': 'minor-info'}).text = '''Publikację wsparli i wsparły:
601 %s.''' % (', '.join(m.funders))
605 p.text = 'Okładka na podstawie: '
615 if getattr(m, self.isbn_field):
616 newp().text = getattr(m, self.isbn_field)
618 newp().text = '\u00a0'
621 p.attrib['class'] = 'minor-info'
623 Plik wygenerowany dnia '''
624 span = etree.SubElement(p, 'span', id='file_date')
625 span.text = str(date.today())
631 file_name='last.xhtml',
632 toc='Strona redakcyjna',
637 def add_annotations(self):
638 if not len(self.footnotes):
642 html.title.text = 'Przypisy'
643 d = etree.SubElement(
658 d.extend(self.footnotes)
662 file_name='annotations.xhtml',
668 # TODO: allow other covers
670 cover_maker = self.make_cover
672 cover_file = io.BytesIO()
673 cover = cover_maker(self.document.meta, width=600)
674 cover.save(cover_file)
675 cover_name = 'cover.%s' % cover.ext()
677 self.output.set_cover(
678 file_name=cover_name,
679 content=cover_file.getvalue(),
682 ci = ('''<?xml version="1.0" encoding="UTF-8"?>
684 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
686 <title>Okładka</title>
688 body { margin: 0em; padding: 0em; }
689 img { width: 100%%; }
693 <img src="cover.%s" alt="Okładka" />
695 </html>''' % cover.ext()).encode('utf-8')
696 self.add_file(file_name='cover.xhtml', content=ci)
698 self.output.spine.append(('cover', 'no'))
699 self.output.guide.append({
701 'href': 'cover.xhtml',
705 def mathml(self, element):
706 name = "math%d.png" % self.assign_mathml_number()
708 content=MathML(element).to_latex().to_png().data,
709 media_type='image/png',
714 def process_comment(self, comment):
715 m = re.match(r'TRIM:(\d+)', comment.text)
717 self.splits.append(comment.sourceline - int(m.group(1)))