88762945e2a52629d69f868ff8be7db9d71df645
[librarian.git] / src / librarian / document.py
1 import gettext
2 import os
3 import re
4 from urllib.request import urlopen
5 from lxml import etree
6 from .parser import parser
7 from . import dcparser
8 from .functions import lang_code_3to2
9
10
11 class WLDocument:
12     def __init__(self, filename=None, url=None):
13         source = filename or urlopen(url)
14         tree = etree.parse(source, parser=parser)
15         self.tree = tree
16         tree.getroot().document = self
17         self.base_meta = dcparser.BookInfo({}, {}, validate_required=False)
18
19     @property
20     def meta(self):
21         # Allow metadata of the master element as document meta.
22         #master = self.tree.getroot()[-1]
23         return self.tree.getroot().meta
24         return master.meta
25
26     def build(self, builder, **kwargs):
27         return builder().build(self, **kwargs)
28
29     def _compat_assign_ordered_ids(self):
30         """
31         Compatibility: ids in document order, to be roughly compatible with legacy
32         footnote ids. Just for testing consistency, change to some sane identifiers
33         at convenience.
34         """
35         EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE)
36         def _compat_assign_ordered_ids_in_elem(elem, i):
37             elem.attrib['_compat_ordered_id'] = str(i)
38             i += 1
39             if getattr(elem, 'HTML_CLASS', None) == 'stanza':
40                 if elem.text:
41                     i += len(EXPR.split(elem.text)) - 1
42                 for sub in elem:
43                     i = _compat_assign_ordered_ids_in_elem(sub, i)
44                     if sub.tail:
45                         i += len(EXPR.split(sub.tail)) - 1
46             else:
47                 if elem.tag in ('uwaga', 'extra'):
48                     return i
49                 for sub in elem:
50                     i = _compat_assign_ordered_ids_in_elem(sub, i)
51             return i
52
53         _compat_assign_ordered_ids_in_elem(self.tree.getroot(), 4)
54
55     def _compat_assign_section_ids(self):
56         """
57         Ids in master-section order. These need to be compatible with the
58         #secN anchors used by WL search results page to link to fragments.
59         """
60         def _compat_assigns_section_ids_in_elem(elem, prefix='sec'):
61             for i, child in enumerate(elem):
62                 idfier = '{}{}'.format(prefix, i + 1)
63                 child.attrib['_compat_section_id'] = idfier
64                 _compat_assigns_section_ids_in_elem(child, idfier + '-')
65         _compat_assigns_section_ids_in_elem(self.tree.getroot().master)
66