1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import print_function, unicode_literals
12 from lxml import etree
13 from librarian import XHTMLNS, ParseError, OutputFile
14 from librarian import functions
16 from lxml.etree import XMLSyntaxError, XSLTApplyError
20 functions.reg_substitute_entities()
21 functions.reg_person_name()
24 'legacy': 'xslt/book2html.xslt',
25 'full': 'xslt/wl2html_full.xslt',
26 'partial': 'xslt/wl2html_partial.xslt'
30 def get_stylesheet(name):
31 return os.path.join(os.path.dirname(__file__), STYLESHEETS[name])
34 def html_has_content(text):
35 return etree.ETXPath('//p|//{%(ns)s}p|//h1|//{%(ns)s}h1' % {'ns': str(XHTMLNS)})(text)
38 def transform_abstrakt(abstrakt_element):
39 style_filename = get_stylesheet('legacy')
40 style = etree.parse(style_filename)
41 xml = etree.tostring(abstrakt_element)
42 document = etree.parse(six.BytesIO(xml.replace('abstrakt', 'dlugi_cytat'))) # HACK
43 result = document.xslt(style)
44 html = re.sub('<a name="sec[0-9]*"/>', '', etree.tostring(result))
45 return re.sub('</?blockquote[^>]*>', '', html)
48 def transform(wldoc, stylesheet='legacy', options=None, flags=None):
49 """Transforms the WL document to XHTML.
51 If output_filename is None, returns an XML,
52 otherwise returns True if file has been written,False if it hasn't.
53 File won't be written if it has no content.
57 style_filename = get_stylesheet(stylesheet)
58 style = etree.parse(style_filename)
60 document = copy.deepcopy(wldoc)
62 document.swap_endlines()
66 document.edoc.getroot().set(flag, 'yes')
68 document.clean_ed_note()
69 document.clean_ed_note('abstrakt')
73 options.setdefault('gallery', "''")
74 result = document.transform(style, **options)
75 del document # no longer needed large object :)
77 if html_has_content(result):
78 add_anchors(result.getroot())
79 add_table_of_themes(result.getroot())
80 add_table_of_contents(result.getroot())
82 return OutputFile.from_bytes(etree.tostring(
83 result, method='html', xml_declaration=False, pretty_print=True, encoding='utf-8'))
87 raise ValueError("'%s' is not a valid stylesheet.")
88 except (XMLSyntaxError, XSLTApplyError) as e:
92 @six.python_2_unicode_compatible
93 class Fragment(object):
94 def __init__(self, id, themes):
95 super(Fragment, self).__init__()
100 def append(self, event, element):
101 self.events.append((event, element))
103 def closed_events(self):
105 for event, element in self.events:
107 stack.append(('end', element))
112 print('CLOSED NON-OPEN TAG:', element)
115 return self.events + stack
119 for event, element in self.closed_events():
121 result.append(u'<%s %s>' % (
122 element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
124 result.append(element.text)
126 result.append(u'</%s>' % element.tag)
128 result.append(element.tail)
130 result.append(element)
132 return ''.join(result)
135 return self.to_string()
138 def extract_fragments(input_filename):
139 """Extracts theme fragments from input_filename."""
141 closed_fragments = {}
143 # iterparse would die on a HTML document
144 parser = etree.HTMLParser(encoding='utf-8')
146 buf.write(etree.tostring(etree.parse(input_filename, parser).getroot()[0][0], encoding='utf-8'))
149 for event, element in etree.iterparse(buf, events=('start', 'end')):
150 # Process begin and end elements
151 if element.get('class', '') in ('theme-begin', 'theme-end'):
152 if not event == 'end':
153 continue # Process elements only once, on end event
156 if element.get('class', '') == 'theme-begin':
157 fragment = Fragment(id=element.get('fid'), themes=element.text)
160 parent = element.getparent()
162 while parent.get('id', None) != 'book-text':
163 cparent = copy.deepcopy(parent)
165 parents.append(cparent)
166 parent = parent.getparent()
169 for parent in parents:
170 fragment.append('start', parent)
172 open_fragments[fragment.id] = fragment
174 # Close existing fragment
177 fragment = open_fragments[element.get('fid')]
179 print('%s:closed not open fragment #%s' % (input_filename, element.get('fid')))
181 closed_fragments[fragment.id] = fragment
182 del open_fragments[fragment.id]
184 # Append element tail to lost_text (we don't want to lose any text)
186 for fragment_id in open_fragments:
187 open_fragments[fragment_id].append('text', element.tail)
189 # Process all elements except begin and end
191 # Omit annotation tags
192 if (len(element.get('name', '')) or
193 element.get('class', '') in ('annotation', 'anchor')):
194 if event == 'end' and element.tail:
195 for fragment_id in open_fragments:
196 open_fragments[fragment_id].append('text', element.tail)
198 for fragment_id in open_fragments:
199 open_fragments[fragment_id].append(event, copy.copy(element))
201 return closed_fragments, open_fragments
204 def add_anchor(element, prefix, with_link=True, with_target=True, link_text=None):
205 parent = element.getparent()
206 index = parent.index(element)
209 if link_text is None:
211 anchor = etree.Element('a', href='#%s' % prefix)
212 anchor.set('class', 'anchor')
213 anchor.text = six.text_type(link_text)
214 parent.insert(index, anchor)
217 anchor_target = etree.Element('a', name='%s' % prefix)
218 anchor_target.set('class', 'target')
219 anchor_target.text = u' '
220 parent.insert(index, anchor_target)
223 def any_ancestor(element, test):
224 for ancestor in element.iterancestors():
230 def add_anchors(root):
232 for element in root.iterdescendants():
234 return e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication', 'frame') or \
235 e.get('id') == 'nota_red' or e.tag == 'blockquote'
236 if any_ancestor(element, f):
239 if element.tag == 'p' and 'verse' in element.get('class', ''):
240 if counter == 1 or counter % 5 == 0:
241 add_anchor(element, "f%d" % counter, link_text=counter)
243 elif 'paragraph' in element.get('class', ''):
244 add_anchor(element, "f%d" % counter, link_text=counter)
248 def raw_printable_text(element):
249 working = copy.deepcopy(element)
250 for e in working.findall('a'):
251 if e.get('class') in ('annotation', 'theme-begin'):
253 return etree.tostring(working, method='text', encoding='unicode').strip()
256 def add_table_of_contents(root):
259 for element in root.iterdescendants():
260 if element.tag in ('h2', 'h3'):
261 if any_ancestor(element,
262 lambda e: e.get('id') in ('footnotes', 'nota_red') or e.get('class') in ('person-list',)):
265 element_text = raw_printable_text(element)
266 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
267 sections[-1][3].append((counter, element.tag, element_text, []))
269 sections.append((counter, element.tag, element_text, []))
270 add_anchor(element, "s%d" % counter, with_link=False)
273 toc = etree.Element('div')
275 toc_header = etree.SubElement(toc, 'h2')
276 toc_header.text = u'Spis treści'
277 toc_list = etree.SubElement(toc, 'ol')
279 for n, section, text, subsections in sections:
280 section_element = etree.SubElement(toc_list, 'li')
281 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
284 subsection_list = etree.SubElement(section_element, 'ol')
285 for n1, subsection, subtext, _ in subsections:
286 subsection_element = etree.SubElement(subsection_list, 'li')
287 add_anchor(subsection_element, "s%d" % n1, with_target=False, link_text=subtext)
292 def add_table_of_themes(root):
294 from sortify import sortify
300 for fragment in root.findall('.//a[@class="theme-begin"]'):
301 if not fragment.text:
303 theme_names = [s.strip() for s in fragment.text.split(',')]
304 for theme_name in theme_names:
305 book_themes.setdefault(theme_name, []).append(fragment.get('name'))
306 book_themes = list(book_themes.items())
307 book_themes.sort(key=lambda s: sortify(s[0]))
308 themes_div = etree.Element('div', id="themes")
309 themes_ol = etree.SubElement(themes_div, 'ol')
310 for theme_name, fragments in book_themes:
311 themes_li = etree.SubElement(themes_ol, 'li')
312 themes_li.text = "%s: " % theme_name
313 for i, fragment in enumerate(fragments):
314 item = etree.SubElement(themes_li, 'a', href="#%s" % fragment)
315 item.text = str(i + 1)
317 root.insert(0, themes_div)
320 def extract_annotations(html_path):
321 """Extracts annotations from HTML for annotations dictionary.
323 For each annotation, yields a tuple of:
324 anchor, footnote type, valid qualifiers, text, html.
327 from .fn_qualifiers import FN_QUALIFIERS
329 parser = etree.HTMLParser(encoding='utf-8')
330 tree = etree.parse(html_path, parser)
331 footnotes = tree.find('//*[@id="footnotes"]')
332 re_qualifier = re.compile(r'[^\u2014]+\s+\(([^\)]+)\)\s+\u2014')
333 if footnotes is not None:
334 for footnote in footnotes.findall('div'):
335 fn_type = footnote.get('class').split('-')[1]
336 anchor = footnote.find('a[@class="annotation"]').get('href')[1:]
339 if len(footnote) and footnote[-1].tail == '\n':
340 footnote[-1].tail = None
341 text_str = etree.tostring(footnote, method='text', encoding='unicode').strip()
342 html_str = etree.tostring(footnote, method='html', encoding='unicode').strip()
344 match = re_qualifier.match(text_str)
346 qualifier_str = match.group(1)
348 for candidate in re.split('[;,]', qualifier_str):
349 candidate = candidate.strip()
350 if candidate in FN_QUALIFIERS:
351 qualifiers.append(candidate)
352 elif candidate.startswith('z '):
353 subcandidate = candidate.split()[1]
354 if subcandidate in FN_QUALIFIERS:
355 qualifiers.append(subcandidate)
359 yield anchor, fn_type, qualifiers, text_str, html_str