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)
56 if result.find('//h1') is not None:
57 add_anchors(result.getroot())
58 add_table_of_contents(result.getroot())
59 result.write(output_filename, xml_declaration=False, pretty_print=True, encoding='utf-8')
65 class Fragment(object):
66 def __init__(self, id, themes):
67 super(Fragment, self).__init__()
72 def append(self, event, element):
73 self.events.append((event, element))
75 def closed_events(self):
77 for event, element in self.events:
79 stack.append(('end', element))
84 print 'CLOSED NON-OPEN TAG:', element
87 return self.events + stack
91 for event, element in self.closed_events():
93 result.append(u'<%s %s>' % (element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
95 result.append(element.text)
97 result.append(u'</%s>' % element.tag)
99 result.append(element.tail)
101 result.append(element)
103 return ''.join(result)
105 def __unicode__(self):
106 return self.to_string()
109 def extract_fragments(input_filename):
110 """Extracts theme fragments from input_filename."""
112 closed_fragments = {}
114 for event, element in etree.iterparse(input_filename, events=('start', 'end')):
115 # Process begin and end elements
116 if element.get('class', '') in ('theme-begin', 'theme-end'):
117 if not event == 'end': continue # Process elements only once, on end event
120 if element.get('class', '') == 'theme-begin':
121 fragment = Fragment(id=element.get('fid'), themes=element.text)
124 if element.getparent().get('id', None) != 'book-text':
125 parents = [element.getparent()]
126 while parents[-1].getparent().get('id', None) != 'book-text':
127 parents.append(parents[-1].getparent())
130 for parent in parents:
131 fragment.append('start', parent)
133 open_fragments[fragment.id] = fragment
135 # Close existing fragment
138 fragment = open_fragments[element.get('fid')]
140 print '%s:closed not open fragment #%s' % (input_filename, element.get('fid'))
142 closed_fragments[fragment.id] = fragment
143 del open_fragments[fragment.id]
145 # Append element tail to lost_text (we don't want to lose any text)
147 for fragment_id in open_fragments:
148 open_fragments[fragment_id].append('text', element.tail)
151 # Process all elements except begin and end
153 # Omit annotation tags
154 if len(element.get('name', '')) or element.get('class', '') == 'annotation':
155 if event == 'end' and element.tail:
156 for fragment_id in open_fragments:
157 open_fragments[fragment_id].append('text', element.tail)
159 for fragment_id in open_fragments:
160 open_fragments[fragment_id].append(event, copy.copy(element))
162 return closed_fragments, open_fragments
165 def add_anchor(element, prefix, with_link=True, with_target=True, link_text=None):
167 if link_text is None:
169 anchor = etree.Element('a', href='#%s' % prefix)
170 anchor.set('class', 'anchor')
171 anchor.text = unicode(link_text)
173 anchor.tail = element.text
175 element.insert(0, anchor)
178 anchor_target = etree.Element('a', name='%s' % prefix)
179 anchor_target.set('class', 'target')
180 anchor_target.text = u' '
182 anchor_target.tail = element.text
184 element.insert(0, anchor_target)
187 def any_ancestor(element, test):
188 for ancestor in element.iterancestors():
194 def add_anchors(root):
196 for element in root.iterdescendants():
197 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
198 or e.tag == 'blockquote'):
201 if element.tag == 'p' and 'verse' in element.get('class', ''):
202 if counter == 1 or counter % 5 == 0:
203 add_anchor(element, "f%d" % counter, link_text=counter)
205 elif 'paragraph' in element.get('class', ''):
206 add_anchor(element, "f%d" % counter, link_text=counter)
210 def add_table_of_contents(root):
213 for element in root.iterdescendants():
214 if element.tag in ('h2', 'h3'):
215 if any_ancestor(element, lambda e: e.get('id') in ('footnotes',) or e.get('class') in ('person-list',)):
218 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
219 sections[-1][3].append((counter, element.tag, ''.join(element.xpath('text()')), []))
221 sections.append((counter, element.tag, ''.join(element.xpath('text()')), []))
222 add_anchor(element, "s%d" % counter, with_link=False)
225 toc = etree.Element('div')
227 toc_header = etree.SubElement(toc, 'h2')
228 toc_header.text = u'Spis treści'
229 toc_list = etree.SubElement(toc, 'ol')
231 for n, section, text, subsections in sections:
232 section_element = etree.SubElement(toc_list, 'li')
233 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
236 subsection_list = etree.SubElement(section_element, 'ol')
237 for n, subsection, text, _ in subsections:
238 subsection_element = etree.SubElement(subsection_list, 'li')
239 add_anchor(subsection_element, "s%d" % n, with_target=False, link_text=text)