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 librarian import ValidationError, NoDublinCore, ParseError
7 from librarian import RDFNS
8 from librarian import dcparser
10 from xml.parsers.expat import ExpatError
11 from lxml import etree
12 from lxml.etree import XMLSyntaxError, XSLTApplyError
15 from StringIO import StringIO
17 class WLDocument(object):
18 LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
20 def __init__(self, edoc, parse_dublincore=True):
23 root_elem = edoc.getroot()
25 dc_path = './/' + RDFNS('RDF')
27 if root_elem.tag != 'utwor':
28 raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
31 self.rdf_elem = root_elem.find(dc_path)
33 if self.rdf_elem is None:
34 raise NoDublinCore('Document has no DublinCore - which is required.')
36 self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
41 def from_string(cls, xml, *args, **kwargs):
42 return cls.from_file(StringIO(xml), *args, **kwargs)
45 def from_file(cls, xmlfile, swap_endlines=False, parse_dublincore=True):
47 # first, prepare for parsing
48 if isinstance(xmlfile, basestring):
49 file = open(xmlfile, 'rb')
57 if not isinstance(data, unicode):
58 data = data.decode('utf-8')
60 data = data.replace(u'\ufeff', '')
63 parser = etree.XMLParser(remove_blank_text=False)
64 tree = etree.parse(StringIO(data.encode('utf-8')), parser)
67 cls.swap_endlines(tree)
69 return cls(tree, parse_dublincore=parse_dublincore)
70 except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
74 def swap_endlines(cls, tree):
75 # only swap inside stanzas
76 for elem in tree.iter('strofa'):
77 for child in list(elem):
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)
87 chunks = cls.LINE_SWAP_EXPR.split(elem.text)
88 while len(chunks) > 1:
89 ins = etree.Element('br')
90 ins.tail = chunks.pop()
92 elem.text = chunks.pop(0)
94 def chunk(self, path):
95 # convert the path to XPath
96 expr = self.path_to_xpath(path)
97 elems = self.edoc.xpath(expr)
104 def path_to_xpath(self, path):
107 for part in path.split('/'):
108 match = re.match(r'([^\[]+)\[(\d+)\]', part)
112 tag, n = match.groups()
113 parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
118 return '/'.join(parts)
120 def transform(self, stylesheet, **options):
121 return self.edoc.xslt(stylesheet, **options)
125 parent = self.rdf_elem.getparent()
126 parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
130 return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)
132 def merge_chunks(self, chunk_dict):
135 for key, data in chunk_dict.iteritems():
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);
142 unmerged.append( repr( (key, xpath, e) ) )
146 def clean_ed_note(self):
147 """ deletes forbidden tags from nota_red """
149 for node in self.edoc.xpath('|'.join('//nota_red//%s' % tag for tag in
150 ('pa', 'pe', 'pr', 'pt', 'begin', 'end', 'motyw'))):