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, number):
166 anchor = etree.Element('a', href='#f%d' % number)
167 anchor.set('class', 'anchor')
168 anchor.text = str(number)
170 anchor.tail = element.text
172 element.insert(0, anchor)
174 anchor_target = etree.Element('a', name='f%d' % number)
175 element.insert(0, anchor_target)
178 def any_ancestor(element, test):
179 for ancestor in element.iterancestors():
185 def add_anchors(root):
187 for element in root.iterdescendants():
188 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
189 or e.tag == 'blockquote'):
192 if element.tag == 'p' and 'verse' in element.get('class', ''):
193 if counter == 1 or counter % 5 == 0:
194 add_anchor(element, counter)
196 elif 'paragraph' in element.get('class', ''):
197 add_anchor(element, counter)
201 def add_table_of_contents(root):
204 for element in root.iterdescendants():
205 if element.tag in ('h2', 'h3'):
206 if any_ancestor(element, lambda e: e.get('id') in ('footnotes')):
209 if element.tag == 'h3' and len(sections) and sections[-1][0] == 'h2':
210 sections[-1][2].append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
212 sections.append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
214 toc = etree.Element('div')
216 toc_header = etree.SubElement(toc, 'h2')
217 toc_header.text = u'Spis treści'
218 toc_list = etree.SubElement(toc, 'ol')
220 for section, text, subsections in sections:
221 section_element = etree.SubElement(toc_list, 'li')
222 section_element.text = text
224 subsection_list = etree.SubElement(section_element, 'ol')
225 for subsection, text, _ in subsections:
226 subsection_element = etree.SubElement(subsection_list, 'li')
227 subsection_element.text = text