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 add_anchors(root):
176 for element in root.iterdescendants():
177 if element.getparent().tag in 'div' and 'note' in element.getparent().get('class', ''):
179 if element.getparent().tag in 'blockquote':
182 if element.tag == 'p' and 'verse' in element.get('class', ''):
183 if counter == 1 or counter % 5 == 0:
184 add_anchor(element, counter)
186 elif 'paragraph' in element.get('class', ''):
187 add_anchor(element, counter)
191 def add_table_of_contents(root):
194 for element in root.iterdescendants():
195 if element.tag in ('h2', 'h3'):
196 if element.tag == 'h3' and len(sections) and sections[-1][0] == 'h2':
197 sections[-1][2].append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
199 sections.append((element.tag, ''.join(element.xpath('descendant-or-self::text()')), []))
201 toc = etree.Element('div')
203 toc_header = etree.SubElement(toc, 'h2')
204 toc_header.text = u'Spis treści'
205 toc_list = etree.SubElement(toc, 'ol')
207 for section, text, subsections in sections:
208 section_element = etree.SubElement(toc_list, 'li')
209 section_element.text = text
211 subsection_list = etree.SubElement(section_element, 'ol')
212 for subsection, text, _ in subsections:
213 subsection_element = etree.SubElement(subsection_list, 'li')
214 subsection_element.text = text