#1032: epubs for virtualo
[librarian.git] / librarian / parser.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 librarian import ValidationError, NoDublinCore,  ParseError
7 from librarian import RDFNS
8 from librarian import dcparser
9
10 from xml.parsers.expat import ExpatError
11 from lxml import etree
12 from lxml.etree import XMLSyntaxError, XSLTApplyError
13
14 import re
15 from StringIO import StringIO
16
17 class WLDocument(object):
18     LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
19
20     def __init__(self, edoc, parse_dublincore=True):
21         self.edoc = edoc
22
23         root_elem = edoc.getroot()
24
25         dc_path = './/' + RDFNS('RDF')
26
27         if root_elem.tag != 'utwor':
28             raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
29
30         if parse_dublincore:
31             self.rdf_elem = root_elem.find(dc_path)
32
33             if self.rdf_elem is None:
34                 raise NoDublinCore('Document has no DublinCore - which is required.')
35
36             self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
37         else:
38             self.book_info = None
39
40     @classmethod
41     def from_string(cls, xml, *args, **kwargs):
42         return cls.from_file(StringIO(xml), *args, **kwargs)
43
44     @classmethod
45     def from_file(cls, xmlfile, swap_endlines=False, parse_dublincore=True):
46
47         # first, prepare for parsing
48         if isinstance(xmlfile, basestring):
49             file = open(xmlfile, 'rb')
50             try:
51                 data = file.read()
52             finally:
53                 file.close()
54         else:
55             data = xmlfile.read()
56
57         if not isinstance(data, unicode):
58             data = data.decode('utf-8')
59
60         data = data.replace(u'\ufeff', '')
61
62         try:
63             parser = etree.XMLParser(remove_blank_text=False)
64             tree = etree.parse(StringIO(data), parser)
65
66             if swap_endlines:
67                 cls.swap_endlines(tree)
68
69             return cls(tree, parse_dublincore=parse_dublincore)
70         except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
71             raise ParseError(e)
72
73     @classmethod
74     def swap_endlines(cls, tree):
75         # only swap inside stanzas
76         for elem in tree.iter('strofa'):
77             for child in list(elem):
78                 if child.tail:
79                     chunks = cls.LINE_SWAP_EXPR.split(child.tail)
80                     ins_index = elem.index(child) + 1
81                     while len(chunks) > 1:
82                         ins = etree.Element('br')
83                         ins.tail = chunks.pop()
84                         elem.insert(ins_index, ins)
85                     child.tail = chunks.pop(0)
86             if elem.text:
87                 chunks = cls.LINE_SWAP_EXPR.split(elem.text)
88                 while len(chunks) > 1:
89                     ins = etree.Element('br')
90                     ins.tail = chunks.pop()
91                     elem.insert(0, ins)
92                 elem.text = chunks.pop(0)
93
94     def chunk(self, path):
95         # convert the path to XPath
96         expr = self.path_to_xpath(path)
97         elems = self.edoc.xpath(expr)
98
99         if len(elems) == 0:
100             return None
101         else:
102             return elems[0]
103
104     def path_to_xpath(self, path):
105         parts = []
106
107         for part in path.split('/'):
108             match = re.match(r'([^\[]+)\[(\d+)\]', part)
109             if not match:
110                 parts.append(part)
111             else:
112                 tag, n = match.groups()
113                 parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
114
115         if parts[0] == '.':
116             parts[0] = ''
117
118         return '/'.join(parts)
119
120     def transform(self, stylesheet, **options):
121         return self.edoc.xslt(stylesheet, **options)
122
123     def update_dc(self):
124         if self.book_info:
125             parent = self.rdf_elem.getparent()
126             parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
127
128     def serialize(self):
129         self.update_dc()
130         return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)
131
132     def merge_chunks(self, chunk_dict):
133         unmerged = []
134
135         for key, data in chunk_dict.iteritems():
136             try:
137                 xpath = self.path_to_xpath(key)
138                 node = self.edoc.xpath(xpath)[0]
139                 repl = etree.fromstring(u"<%s>%s</%s>" %(node.tag, data, node.tag) )
140                 node.getparent().replace(node, repl);
141             except Exception, e:
142                 unmerged.append( repr( (key, xpath, e) ) )
143
144         return unmerged
145
146     def clean_ed_note(self):
147         """ deletes forbidden tags from nota_red """
148
149         for node in self.edoc.xpath('|'.join('//nota_red//%s' % tag for tag in
150                     ('pa', 'pe', 'pr', 'pt', 'begin', 'end', 'motyw'))):
151             tail = node.tail
152             node.clear()
153             node.tag = 'span'
154             node.tail = tail