1 # -*- coding: utf-8 -*-
11 ENTITY_SUBSTITUTIONS = [
20 def substitute_entities(context, text):
21 """XPath extension function converting all entites in passed text."""
22 if isinstance(text, list):
24 for entity, substitutution in ENTITY_SUBSTITUTIONS:
25 text = text.replace(entity, substitutution)
29 # Register substitute_entities function with lxml
30 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
31 ns['substitute_entities'] = substitute_entities
34 def transform(input_filename, output_filename=None, is_file=True):
35 """Transforms file input_filename in XML to output_filename in XHTML."""
37 style_filename = os.path.join(os.path.dirname(__file__), 'book2html.xslt')
38 style = etree.parse(style_filename)
40 doc_file = cStringIO.StringIO()
41 expr = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
44 f = open(input_filename, 'rb')
45 input_filename = f.read()
48 data = input_filename.decode('utf-8')
49 data = expr.sub(u'<br />\n', data)
50 doc_file.write(data.encode('utf-8'))
53 parser = etree.XMLParser(remove_blank_text=True)
54 doc = etree.parse(doc_file, parser)
56 result = doc.xslt(style)
57 if result.find('//p') is not None:
58 add_anchors(result.getroot())
59 add_table_of_contents(result.getroot())
61 if output_filename is not None:
62 result.write(output_filename, xml_declaration=False, pretty_print=True, encoding='utf-8')
70 class Fragment(object):
71 def __init__(self, id, themes):
72 super(Fragment, self).__init__()
77 def append(self, event, element):
78 self.events.append((event, element))
80 def closed_events(self):
82 for event, element in self.events:
84 stack.append(('end', element))
89 print 'CLOSED NON-OPEN TAG:', element
92 return self.events + stack
96 for event, element in self.closed_events():
98 result.append(u'<%s %s>' % (element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
100 result.append(element.text)
102 result.append(u'</%s>' % element.tag)
104 result.append(element.tail)
106 result.append(element)
108 return ''.join(result)
110 def __unicode__(self):
111 return self.to_string()
114 def extract_fragments(input_filename):
115 """Extracts theme fragments from input_filename."""
117 closed_fragments = {}
119 for event, element in etree.iterparse(input_filename, events=('start', 'end')):
120 # Process begin and end elements
121 if element.get('class', '') in ('theme-begin', 'theme-end'):
122 if not event == 'end': continue # Process elements only once, on end event
125 if element.get('class', '') == 'theme-begin':
126 fragment = Fragment(id=element.get('fid'), themes=element.text)
129 if element.getparent().get('id', None) != 'book-text':
130 parents = [element.getparent()]
131 while parents[-1].getparent().get('id', None) != 'book-text':
132 parents.append(parents[-1].getparent())
135 for parent in parents:
136 fragment.append('start', parent)
138 open_fragments[fragment.id] = fragment
140 # Close existing fragment
143 fragment = open_fragments[element.get('fid')]
145 print '%s:closed not open fragment #%s' % (input_filename, element.get('fid'))
147 closed_fragments[fragment.id] = fragment
148 del open_fragments[fragment.id]
150 # Append element tail to lost_text (we don't want to lose any text)
152 for fragment_id in open_fragments:
153 open_fragments[fragment_id].append('text', element.tail)
156 # Process all elements except begin and end
158 # Omit annotation tags
159 if len(element.get('name', '')) or element.get('class', '') == 'annotation':
160 if event == 'end' and element.tail:
161 for fragment_id in open_fragments:
162 open_fragments[fragment_id].append('text', element.tail)
164 for fragment_id in open_fragments:
165 open_fragments[fragment_id].append(event, copy.copy(element))
167 return closed_fragments, open_fragments
170 def add_anchor(element, prefix, with_link=True, with_target=True, link_text=None):
172 if link_text is None:
174 anchor = etree.Element('a', href='#%s' % prefix)
175 anchor.set('class', 'anchor')
176 anchor.text = unicode(link_text)
178 anchor.tail = element.text
180 element.insert(0, anchor)
183 anchor_target = etree.Element('a', name='%s' % prefix)
184 anchor_target.set('class', 'target')
185 anchor_target.text = u' '
187 anchor_target.tail = element.text
189 element.insert(0, anchor_target)
192 def any_ancestor(element, test):
193 for ancestor in element.iterancestors():
199 def add_anchors(root):
201 for element in root.iterdescendants():
202 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
203 or e.tag == 'blockquote'):
206 if element.tag == 'p' and 'verse' in element.get('class', ''):
207 if counter == 1 or counter % 5 == 0:
208 add_anchor(element, "f%d" % counter, link_text=counter)
210 elif 'paragraph' in element.get('class', ''):
211 add_anchor(element, "f%d" % counter, link_text=counter)
215 def add_table_of_contents(root):
218 for element in root.iterdescendants():
219 if element.tag in ('h2', 'h3'):
220 if any_ancestor(element, lambda e: e.get('id') in ('footnotes',) or e.get('class') in ('person-list',)):
223 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
224 sections[-1][3].append((counter, element.tag, ''.join(element.xpath('text()')), []))
226 sections.append((counter, element.tag, ''.join(element.xpath('text()')), []))
227 add_anchor(element, "s%d" % counter, with_link=False)
230 toc = etree.Element('div')
232 toc_header = etree.SubElement(toc, 'h2')
233 toc_header.text = u'Spis treści'
234 toc_list = etree.SubElement(toc, 'ol')
236 for n, section, text, subsections in sections:
237 section_element = etree.SubElement(toc_list, 'li')
238 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
241 subsection_list = etree.SubElement(section_element, 'ol')
242 for n, subsection, text, _ in subsections:
243 subsection_element = etree.SubElement(subsection_list, 'li')
244 add_anchor(subsection_element, "s%d" % n, with_target=False, link_text=text)