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):
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);
43 f = open(input_filename, 'r')
45 line = line.decode('utf-8')
46 line = expr.sub(u'<br/>\n', line)
47 doc_file.write(line.encode('utf-8'))
52 parser = etree.XMLParser(remove_blank_text=True)
53 doc = etree.parse(doc_file, parser)
55 result = doc.xslt(style)
57 if result.find('//div') is not None:
58 add_anchors(result.getroot())
59 add_table_of_contents(result.getroot())
60 result.write(output_filename, xml_declaration=False, pretty_print=True, encoding='utf-8')
66 class Fragment(object):
67 def __init__(self, id, themes):
68 super(Fragment, self).__init__()
73 def append(self, event, element):
74 self.events.append((event, element))
76 def closed_events(self):
78 for event, element in self.events:
80 stack.append(('end', element))
85 print 'CLOSED NON-OPEN TAG:', element
88 return self.events + stack
92 for event, element in self.closed_events():
94 result.append(u'<%s %s>' % (element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
96 result.append(element.text)
98 result.append(u'</%s>' % element.tag)
100 result.append(element.tail)
102 result.append(element)
104 return ''.join(result)
106 def __unicode__(self):
107 return self.to_string()
110 def extract_fragments(input_filename):
111 """Extracts theme fragments from input_filename."""
113 closed_fragments = {}
115 for event, element in etree.iterparse(input_filename, events=('start', 'end')):
116 # Process begin and end elements
117 if element.get('class', '') in ('theme-begin', 'theme-end'):
118 if not event == 'end': continue # Process elements only once, on end event
121 if element.get('class', '') == 'theme-begin':
122 fragment = Fragment(id=element.get('fid'), themes=element.text)
125 if element.getparent().get('id', None) != 'book-text':
126 parents = [element.getparent()]
127 while parents[-1].getparent().get('id', None) != 'book-text':
128 parents.append(parents[-1].getparent())
131 for parent in parents:
132 fragment.append('start', parent)
134 open_fragments[fragment.id] = fragment
136 # Close existing fragment
139 fragment = open_fragments[element.get('fid')]
141 print '%s:closed not open fragment #%s' % (input_filename, element.get('fid'))
143 closed_fragments[fragment.id] = fragment
144 del open_fragments[fragment.id]
146 # Append element tail to lost_text (we don't want to lose any text)
148 for fragment_id in open_fragments:
149 open_fragments[fragment_id].append('text', element.tail)
152 # Process all elements except begin and end
154 # Omit annotation tags
155 if len(element.get('name', '')) or element.get('class', '') == 'annotation':
156 if event == 'end' and element.tail:
157 for fragment_id in open_fragments:
158 open_fragments[fragment_id].append('text', element.tail)
160 for fragment_id in open_fragments:
161 open_fragments[fragment_id].append(event, copy.copy(element))
163 return closed_fragments, open_fragments
166 def add_anchor(element, prefix, with_link=True, with_target=True, link_text=None):
168 if link_text is None:
170 anchor = etree.Element('a', href='#%s' % prefix)
171 anchor.set('class', 'anchor')
172 anchor.text = unicode(link_text)
174 anchor.tail = element.text
176 element.insert(0, anchor)
179 anchor_target = etree.Element('a', name='%s' % prefix)
180 anchor_target.set('class', 'target')
181 anchor_target.text = u' '
183 anchor_target.tail = element.text
185 element.insert(0, anchor_target)
188 def any_ancestor(element, test):
189 for ancestor in element.iterancestors():
195 def add_anchors(root):
197 for element in root.iterdescendants():
198 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
199 or e.tag == 'blockquote'):
202 if element.tag == 'p' and 'verse' in element.get('class', ''):
203 if counter == 1 or counter % 5 == 0:
204 add_anchor(element, "f%d" % counter, link_text=counter)
206 elif 'paragraph' in element.get('class', ''):
207 add_anchor(element, "f%d" % counter, link_text=counter)
211 def add_table_of_contents(root):
214 for element in root.iterdescendants():
215 if element.tag in ('h2', 'h3'):
216 if any_ancestor(element, lambda e: e.get('id') in ('footnotes',) or e.get('class') in ('person-list',)):
219 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
220 sections[-1][3].append((counter, element.tag, ''.join(element.xpath('text()')), []))
222 sections.append((counter, element.tag, ''.join(element.xpath('text()')), []))
223 add_anchor(element, "s%d" % counter, with_link=False)
226 toc = etree.Element('div')
228 toc_header = etree.SubElement(toc, 'h2')
229 toc_header.text = u'Spis treści'
230 toc_list = etree.SubElement(toc, 'ol')
232 for n, section, text, subsections in sections:
233 section_element = etree.SubElement(toc_list, 'li')
234 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
237 subsection_list = etree.SubElement(section_element, 'ol')
238 for n, subsection, text, _ in subsections:
239 subsection_element = etree.SubElement(subsection_list, 'li')
240 add_anchor(subsection_element, "s%d" % n, with_target=False, link_text=text)