1 from datetime import date
4 from ebooklib import epub
7 from librarian import functions, OutputFile, get_resource, XHTMLNS
8 from librarian.cover import make_cover
9 from librarian.embeds.mathml import MathML
11 from librarian.fonts import strip_font
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>''')
22 return self.element.find('.//' + XHTMLNS('title'))
26 return self.element.find('.//' + XHTMLNS('body'))
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
40 # 'header': self.header,
41 'footnotes': self.footnotes,
43 self.current_cursors = []
49 return self.current_cursors[-1]
51 def enter_fragment(self, fragment):
52 self.current_cursors.append(self.cursors[fragment])
54 def exit_fragment(self):
55 self.current_cursors.pop()
57 def create_fragment(self, name, element):
58 assert name not in self.cursors
59 self.cursors[name] = element
61 def forget_fragment(self, name):
62 del self.cursors[name]
68 if self._base_url is not None:
71 return 'https://wolnelektury.pl/media/book/pictures/{}/'.format(self.document.meta.url.slug)
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()
80 class EpubBuilder(Builder):
81 file_extension = 'epub'
82 isbn_field = 'isbn_epub'
84 def __init__(self, *args, **kwargs):
87 super().__init__(*args, **kwargs)
89 def build(self, document, **kwargs):
90 # replace_characters -- nie, robimy to na poziomie elementów
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: ­⁠-
97 # początek z KAŻDEGO PLIKU xml
99 # zliczamy zbiór użytych znaków
102 # mieliśmy taką flagę less-advertising, używaną tylko dla Prestigio; już nie używamy.
104 # @editors = document.editors() (jako str)
105 # @funders = join(meta.funders)
106 # @thanks = meta.thanks
109 self.output = output = epub.EpubBook()
110 self.document = document
116 self.add_title_page()
125 'Początek utworu', # i18n
128 self.output.guide.append({
131 "href": "part1.xhtml"
135 self.build_document(self.document)
140 self.add_annotations()
141 self.add_support_page()
145 e = len(self.output.spine) - 3 - 3
146 nfunds = len(self.fundraising)
150 # COUNTING CHARACTERS?
151 for f in range(nfunds):
152 spine_index = int(4 + (f / nfunds * e) + f)
156 etree.XML('<div id="book-text"><div class="fundraising">' + self.fundraising[f % len(self.fundraising)] + '</div></div>')
158 self.add_html(h.element, file_name='fund%d.xhtml' % f, spine=spine_index)
162 output_file = tempfile.NamedTemporaryFile(
163 prefix='librarian', suffix='.epub',
166 epub.write_epub(output_file.name, output, {'epub3_landmark': False})
167 return OutputFile.from_filename(output_file.name)
169 def build_document(self, document):
170 self.toc_precedences = []
175 document.tree.getroot().epub_build(self)
176 if document.meta.parts:
179 self.start_element('div', {'class': 'title-page'})
180 self.start_element('h1', {'class': 'title'})
181 self.push_text(document.meta.title)
195 for child in document.children:
197 self.add_toc_entry(None, child.meta.title, 0)
198 self.build_document(child)
200 self.shift_toc_base()
203 def add_title_page(self):
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'})
209 # Tak jak jest teraz – czy może być jednocześnie
211 # i „dzieło nadrzędne”
212 # wcześniej mogło być dzieło nadrzędne,
214 e = self.document.tree.find('//autor_utworu')
216 etree.SubElement(tp, 'h2', **{'class': 'author'}).text = e.raw_printable_text(self)
217 e = self.document.tree.find('//nazwa_utworu')
219 etree.SubElement(tp, 'h1', **{'class': 'title'}).text = e.raw_printable_text(self)
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
226 # <xsl:apply-templates select="//nazwa_utworu | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
228 # <xsl:apply-templates select="//dc:creator" mode="poczatek"/>
229 # <xsl:apply-templates select="//dc:title | //podtytul | //dzielo_nadrzedne" mode="poczatek"/>
231 etree.SubElement(tp, 'p', **{"class": "info"}).text = '\u00a0'
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)
237 #<p class="info">[Kopia robocza]</p>
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>.
243 p[0].attrib['href'] = str(self.document.meta.url)
246 if self.document.meta.thanks:
247 etree.SubElement(tp, 'p', **{'class': 'info'}).text = self.document.meta.thanks
249 tp.append(etree.XML("""
251 Utwór opracowany został w ramach projektu<a href="http://www.wolnelektury.pl/"> Wolne Lektury</a> przez<a href="http://www.nowoczesnapolska.org.pl/"> fundację Nowoczesna Polska</a>.
255 if getattr(self.document.meta, self.isbn_field):
256 etree.SubElement(tp, 'p', **{"class": "info"}).text = getattr(self.document.meta, self.isbn_field)
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>
264 file_name='title.xhtml',
266 toc='Strona tytułowa' # TODO: i18n
270 get_resource('res/wl-logo-small.png'),
271 file_name='logo_wolnelektury.png',
272 media_type='image/png'
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)
281 self.output.set_title(self.document.meta.title)
283 for i, author in enumerate(self.document.meta.authors):
284 self.output.add_author(
286 file_as=six.text_type(author),
287 uid='creator{}'.format(i)
289 for translator in self.document.meta.translators:
290 self.output.add_author(
291 translator.readable(),
292 file_as=six.text_type(translator),
294 uid='translator{}'.format(i)
296 for publisher in self.document.meta.publisher:
297 self.output.add_metadata("DC", "publisher", publisher)
299 self.output.add_metadata("DC", "date", self.document.meta.created_at)
305 item = epub.EpubNav()
306 self.output.add_item(item)
307 self.output.spine.append(item)
308 self.output.add_item(epub.EpubNcx())
310 self.output.toc.append(
320 def add_support_page(self):
322 get_resource('epub/support.xhtml'),
324 toc='Wesprzyj Wolne Lektury'
328 get_resource('res/jedenprocent.png'),
329 media_type='image/png'
332 get_resource('epub/style.css'),
333 media_type='text/css'
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):
343 # jakieś tam ścieśnianie białych znaków?
346 with open(path, 'rb') as f:
348 if file_name is None:
349 file_name = path.rsplit('/', 1)[-1]
352 uid = file_name.split('.', 1)[0]
354 item = epub.EpubItem(
357 media_type=media_type,
361 self.output.add_item(item)
364 self.output.spine.append(item)
366 self.output.spine.insert(spine, item)
369 self.output.toc.append(
377 def add_html(self, html_tree, **kwargs):
378 html = etree.tostring(
379 html_tree, pretty_print=True, xml_declaration=True,
381 doctype='<!DOCTYPE html>'
384 html = librarian.epub.squeeze_whitespace(html)
393 for fname in ('DejaVuSerif.ttf', 'DejaVuSerif-Bold.ttf',
394 'DejaVuSerif-Italic.ttf', 'DejaVuSerif-BoldItalic.ttf'):
397 get_resource('fonts/' + fname),
401 media_type='font/ttf'
404 def start_chunk(self):
405 if getattr(self, 'current_chunk', None) is not None:
406 if not len(self.current_chunk):
409 self.current_chunk = etree.Element(
413 self.cursors[None] = self.current_chunk
414 self.current_cursors.append(self.current_chunk)
416 self.section_number = 0
419 def close_chunk(self):
420 assert self.cursor is self.current_chunk
421 ###### -- what if we're inside?
428 self.chunk_counter = chunk_no + 1
431 html.body.append(self.current_chunk)
434 ## html container from template.
437 file_name='part%d.xhtml' % chunk_no,
441 self.current_chunk = None
442 self.current_cursors.pop()
444 def start_element(self, tag, attr):
445 self.current_cursors.append(
446 etree.SubElement(self.cursor, tag, **attr)
449 def end_element(self):
450 self.current_cursors.pop()
452 def push_text(self, text):
453 self.chars.update(text)
455 self.cursor[-1].tail = (self.cursor[-1].tail or '') + text
457 self.cursor.text = (self.cursor.text or '') + text
460 def assign_image_number(self):
461 image_number = getattr(self, 'image_number', 0)
462 self.image_number = image_number + 1
465 def assign_footnote_number(self):
466 number = getattr(self, 'footnote_number', 1)
467 self.footnote_number = number + 1
470 def assign_section_number(self):
471 number = getattr(self, 'section_number', 1)
472 self.section_number = number + 1
475 def assign_mathml_number(self):
476 number = getattr(self, 'mathml_number', 0)
477 self.mathml_number = number + 1
481 def add_toc_entry(self, fragment, name, precedence):
483 while self.toc_precedences and self.toc_precedences[-1] >= precedence:
484 self.toc_precedences.pop()
486 self.toc_precedences = []
488 real_level = self.toc_base + len(self.toc_precedences)
490 self.toc_precedences.append(precedence)
494 part_number = getattr(
499 filename = 'part%d.xhtml' % part_number
500 uid = filename.split('.')[0]
502 filename += '#' + fragment
503 uid += '-' + fragment
505 toc = self.output.toc
506 for l in range(1, real_level):
507 if isinstance(toc[-1], epub.Link):
508 toc[-1] = [toc[-1], []]
519 def shift_toc_base(self):
523 def add_last_page(self):
525 m = self.document.meta
527 html.title.text = 'Strona redakcyjna'
528 d = etree.SubElement(html.body, 'div', id='book-text')
530 newp = lambda: etree.SubElement(d, 'p', {'class': 'info'})
534 "Wszystkie zasoby Wolnych Lektur możesz swobodnie wykorzystywać, "
535 "publikować i rozpowszechniać pod warunkiem zachowania warunków "
536 "licencji i zgodnie z "
538 a = etree.SubElement(p, "a", href="https://wolnelektury.pl/info/zasady-wykorzystania/")
539 a.text = "Zasadami wykorzystania Wolnych Lektur"
542 etree.SubElement(p, "br")
546 p[-1].tail = "Ten utwór jest udostępniony na licencji "
547 etree.SubElement(p, 'a', href=m.license).text = m.license_description
549 p[-1].tail = 'Ten utwór jest w domenie publicznej.'
551 etree.SubElement(p, "br")
554 "Wszystkie materiały dodatkowe (przypisy, motywy literackie) są "
557 etree.SubElement(p, 'a', href='https://artlibre.org/licence/lal/pl/').text = 'Licencji Wolnej Sztuki 1.3'
559 etree.SubElement(p, "br")
561 "Fundacja Nowoczesna Polska zastrzega sobie prawa do wydania "
562 "krytycznego zgodnie z art. Art.99(2) Ustawy o prawach autorskich "
563 "i prawach pokrewnych. Wykorzystując zasoby z Wolnych Lektur, "
564 "należy pamiętać o zapisach licencji oraz zasadach, które "
568 etree.SubElement(p, 'a', href='https://wolnelektury.pl/info/zasady-wykorzystania/').text = 'Zasadach wykorzystania Wolnych Lektur'
569 p[-1].tail = '. Zapoznaj się z nimi, zanim udostępnisz dalej nasze książki.'
572 p.text = 'E-book można pobrać ze strony: '
574 p, 'a', href=str(m.url),
576 ', '.join(p.readable() for p in m.authors),
582 newp().text = 'Tekst opracowany na podstawie: ' + m.source_name
586 """ + ", ".join(p for p in m.publisher)
589 newp().text = m.description
593 newp().text = 'Opracowanie redakcyjne i przypisy: %s.' % (
594 ', '.join(e.readable() for e in sorted(self.document.editors())))
597 etree.SubElement(d, 'p', {'class': 'minor-info'}).text = '''Publikację wsparli i wsparły:
598 %s.''' % (', '.join(m.funders))
602 p.text = 'Okładka na podstawie: '
612 if getattr(m, self.isbn_field):
613 newp().text = getattr(m, self.isbn_field)
615 newp().text = '\u00a0'
618 p.attrib['class'] = 'minor-info'
620 Plik wygenerowany dnia '''
621 span = etree.SubElement(p, 'span', id='file_date')
622 span.text = str(date.today())
628 file_name='last.xhtml',
629 toc='Strona redakcyjna',
634 def add_annotations(self):
635 if not len(self.footnotes):
639 html.title.text = 'Przypisy'
640 d = etree.SubElement(
655 d.extend(self.footnotes)
659 file_name='annotations.xhtml',
665 # TODO: allow other covers
667 cover_maker = self.make_cover
669 cover_file = six.BytesIO()
670 cover = cover_maker(self.document.meta, width=600)
671 cover.save(cover_file)
672 cover_name = 'cover.%s' % cover.ext()
674 self.output.set_cover(
675 file_name=cover_name,
676 content=cover_file.getvalue(),
679 ci = ('''<?xml version="1.0" encoding="UTF-8"?>
681 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
683 <title>Okładka</title>
685 body { margin: 0em; padding: 0em; }
686 img { width: 100%%; }
690 <img src="cover.%s" alt="Okładka" />
692 </html>''' % cover.ext()).encode('utf-8')
693 self.add_file(file_name='cover.xhtml', content=ci)
695 self.output.spine.append(('cover', 'no'))
696 self.output.guide.append({
698 'href': 'cover.xhtml',
702 def mathml(self, element):
703 name = "math%d.png" % self.assign_mathml_number()
705 content=MathML(element).to_latex().to_png().data,
706 media_type='image/png',