84a745fc675a163c9132a474429fdded71e9f0e3
[librarian.git] / librarian / epub.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.  
5 #
6 from __future__ import with_statement
7
8 import os
9 import os.path
10 from copy import deepcopy
11 from lxml import etree
12 import zipfile
13
14 import sys
15 sys.path.append('..') # for running from working copy
16
17 from librarian import XMLNamespace, RDFNS, DCNS, WLNS, NCXNS, OPFNS, NoDublinCore
18 from librarian.dcparser import BookInfo
19
20
21 def inner_xml(node):
22     """ returns node's text and children as a string
23
24     >>> print inner_xml(etree.fromstring('<a>x<b>y</b>z</a>'))
25     x<b>y</b>z
26     """
27
28     nt = node.text if node.text is not None else ''
29     return ''.join([nt] + [etree.tostring(child) for child in node]) 
30
31 def set_inner_xml(node, text):
32     """ sets node's text and children from a string
33
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)
37     <a>x<b>y</b>z</a>
38     """
39
40     p = etree.fromstring('<x>%s</x>' % text)
41     node.text = p.text
42     node[:] = p[:]
43
44
45 def node_name(node):
46     """ Find out a node's name
47
48     >>> print node_name(etree.fromstring('<a>X<b>Y</b>Z</a>'))
49     XYZ
50     """
51
52     tempnode = deepcopy(node)
53
54     for p in ('pe', 'pa', 'pt', 'pr', 'motyw'):
55         for e in tempnode.findall('.//%s' % p):
56             t = e.tail
57             e.clear()
58             e.tail = t
59     etree.strip_tags(tempnode, '*')
60     return tempnode.text
61
62
63 def xslt(xml, sheet):
64     if isinstance(xml, etree._Element):
65         xml = etree.ElementTree(xml)
66     with open(sheet) as xsltf:
67         return xml.xslt(etree.parse(xsltf))
68
69
70 _resdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'epub')
71 def res(fname):
72     return os.path.join(_resdir, fname)
73
74
75 def replace_characters(node):
76     def replace_chars(text):
77         if text is None:
78             return None
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':
85         node.clear()
86     else:
87         node.text = replace_chars(node.text)
88         node.tail = replace_chars(node.tail)
89         for child in node:
90             replace_characters(child)
91
92
93 def find_annotations(annotations, source, part_no):
94     for child in source:
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))
100             annotation.tail = ''
101             annotations.append(annotation)
102             tail = child.tail
103             child.clear()
104             child.tail = tail
105             child.text = number
106         if child.tag not in ('extra', 'podtytul'):
107             find_annotations(annotations, child, part_no)
108
109
110 def replace_by_verse(tree):
111     """ Find stanzas and create new verses in place of a '/' character """
112
113     stanzas = tree.findall('.//' + WLNS('strofa'))
114     for node in stanzas:
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:
119                     new_foreign = ''
120                     for foreign_verse in foreign_verses:
121                         if foreign_verse.startswith('<wers'):
122                             new_foreign += foreign_verse
123                         else:
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')
127         if len(verses) > 1:
128             modified_inner_xml = ''
129             for verse in verses:
130                 if verse.startswith('<wers') or verse.startswith('<extra'):
131                     modified_inner_xml += verse
132                 else:
133                     modified_inner_xml += ''.join(('<wers_normalny>', verse, '</wers_normalny>'))
134             set_inner_xml(node, modified_inner_xml)
135
136
137 def add_to_manifest(manifest, partno):
138     """ Adds a node to the manifest section in content.opf file """
139
140     partstr = 'part%d' % partno
141     e = manifest.makeelement(OPFNS('item'), attrib={
142                                  'id': partstr,
143                                  'href': partstr + '.html',
144                                  'media-type': 'application/xhtml+xml',
145                              })
146     manifest.append(e)
147
148
149 def add_to_spine(spine, partno):
150     """ Adds a node to the spine section in content.opf file """
151
152     e = spine.makeelement(OPFNS('itemref'), attrib={'idref': 'part%d' % partno});
153     spine.append(e)
154
155
156 class TOC(object):
157     def __init__(self, name=None, part_number=None):
158         self.children = []
159         self.name = name
160         self.part_number = part_number
161         self.sub_number = None
162
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)
166         else:
167             t = TOC(name)
168             t.part_number = part_number
169             self.children.append(t)
170             if not is_part:
171                 t.sub_number = len(self.children) + 1
172                 return t.sub_number
173
174     def append(self, toc):
175         self.children.append(toc)
176
177     def extend(self, toc):
178         self.children.extend(toc.children)
179
180     def depth(self):
181         if self.children:
182             return max((c.depth() for c in self.children)) + 1
183         else:
184             return 0
185
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))
191
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)
197
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)
206         return counter
207
208
209 def chop(main_text):
210     """ divide main content of the XML file into chunks """
211
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
216
217     last_node_part = False
218     for one_part in main_text:
219         name = one_part.tag
220         if name == 'naglowek_czesc':
221             yield part_xml
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"):
225             yield part_xml
226             main_xml_part[:] = [deepcopy(one_part)]
227         else:
228             main_xml_part.append(deepcopy(one_part))
229             last_node_part = False
230     yield part_xml
231
232
233 def transform_chunk(chunk_xml, chunk_no, annotations):
234     """ transforms one chunk, returns a HTML string and a TOC object """
235
236     toc = TOC()
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
247
248
249 def transform(provider, slug, output_file=None, output_dir=None):
250     """ produces an epub
251
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
255     """
256
257     def transform_file(input_xml, chunk_counter=1, first=True):
258         """ processes one input file and proceeds to its children """
259
260         children = [child.text for child in input_xml.findall('.//'+DCNS('relation.hasPart'))]
261
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)
265         if first:
266             # write book title page
267             zip.writestr('OPS/title.html',
268                  etree.tostring(xslt(input_xml, res('xsltTitle.xsl')), pretty_print=True))
269         elif children:
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)
275             chunk_counter += 1
276
277         if len(input_xml.getroot()) > 1:
278             # rdf before style master
279             main_text = input_xml.getroot()[1]
280         else:
281             # rdf in style master
282             main_text = input_xml.getroot()[0]
283             if main_text.tag == RDFNS('RDF'):
284                 main_text = None
285
286         if main_text is not None:
287             replace_characters(main_text)
288
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)
295                 chunk_counter += 1
296
297         if children:
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)
302
303         return toc, chunk_counter
304
305     # read metadata from the first file
306     input_xml = etree.parse(provider[slug])
307     metadata = input_xml.find('.//'+RDFNS('Description'))
308     if metadata is None:
309         raise NoDublinCore('Document has no DublinCore - which is required.')
310     book_info = BookInfo.from_element(input_xml)
311     metadata = etree.ElementTree(metadata)
312
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)
317         try:
318             os.makedirs(author_dir)
319         except OSError:
320             pass
321         output_file = open(os.path.join(author_dir, '%s.epub' % slug), 'w')
322
323
324     zip = zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED)
325
326     # write static elements
327     mime = zipfile.ZipInfo()
328     mime.filename = 'mimetype'
329     mime.compress_type = zipfile.ZIP_STORED
330     mime.extra = ''
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))
339
340     opf = xslt(metadata, res('xsltContent.xsl'))
341     manifest = opf.find('.//' + OPFNS('manifest'))
342     spine = opf.find('.//' + OPFNS('spine'))
343
344     annotations = etree.Element('annotations')
345
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></navMap></ncx>')
353     nav_map = toc_file[-1]
354
355     toc, chunk_counter = transform_file(input_xml)
356     if not toc.children:
357         toc.add(u"Początek utworu", 1)
358     toc_counter = toc.write_to_xml(nav_map, 2)
359
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))
372
373     zip.writestr('OPS/content.opf', etree.tostring(opf, pretty_print=True))
374     contents = []
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'))
379         meta.set('name', st)
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))
386     zip.close()
387
388
389 if __name__ == '__main__':
390     from librarian import DirDocProvider
391
392     if len(sys.argv) < 2:
393         print >> sys.stderr, 'Usage: python epub.py <input file>'
394         sys.exit(1)
395
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)
401