1 # -*- coding: utf-8 -*-
8 from librarian.parser import WLDocument
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, output_filename=None, is_file=True):
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)
41 document = WLDocument.from_file(input, True)
43 document = WLDocument.from_string(input, True)
45 result = document.transform(style)
46 del document # no longer needed large object :)
48 if result.find('//p') is not None:
49 add_anchors(result.getroot())
50 add_table_of_contents(result.getroot())
52 if output_filename is not None:
53 result.write(output_filename, xml_declaration=False, 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.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().get('id', None) != 'book-text':
121 parents = [element.getparent()]
122 while parents[-1].getparent().get('id', None) != 'book-text':
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, prefix, with_link=True, with_target=True, link_text=None):
163 if link_text is None:
165 anchor = etree.Element('a', href='#%s' % prefix)
166 anchor.set('class', 'anchor')
167 anchor.text = unicode(link_text)
169 anchor.tail = element.text
171 element.insert(0, anchor)
174 anchor_target = etree.Element('a', name='%s' % prefix)
175 anchor_target.set('class', 'target')
176 anchor_target.text = u' '
178 anchor_target.tail = element.text
180 element.insert(0, anchor_target)
183 def any_ancestor(element, test):
184 for ancestor in element.iterancestors():
190 def add_anchors(root):
192 for element in root.iterdescendants():
193 if any_ancestor(element, lambda e: e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication')
194 or e.tag == 'blockquote'):
197 if element.tag == 'p' and 'verse' in element.get('class', ''):
198 if counter == 1 or counter % 5 == 0:
199 add_anchor(element, "f%d" % counter, link_text=counter)
201 elif 'paragraph' in element.get('class', ''):
202 add_anchor(element, "f%d" % counter, link_text=counter)
206 def add_table_of_contents(root):
209 for element in root.iterdescendants():
210 if element.tag in ('h2', 'h3'):
211 if any_ancestor(element, lambda e: e.get('id') in ('footnotes',) or e.get('class') in ('person-list',)):
214 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
215 sections[-1][3].append((counter, element.tag, ''.join(element.xpath('text()')), []))
217 sections.append((counter, element.tag, ''.join(element.xpath('text()')), []))
218 add_anchor(element, "s%d" % counter, with_link=False)
221 toc = etree.Element('div')
223 toc_header = etree.SubElement(toc, 'h2')
224 toc_header.text = u'Spis treści'
225 toc_list = etree.SubElement(toc, 'ol')
227 for n, section, text, subsections in sections:
228 section_element = etree.SubElement(toc_list, 'li')
229 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
232 subsection_list = etree.SubElement(section_element, 'ol')
233 for n, subsection, text, _ in subsections:
234 subsection_element = etree.SubElement(subsection_list, 'li')
235 add_anchor(subsection_element, "s%d" % n, with_target=False, link_text=text)