minor fix
[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, preserve_lines=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         if swap_endlines:
63             sub = u'<br/>'
64             if preserve_lines:
65                 sub += u'\n'
66             data = cls.LINE_SWAP_EXPR.sub(sub, data)
67
68         try:
69             parser = etree.XMLParser(remove_blank_text=False)
70             return cls(etree.parse(StringIO(data), parser), parse_dublincore=parse_dublincore)
71         except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
72             raise ParseError(e)
73
74     def chunk(self, path):
75         # convert the path to XPath
76         expr = self.path_to_xpath(path)
77         elems = self.edoc.xpath(expr)
78
79         if len(elems) == 0:
80             return None
81         else:
82             return elems[0]
83
84     def path_to_xpath(self, path):
85         parts = []
86
87         for part in path.split('/'):
88             match = re.match(r'([^\[]+)\[(\d+)\]', part)
89             if not match:
90                 parts.append(part)
91             else:
92                 tag, n = match.groups()
93                 parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
94
95         if parts[0] == '.':
96             parts[0] = ''
97
98         return '/'.join(parts)
99
100     def transform(self, stylesheet, **options):
101         return self.edoc.xslt(stylesheet, **options)
102
103     def update_dc(self):
104         if self.book_info:
105             parent = self.rdf_elem.getparent()
106             parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
107
108     def serialize(self):
109         self.update_dc()
110         return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)
111
112     def merge_chunks(self, chunk_dict):
113         unmerged = []
114
115         for key, data in chunk_dict.iteritems():
116             try:
117                 xpath = self.path_to_xpath(key)
118                 node = self.edoc.xpath(xpath)[0]
119                 repl = etree.fromstring(u"<%s>%s</%s>" %(node.tag, data, node.tag) )
120                 node.getparent().replace(node, repl);
121             except Exception, e:
122                 unmerged.append( repr( (key, xpath, e) ) )
123
124         return unmerged
125
126     def clean_ed_note(self):
127         """ deletes forbidden tags from nota_red """
128
129         for node in self.edoc.xpath('|'.join('//nota_red//%s' % tag for tag in
130                     ('pa', 'pe', 'pr', 'pt', 'begin', 'end', 'motyw'))):
131             tail = node.tail
132             node.clear()
133             node.tag = 'span'
134             node.tail = tail