1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import with_statement
10 from copy import deepcopy
11 from lxml import etree
15 sys.path.append('..') # for running from working copy
17 from librarian import XMLNamespace, RDFNS, DCNS, WLNS, NCXNS, OPFNS, NoDublinCore
18 from librarian.dcparser import BookInfo
22 """ returns node's text and children as a string
24 >>> print inner_xml(etree.fromstring('<a>x<b>y</b>z</a>'))
28 nt = node.text if node.text is not None else ''
29 return ''.join([nt] + [etree.tostring(child) for child in node])
31 def set_inner_xml(node, text):
32 """ sets node's text and children from a string
34 >>> e = etree.fromstring('<a>b<b>x</b>x</a>')
35 >>> set_inner_xml(e, 'x<b>y</b>z')
36 >>> print etree.tostring(e)
40 p = etree.fromstring('<x>%s</x>' % text)
46 """ Find out a node's name
48 >>> print node_name(etree.fromstring('<a>X<b>Y</b>Z</a>'))
52 tempnode = deepcopy(node)
54 for p in ('pe', 'pa', 'pt', 'pr', 'motyw'):
55 for e in tempnode.findall('.//%s' % p):
59 etree.strip_tags(tempnode, '*')
64 if isinstance(xml, etree._Element):
65 xml = etree.ElementTree(xml)
66 with open(sheet) as xsltf:
67 return xml.xslt(etree.parse(xsltf))
70 _resdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epub')
72 return os.path.join(_resdir, fname)
75 def replace_characters(node):
76 def replace_chars(text):
79 return text.replace("---", u"\u2014")\
80 .replace("--", u"\u2013")\
81 .replace(",,", u"\u201E")\
82 .replace('"', u"\u201D")\
83 .replace("'", u"\u2019")
84 if node.tag == 'extra':
87 node.text = replace_chars(node.text)
88 node.tail = replace_chars(node.tail)
90 replace_characters(child)
93 def find_annotations(annotations, source, part_no):
95 if child.tag in ('pe', 'pa', 'pt', 'pr'):
96 annotation = deepcopy(child)
97 number = str(len(annotations)+1)
98 annotation.set('number', number)
99 annotation.set('part', str(part_no))
101 annotations.append(annotation)
106 if child.tag not in ('extra', 'podtytul'):
107 find_annotations(annotations, child, part_no)
110 def replace_by_verse(tree):
111 """ Find stanzas and create new verses in place of a '/' character """
113 stanzas = tree.findall('.//' + WLNS('strofa'))
115 for child_node in node:
116 if child_node.tag in ('slowo_obce', 'wyroznienie'):
117 foreign_verses = inner_xml(child_node).split('/\n')
118 if len(foreign_verses) > 1:
120 for foreign_verse in foreign_verses:
121 if foreign_verse.startswith('<wers'):
122 new_foreign += foreign_verse
124 new_foreign += ''.join(('<wers_normalny>', foreign_verse, '</wers_normalny>'))
125 set_inner_xml(child_node, new_foreign)
126 verses = inner_xml(node).split('/\n')
128 modified_inner_xml = ''
130 if verse.startswith('<wers') or verse.startswith('<extra'):
131 modified_inner_xml += verse
133 modified_inner_xml += ''.join(('<wers_normalny>', verse, '</wers_normalny>'))
134 set_inner_xml(node, modified_inner_xml)
137 def add_to_manifest(manifest, partno):
138 """ Adds a node to the manifest section in content.opf file """
140 partstr = 'part%d' % partno
141 e = manifest.makeelement(OPFNS('item'), attrib={
143 'href': partstr + '.html',
144 'media-type': 'application/xhtml+xml',
149 def add_to_spine(spine, partno):
150 """ Adds a node to the spine section in content.opf file """
152 e = spine.makeelement(OPFNS('itemref'), attrib={'idref': 'part%d' % partno});
157 def __init__(self, name=None, part_number=None):
160 self.part_number = part_number
161 self.sub_number = None
163 def add(self, name, part_number, level=0, is_part=True):
164 if level > 0 and self.children:
165 return self.children[-1].add(name, part_number, level-1, is_part)
168 t.part_number = part_number
169 self.children.append(t)
171 t.sub_number = len(self.children) + 1
174 def append(self, toc):
175 self.children.append(toc)
177 def extend(self, toc):
178 self.children.extend(toc.children)
182 return max((c.depth() for c in self.children)) + 1
186 def write_to_xml(self, nav_map, counter):
187 for child in self.children:
188 nav_point = nav_map.makeelement(NCXNS('navPoint'))
189 nav_point.set('id', 'NavPoint-%d' % counter)
190 nav_point.set('playOrder', str(counter))
192 nav_label = nav_map.makeelement(NCXNS('navLabel'))
193 text = nav_map.makeelement(NCXNS('text'))
194 text.text = child.name
195 nav_label.append(text)
196 nav_point.append(nav_label)
198 content = nav_map.makeelement(NCXNS('content'))
199 src = 'part%d.html' % child.part_number
200 if child.sub_number is not None:
201 src += '#sub%d' % child.sub_number
202 content.set('src', src)
203 nav_point.append(content)
204 nav_map.append(nav_point)
205 counter = child.write_to_xml(nav_point, counter + 1)
210 """ divide main content of the XML file into chunks """
212 # prepare a container for each chunk
213 part_xml = etree.Element('utwor')
214 etree.SubElement(part_xml, 'master')
215 main_xml_part = part_xml[0] # master
217 last_node_part = False
218 for one_part in main_text:
220 if name == 'naglowek_czesc':
222 last_node_part = True
223 main_xml_part[:] = [deepcopy(one_part)]
224 elif not last_node_part and name in ("naglowek_rozdzial", "naglowek_akt", "srodtytul"):
226 main_xml_part[:] = [deepcopy(one_part)]
228 main_xml_part.append(deepcopy(one_part))
229 last_node_part = False
233 def transform_chunk(chunk_xml, chunk_no, annotations):
234 """ transforms one chunk, returns a HTML string and a TOC object """
237 for element in chunk_xml[0]:
238 if element.tag in ("naglowek_czesc", "naglowek_rozdzial", "naglowek_akt", "srodtytul"):
239 toc.add(node_name(element), chunk_no)
240 elif element.tag in ('naglowek_podrozdzial', 'naglowek_scena'):
241 subnumber = toc.add(node_name(element), chunk_no, level=1, is_part=False)
242 element.set('sub', str(subnumber))
243 find_annotations(annotations, chunk_xml, chunk_no)
244 replace_by_verse(chunk_xml)
245 output_html = etree.tostring(xslt(chunk_xml, res('xsltScheme.xsl')), pretty_print=True)
246 return output_html, toc
249 def transform(provider, slug, output_file=None, output_dir=None):
252 provider is a DocProvider
253 either output_file (a file-like object) or output_dir (path to file/dir) should be specified
254 if output_dir is specified, file will be written to <output_dir>/<author>/<slug>.epub
257 def transform_file(input_xml, chunk_counter=1, first=True):
258 """ processes one input file and proceeds to its children """
260 children = [child.text for child in input_xml.findall('.//'+DCNS('relation.hasPart'))]
262 # every input file will have a TOC entry,
263 # pointing to starting chunk
264 toc = TOC(node_name(input_xml.find('.//'+DCNS('title'))), chunk_counter)
266 # write book title page
267 zip.writestr('OPS/title.html',
268 etree.tostring(xslt(input_xml, res('xsltTitle.xsl')), pretty_print=True))
270 # write title page for every parent
271 zip.writestr('OPS/part%d.html' % chunk_counter,
272 etree.tostring(xslt(input_xml, res('xsltChunkTitle.xsl')), pretty_print=True))
273 add_to_manifest(manifest, chunk_counter)
274 add_to_spine(spine, chunk_counter)
277 if len(input_xml.getroot()) > 1:
278 # rdf before style master
279 main_text = input_xml.getroot()[1]
281 # rdf in style master
282 main_text = input_xml.getroot()[0]
283 if main_text.tag == RDFNS('RDF'):
286 if main_text is not None:
287 replace_characters(main_text)
289 for chunk_xml in chop(main_text):
290 chunk_html, chunk_toc = transform_chunk(chunk_xml, chunk_counter, annotations)
291 toc.extend(chunk_toc)
292 zip.writestr('OPS/part%d.html' % chunk_counter, chunk_html)
293 add_to_manifest(manifest, chunk_counter)
294 add_to_spine(spine, chunk_counter)
298 for child in children:
299 child_xml = etree.parse(provider.by_uri(child))
300 child_toc, chunk_counter = transform_file(child_xml, chunk_counter, first=False)
301 toc.append(child_toc)
303 return toc, chunk_counter
305 # read metadata from the first file
306 input_xml = etree.parse(provider[slug])
307 metadata = input_xml.find('.//'+RDFNS('Description'))
309 raise NoDublinCore('Document has no DublinCore - which is required.')
310 book_info = BookInfo.from_element(input_xml)
311 metadata = etree.ElementTree(metadata)
313 # if output to dir, create the file
314 if output_dir is not None:
315 author = unicode(book_info.author)
316 author_dir = os.path.join(output_dir, author)
318 os.makedirs(author_dir)
321 output_file = open(os.path.join(author_dir, '%s.epub' % slug), 'w')
324 zip = zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED)
326 # write static elements
327 mime = zipfile.ZipInfo()
328 mime.filename = 'mimetype'
329 mime.compress_type = zipfile.ZIP_STORED
331 zip.writestr(mime, 'application/epub+zip')
332 zip.writestr('META-INF/container.xml', '<?xml version="1.0" ?><container version="1.0" ' \
333 'xmlns="urn:oasis:names:tc:opendocument:xmlns:container">' \
334 '<rootfiles><rootfile full-path="OPS/content.opf" ' \
335 'media-type="application/oebps-package+xml" />' \
336 '</rootfiles></container>')
337 for fname in 'style.css', 'logo_wolnelektury.png':
338 zip.write(res(fname), os.path.join('OPS', fname))
340 opf = xslt(metadata, res('xsltContent.xsl'))
341 manifest = opf.find('.//' + OPFNS('manifest'))
342 spine = opf.find('.//' + OPFNS('spine'))
344 annotations = etree.Element('annotations')
346 toc_file = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><!DOCTYPE ncx PUBLIC ' \
347 '"-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">' \
348 '<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" xml:lang="pl" ' \
349 'version="2005-1"><head></head><docTitle></docTitle><navMap>' \
350 '<navPoint id="NavPoint-1" playOrder="1"><navLabel>' \
351 '<text>Strona tytułowa</text></navLabel><content src="title.html" />' \
352 '</navPoint><navPoint id="NavPoint-2" playOrder="2"><navLabel>' \
353 '<text>Początek utworu</text></navLabel><content src="part1.html" />' \
354 '</navPoint></navMap></ncx>')
355 nav_map = toc_file[-1]
357 toc, chunk_counter = transform_file(input_xml)
358 toc_counter = toc.write_to_xml(nav_map, 3) # we already have 2 navpoints
360 # Last modifications in container files and EPUB creation
361 if len(annotations) > 0:
362 nav_map.append(etree.fromstring(
363 '<navPoint id="NavPoint-%(i)d" playOrder="%(i)d" ><navLabel><text>Przypisy</text>'\
364 '</navLabel><content src="annotations.html" /></navPoint>' % {'i': toc_counter}))
365 manifest.append(etree.fromstring(
366 '<item id="annotations" href="annotations.html" media-type="application/xhtml+xml" />'))
367 spine.append(etree.fromstring(
368 '<itemref idref="annotations" />'))
369 replace_by_verse(annotations)
370 zip.writestr('OPS/annotations.html', etree.tostring(
371 xslt(annotations, res("xsltAnnotations.xsl")), pretty_print=True))
373 zip.writestr('OPS/content.opf', etree.tostring(opf, pretty_print=True))
375 title = node_name(etree.ETXPath('.//'+DCNS('title'))(input_xml)[0])
376 attributes = "dtb:uid", "dtb:depth", "dtb:totalPageCount", "dtb:maxPageNumber"
377 for st in attributes:
378 meta = toc_file.makeelement(NCXNS('meta'))
380 meta.set('content', '0')
381 toc_file[0].append(meta)
382 toc_file[0][0].set('content', ''.join((title, 'WolneLektury.pl')))
383 toc_file[0][1].set('content', str(toc.depth()))
384 set_inner_xml(toc_file[1], ''.join(('<text>', title, '</text>')))
385 zip.writestr('OPS/toc.ncx', etree.tostring(toc_file, pretty_print=True))
389 if __name__ == '__main__':
390 from librarian import DirDocProvider
392 if len(sys.argv) < 2:
393 print >> sys.stderr, 'Usage: python epub.py <input file>'
396 main_input = sys.argv[1]
397 basepath, ext = os.path.splitext(main_input)
398 path, slug = os.path.realpath(basepath).rsplit('/', 1)
399 provider = DirDocProvider(path)
400 transform(provider, slug, output_dir=path)