Allow anonymous read on bookmarks, user lists.
[wolnelektury.git] / src / catalogue / api / tojson.py
1 from collections import defaultdict
2 import json
3 import re
4 from sys import argv
5 from lxml import etree
6
7 tags = {
8     'utwor': ('_pass', False, None, None, None),
9     '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF': ('_ignore', False, None, None, None),
10     'abstrakt': ('_ignore', False, None, None, None),
11     'uwaga': ('_ignore', False, None, None, None),
12     'extra': ('_ignore', False, None, None, None),
13     'nota_red': ('_ignore', False, None, None, None),
14     'numeracja': ('_ignore', False, None, None, None),
15
16     'powiesc': ('master', False, None, None, None),
17     'opowiadanie': ('master', False, None, None, None),
18     'liryka_lp': ('master', False, None, None, None),
19     'liryka_l': ('master', False, None, None, None),
20     'dramat_wspolczesny': ('master', False, None, None, None),
21     'dramat_wierszowany_lp': ('master', False, None, None, None),
22     'dramat_wierszowany_l': ('master', False, None, None, None),
23
24     'dlugi_cytat': ('blockquote', False, None, None, None),
25     'poezja_cyt': ('blockquote', False, None, None, None),
26     'dlugi_cyt': ('blockquote', False, None, None, None),
27     'ramka': ('blockquote', False, {'class': 'ramka'}, None, None),
28     
29     'blok': ('div', False, None, None, None),
30
31     'strofa': ('div', True, {'class': 'stanza'}, None, None),
32     'wers': ('div', True, {'class': 'verse'}, None, None),
33     'wers_wciety': ('div', True, {'class': 'wers_wciety'}, None, None),
34     'wers_cd': ('div', True, {'class': 'wers_cd'}, None, None),
35     'wers_akap': ('div', True, {'class': 'wers_akap'}, None, None),
36     'zastepnik_wersu': ('div', True, {'class': 'zastepnik_wersu'}, None, None),
37     'wers_do_prawej': ('div', True, {'class': 'wers_do_prawej'}, None, None),
38     'wers_srodek': ('div', True, {'class': 'wers_srodek'}, None, None),
39     
40     'autor_utworu': ('div', True, {'class': 'author'}, None, None),
41     'dzielo_nadrzedne': ('div', True, {'class': 'dzielo_nadrzedne'}, None, None),
42     'nazwa_utworu': ('div', True, {'class': 'title'}, None, None),
43     'podtytul': ('div', True, {'class': 'podtytul'}, None, None),
44
45     'motto': ('div', False, {'class': 'motto'}, None, None),
46     'motto_podpis': ('div', True, {'class': 'motto_podpis'}, None, None),
47     'dedykacja': ('div', True, {'class': 'dedykacja'}, None, None),
48     'miejsce_czas': ('div', True, {'class': 'miejsce_czas'}, None, None),
49     
50     'lista_osob': ('div', False, {'class': 'lista_osob'}, None, None),
51     'naglowek_listy': ('div', True, {'class': 'naglowek_listy'}, None, None),
52     'lista_osoba': ('div', True, {'class': 'lista_osoba'}, None, None),
53     'naglowek_osoba': ('div', True, {'class': 'naglowek_osoba'}, None, None),
54     'osoba': ('em', True, {'class': 'osoba'}, None, None),
55     'didaskalia': ('div', True, {'class': 'didaskalia'}, None, None),
56     'kwestia': ('div', False, {'class': 'kwestia'}, None, None),
57     'didask_tekst': ('em', False, {'class': 'didask_tekst'}, None, None),
58     
59     'naglowek_czesc': ('h2', True, None, None, None),
60     'naglowek_akt': ('h2', True, None, None, None),
61     'naglowek_scena': ('h3', True, None, None, None),
62     'naglowek_rozdzial': ('h3', True, None, None, None),
63     'naglowek_podrozdzial': ('h4', True, None, None, None),
64     'srodtytul': ('h5', True, None, None, None),
65
66     'nota': ('div', True, {'class': 'note'}, None, False),
67
68     'akap': ('p', True, {'class': 'paragraph'}, None, True),
69     'akap_dialog': ('p', True, {'class': 'paragraph'}, None, True),
70     'akap_cd': ('p', True, {'class': 'paragraph'}, None, True),
71
72     'sekcja_asterysk': ('p', True, {'class': 'spacer-asterisk'}, None, True),
73     'sekcja_swiatlo': ('p', True, {'class': 'sekcja_swiatlo'}, None, True),
74     'separator_linia': ('p', True, {'class': 'separator_linia'}, None, True),
75
76     'tytul_dziela': ('em', True, {'class': 'book-title'}, None, False),
77     'slowo_obce': ('em', True, {'class': 'foreign-word'}, None, False),
78     'wyroznienie': ('em', True, {'class': 'author-emphasis'}, None, False),
79     'wieksze_odstepy': ('em', True, {'class': 'wieksze_odstepy'}, None, False),
80
81     'ref': ('a', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
82
83     'begin': ('_ignore', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
84     'end': ('_ignore', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
85     'motyw': ('_ignore', True, {'class': 'theme'}, None, False),
86
87     'pa': ('a', True, {'class': 'footnote footnote-pa'}, None, False),
88     'pe': ('a', True, {'class': 'footnote footnote-pe'}, None, False),
89     'pr': ('a', True, {'class': 'footnote footnote-pr'}, None, False),
90     'pt': ('a', True, {'class': 'footnote footnote-pt'}, None, False),
91     'ptrad': ('a', True, {'class': 'footnote footnote-ptrad'}, None, False),
92 }
93
94 id_prefixes = {
95     'pa': 'fn',
96     'pe': 'fn',
97     'pr': 'fn',
98     'pt': 'fn',
99     'ptrad': 'fn',
100     'wers': 'f',
101     'wers_wciety': 'f',
102     'wers_cd': 'f',
103     'wers_akap': 'f',
104     'zastepnik_wersu': 'f',
105     'wers_do_prawej': 'f',
106     'wers_srodek': 'f',
107     'akap': 'f',
108     'akap_cd': 'f',
109     'akap_dialog': 'f',
110 }
111
112
113 #tree = etree.parse(argv[1])
114
115 front1 = set([
116     'dzielo_nadrzedne',
117     'nazwa_utworu',
118     'podtytul',
119     ])
120 front2 = set(['autor_utworu'])
121
122
123 def norm(text):
124     text = text.replace('---', '—').replace('--', '–').replace('...', '…').replace(',,', '„').replace('"', '”').replace('\n', ' ')
125     return text
126
127
128 def toj(elem, S):
129     if elem.tag is etree.Comment: return []
130     tag, hastext, attrs, attr_map, num = tags[elem.tag]
131     contents = []
132     if tag == '_pass':
133         output = contents
134     elif tag == '_ignore':
135         return []
136     else:
137         output = {
138             'tag': tag,
139         }
140         if num:
141             S['index'] += 1
142             output['paragraphIndex'] = S['index']
143             if 'dlugi_cytat' not in S['stack'] and 'poezja_cyt' not in S['stack']:
144                 S['vindex'] += 1
145                 output['visibleNumber'] = S['vindex']
146         id_prefix = id_prefixes.get(elem.tag, 'i')
147         S['id'][id_prefix] += 1
148         output['id'] = id_prefix + str(S['id'][id_prefix])
149         if elem.attrib.get('id'):
150             output['id'] = 'wl-' + elem.attrib.get('id')
151         if attrs:
152             output['attr'] = attrs.copy()
153         if attr_map:
154             output.setdefault('attr', {})
155             for k, v in attr_map.items():
156                 output['attr'][k] = elem.attrib[v]
157         output['contents'] = contents
158         output = [output]
159     if elem.tag == 'strofa':
160         verses = [etree.Element('wers')]
161         if elem.text:
162             vparts = re.split(r'/\s+', elem.text)
163             for i, v in enumerate(vparts):
164                 if i:
165                     verses.append(etree.Element('wers'))
166                 verses[-1].text = (verses[-1].text or '') + v
167         for child in elem:
168             vparts = re.split(r'/\s+', child.tail or '')
169             child.tail = vparts[0]
170             verses[-1].append(child)
171             for v in vparts[1:]:
172                 verses.append(etree.Element('wers'))
173                 verses[-1].text = v
174
175         if not(len(verses[-1]) or (verses[-1].text or '').strip()):
176             verses.pop()
177
178         elem.clear(keep_tail=True)
179         for verse in verses:
180             if len(verse) == 1 and (verse[0].tag.startswith('wers') or verse[0].tag == 'zastepnik_wersu') and not (verse[0].tail or '').strip():
181                 elem.append(verse[0])
182             else:
183                 elem.append(verse)
184
185         #if not len(elem):
186         #    for v in re.split(r'/\s+', elem.text):
187         #        etree.SubElement(elem, 'wers').text = v
188         #    elem.text = None
189         
190     if hastext and elem.text:
191         contents.append(norm(elem.text))
192     for c in elem:
193         S['stack'].append(elem.tag)
194         contents += toj(c, S)
195         if hastext and c.tail:
196             contents.append(norm(c.tail))
197         S['stack'].pop()
198
199     if elem.tag in front1:
200         S['front1'] += output
201         return []
202     if elem.tag in front2:
203         S['front2'] += output
204         return []
205     return output
206
207 def conv(tree):
208     S = {
209         'index': 0,
210         'vindex': 0,
211         'id': defaultdict(lambda: 0),
212         'stack': [],
213         'front1': [],
214         'front2': [],
215     }
216     output = toj(tree.getroot(), S)
217     if not len(output): return {}
218     jt = output[0]
219     jt['front1'] = S['front1']
220     jt['front2'] = S['front2']
221     return jt
222
223 #print(json.dumps(jt, indent=2, ensure_ascii=False))