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 add_anchors(result.getroot())
57 add_table_of_contents(result.getroot())
58 result.write(output_filename, xml_declaration=True, pretty_print=True, encoding='utf-8')
61 class Fragment(object):
62 def __init__(self, id, themes):
63 super(Fragment, self).__init__()
68 def append(self, event, element):
69 self.events.append((event, element))
71 def closed_events(self):
73 for event, element in self.events:
75 stack.append(('end', element))
80 print 'CLOSED NON-OPEN TAG:', element
83 return self.events + stack
87 for event, element in self.closed_events():
89 result.append(u'<%s %s>' % (element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
91 result.append(element.text)
93 result.append(u'</%s>' % element.tag)
95 result.append(element.tail)
97 result.append(element)
99 return ''.join(result)
101 def __unicode__(self):
102 return self.to_string()
105 def extract_fragments(input_filename):
106 """Extracts theme fragments from input_filename."""
108 closed_fragments = {}
110 for event, element in etree.iterparse(input_filename, events=('start', 'end')):
111 # Process begin and end elements
112 if element.tag == 'span' and element.get('class', '') in ('theme-begin', 'theme-end'):
113 if not event == 'end': continue # Process elements only once, on end event
116 if element.get('class', '') == 'theme-begin':
117 fragment = Fragment(id=element.get('fid'), themes=element.text)
120 if element.getparent().tag != 'body':
121 parents = [element.getparent()]
122 while parents[-1].getparent().tag != 'body':
123 parents.append(parents[-1].getparent())
126 for parent in parents:
127 fragment.append('start', parent)
129 open_fragments[fragment.id] = fragment
131 # Close existing fragment
134 fragment = open_fragments[element.get('fid')]
136 print '%s:closed not open fragment #%s' % (input_filename, element.get('fid'))
138 closed_fragments[fragment.id] = fragment
139 del open_fragments[fragment.id]
141 # Append element tail to lost_text (we don't want to lose any text)
143 for fragment_id in open_fragments:
144 open_fragments[fragment_id].append('text', element.tail)
147 # Process all elements except begin and end
149 # Omit annotation tags
150 if len(element.get('name', '')) or element.get('class', '') == 'annotation':
151 if event == 'end' and element.tail:
152 for fragment_id in open_fragments:
153 open_fragments[fragment_id].append('text', element.tail)
155 for fragment_id in open_fragments:
156 open_fragments[fragment_id].append(event, copy.copy(element))
158 return closed_fragments, open_fragments
161 def add_anchor(element, number):
162 anchor = etree.Element('a', href='#f%d' % number)
163 anchor.set('class', 'anchor')
164 anchor.text = str(number)
166 anchor.tail = element.text
168 element.insert(0, anchor)
170 anchor_target = etree.Element('a', name='f%d' % number)
171 element.insert(0, anchor_target)
174 def any_ancestor(element, test):
175 for ancestor in element.iterancestors():
181 def add_anchors(root):
183 for element in root.iterdescendants():
184 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
185 or e.tag == 'blockquote'):
188 if element.tag == 'p' and 'verse' in element.get('class', ''):
189 if counter == 1 or counter % 5 == 0:
190 add_anchor(element, counter)
192 elif 'paragraph' in element.get('class', ''):
193 add_anchor(element, counter)
197 def add_table_of_contents(root):
200 for element in root.iterdescendants():
201 if element.tag in ('h2', 'h3'):
202 if element.tag == 'h3' and len(sections) and sections[-1][0] == 'h2':
203 sections[-1][2].append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
205 sections.append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
207 toc = etree.Element('div')
209 toc_header = etree.SubElement(toc, 'h2')
210 toc_header.text = u'Spis treści'
211 toc_list = etree.SubElement(toc, 'ol')
213 for section, text, subsections in sections:
214 section_element = etree.SubElement(toc_list, 'li')
215 section_element.text = text
217 subsection_list = etree.SubElement(section_element, 'ol')
218 for subsection, text, _ in subsections:
219 subsection_element = etree.SubElement(subsection_list, 'li')
220 subsection_element.text = text