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, encoding='unicode')
42 document = etree.parse(six.StringIO(xml.replace('abstrakt', 'dlugi_cytat'))) # HACK
43 result = document.xslt(style)
44 html = re.sub('<a name="sec[0-9]*"/>', '', etree.tostring(result, encoding='unicode'))
45 return re.sub('</?blockquote[^>]*>', '', html)
48 def transform(wldoc, stylesheet='legacy', options=None, flags=None, css=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', "''")
75 css = css or 'https://static.wolnelektury.pl/css/compressed/book_text.css'
77 result = document.transform(style, css=css, **options)
78 del document # no longer needed large object :)
80 if html_has_content(result):
81 add_anchors(result.getroot())
82 add_table_of_themes(result.getroot())
83 add_table_of_contents(result.getroot())
85 return OutputFile.from_bytes(etree.tostring(
86 result, method='html', xml_declaration=False, pretty_print=True, encoding='utf-8'))
90 raise ValueError("'%s' is not a valid stylesheet.")
91 except (XMLSyntaxError, XSLTApplyError) as e:
95 @six.python_2_unicode_compatible
96 class Fragment(object):
97 def __init__(self, id, themes):
98 super(Fragment, self).__init__()
103 def append(self, event, element):
104 self.events.append((event, element))
106 def closed_events(self):
108 for event, element in self.events:
110 stack.append(('end', element))
115 print('CLOSED NON-OPEN TAG:', element)
118 return self.events + stack
122 for event, element in self.closed_events():
124 result.append(u'<%s %s>' % (
125 element.tag, ' '.join('%s="%s"' % (k, v) for k, v in element.attrib.items())))
127 result.append(element.text)
129 result.append(u'</%s>' % element.tag)
131 result.append(element.tail)
133 result.append(element)
135 return ''.join(result)
138 return self.to_string()
141 def extract_fragments(input_filename):
142 """Extracts theme fragments from input_filename."""
144 closed_fragments = {}
146 # iterparse would die on a HTML document
147 parser = etree.HTMLParser(encoding='utf-8')
149 buf.write(etree.tostring(etree.parse(input_filename, parser).getroot()[0][0], encoding='utf-8'))
152 for event, element in etree.iterparse(buf, events=('start', 'end')):
153 # Process begin and end elements
154 if element.get('class', '') in ('theme-begin', 'theme-end'):
155 if not event == 'end':
156 continue # Process elements only once, on end event
159 if element.get('class', '') == 'theme-begin':
160 fragment = Fragment(id=element.get('fid'), themes=element.text)
163 parent = element.getparent()
165 while parent.get('id', None) != 'book-text':
166 cparent = copy.deepcopy(parent)
168 parents.append(cparent)
169 parent = parent.getparent()
172 for parent in parents:
173 fragment.append('start', parent)
175 open_fragments[fragment.id] = fragment
177 # Close existing fragment
180 fragment = open_fragments[element.get('fid')]
182 print('%s:closed not open fragment #%s' % (input_filename, element.get('fid')))
184 closed_fragments[fragment.id] = fragment
185 del open_fragments[fragment.id]
187 # Append element tail to lost_text (we don't want to lose any text)
189 for fragment_id in open_fragments:
190 open_fragments[fragment_id].append('text', element.tail)
192 # Process all elements except begin and end
194 # Omit annotation tags
195 if (len(element.get('name', '')) or
196 element.get('class', '') in ('annotation', 'anchor')):
197 if event == 'end' and element.tail:
198 for fragment_id in open_fragments:
199 open_fragments[fragment_id].append('text', element.tail)
201 for fragment_id in open_fragments:
202 open_fragments[fragment_id].append(event, copy.copy(element))
204 return closed_fragments, open_fragments
207 def add_anchor(element, prefix, with_link=True, with_target=True, link_text=None):
208 parent = element.getparent()
209 index = parent.index(element)
212 if link_text is None:
214 anchor = etree.Element('a', href='#%s' % prefix)
215 anchor.set('class', 'anchor')
216 anchor.text = six.text_type(link_text)
217 parent.insert(index, anchor)
220 anchor_target = etree.Element('a', name='%s' % prefix)
221 anchor_target.set('class', 'target')
222 anchor_target.text = u' '
223 parent.insert(index, anchor_target)
226 def any_ancestor(element, test):
227 for ancestor in element.iterancestors():
233 def add_anchors(root):
235 for element in root.iterdescendants():
237 return e.get('class') in ('note', 'motto', 'motto_podpis', 'dedication', 'frame') or \
238 e.get('id') == 'nota_red' or e.tag == 'blockquote'
239 if any_ancestor(element, f):
242 if element.tag == 'div' and 'verse' in element.get('class', ''):
243 if counter == 1 or counter % 5 == 0:
244 add_anchor(element, "f%d" % counter, link_text=counter)
246 elif 'paragraph' in element.get('class', ''):
247 add_anchor(element, "f%d" % counter, link_text=counter)
251 def raw_printable_text(element):
252 working = copy.deepcopy(element)
253 for e in working.findall('a'):
254 if e.get('class') in ('annotation', 'theme-begin'):
256 return etree.tostring(working, method='text', encoding='unicode').strip()
259 def add_table_of_contents(root):
262 for element in root.iterdescendants():
263 if element.tag in ('h2', 'h3'):
264 if any_ancestor(element,
265 lambda e: e.get('id') in ('footnotes', 'nota_red') or e.get('class') in ('person-list',)):
268 element_text = raw_printable_text(element)
269 if element.tag == 'h3' and len(sections) and sections[-1][1] == 'h2':
270 sections[-1][3].append((counter, element.tag, element_text, []))
272 sections.append((counter, element.tag, element_text, []))
273 add_anchor(element, "s%d" % counter, with_link=False)
276 toc = etree.Element('div')
278 toc_header = etree.SubElement(toc, 'h2')
279 toc_header.text = u'Spis treści'
280 toc_list = etree.SubElement(toc, 'ol')
282 for n, section, text, subsections in sections:
283 section_element = etree.SubElement(toc_list, 'li')
284 add_anchor(section_element, "s%d" % n, with_target=False, link_text=text)
287 subsection_list = etree.SubElement(section_element, 'ol')
288 for n1, subsection, subtext, _ in subsections:
289 subsection_element = etree.SubElement(subsection_list, 'li')
290 add_anchor(subsection_element, "s%d" % n1, with_target=False, link_text=subtext)
295 def add_table_of_themes(root):
297 from sortify import sortify
303 for fragment in root.findall('.//a[@class="theme-begin"]'):
304 if not fragment.text:
306 theme_names = [s.strip() for s in fragment.text.split(',')]
307 for theme_name in theme_names:
308 book_themes.setdefault(theme_name, []).append(fragment.get('name'))
309 book_themes = list(book_themes.items())
310 book_themes.sort(key=lambda s: sortify(s[0]))
311 themes_div = etree.Element('div', id="themes")
312 themes_ol = etree.SubElement(themes_div, 'ol')
313 for theme_name, fragments in book_themes:
314 themes_li = etree.SubElement(themes_ol, 'li')
315 themes_li.text = "%s: " % theme_name
316 for i, fragment in enumerate(fragments):
317 item = etree.SubElement(themes_li, 'a', href="#%s" % fragment)
318 item.text = str(i + 1)
320 root.insert(0, themes_div)
323 def extract_annotations(html_path):
324 """Extracts annotations from HTML for annotations dictionary.
326 For each annotation, yields a tuple of:
327 anchor, footnote type, valid qualifiers, text, html.
330 from .fn_qualifiers import FN_QUALIFIERS
332 parser = etree.HTMLParser(encoding='utf-8')
333 tree = etree.parse(html_path, parser)
334 footnotes = tree.find('//*[@id="footnotes"]')
335 re_qualifier = re.compile(r'[^\u2014]+\s+\(([^\)]+)\)\s+\u2014')
336 if footnotes is not None:
337 for footnote in footnotes.findall('div'):
338 fn_type = footnote.get('class').split('-')[1]
339 anchor = footnote.find('a[@class="annotation"]').get('href')[1:]
342 if len(footnote) and footnote[-1].tail == '\n':
343 footnote[-1].tail = None
344 text_str = etree.tostring(footnote, method='text', encoding='unicode').strip()
345 html_str = etree.tostring(footnote, method='html', encoding='unicode').strip()
347 match = re_qualifier.match(text_str)
349 qualifier_str = match.group(1)
351 for candidate in re.split('[;,]', qualifier_str):
352 candidate = candidate.strip()
353 if candidate in FN_QUALIFIERS:
354 qualifiers.append(candidate)
355 elif candidate.startswith('z '):
356 subcandidate = candidate.split()[1]
357 if subcandidate in FN_QUALIFIERS:
358 qualifiers.append(subcandidate)
362 yield anchor, fn_type, qualifiers, text_str, html_str