Ilustr sizes in json for app
[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 from catalogue.utils import get_ilustr_sizes
7
8
9 def ilustr_sizes_getter(e, S):
10     sizes = get_ilustr_sizes(e.attrib['src'], S['slug'], S['ilustr'])
11     S['ilustr'] += 1
12     return sizes
13
14
15 tags = {
16     'utwor': ('_pass', False, None, None, None),
17     '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF': ('_ignore', False, None, None, None),
18     'abstrakt': ('_ignore', False, None, None, None),
19     'uwaga': ('_ignore', False, None, None, None),
20     'extra': ('_ignore', False, None, None, None),
21     'nota_red': ('_ignore', False, None, None, None),
22     'numeracja': ('_ignore', False, None, None, None),
23
24     'powiesc': ('master', False, None, None, None),
25     'opowiadanie': ('master', False, None, None, None),
26     'liryka_lp': ('master', False, None, None, None),
27     'liryka_l': ('master', False, None, None, None),
28     'dramat_wspolczesny': ('master', False, None, None, None),
29     'dramat_wierszowany_lp': ('master', False, None, None, None),
30     'dramat_wierszowany_l': ('master', False, None, None, None),
31
32     'dlugi_cytat': ('blockquote', False, None, None, None),
33     'poezja_cyt': ('blockquote', False, None, None, None),
34     'dlugi_cyt': ('blockquote', False, None, None, None),
35     'ramka': ('blockquote', False, {'class': 'ramka'}, None, None),
36     
37     'blok': ('div', False, None, None, None),
38
39     'strofa': ('div', True, {'class': 'stanza'}, None, None),
40     'wers': ('div', True, {'class': 'verse'}, None, None),
41     'wers_wciety': ('div', True, {'class': 'wers_wciety'}, None, None),
42     'wers_cd': ('div', True, {'class': 'wers_cd'}, None, None),
43     'wers_akap': ('div', True, {'class': 'wers_akap'}, None, None),
44     'zastepnik_wersu': ('div', True, {'class': 'zastepnik_wersu'}, None, None),
45     'wers_do_prawej': ('div', True, {'class': 'wers_do_prawej'}, None, None),
46     'wers_srodek': ('div', True, {'class': 'wers_srodek'}, None, None),
47     
48     'autor_utworu': ('div', True, {'class': 'author'}, None, None),
49     'dzielo_nadrzedne': ('div', True, {'class': 'dzielo_nadrzedne'}, None, None),
50     'nazwa_utworu': ('div', True, {'class': 'title'}, None, None),
51     'podtytul': ('div', True, {'class': 'podtytul'}, None, None),
52
53     'motto': ('div', False, {'class': 'motto'}, None, None),
54     'motto_podpis': ('div', True, {'class': 'motto_podpis'}, None, None),
55     'dedykacja': ('div', True, {'class': 'dedykacja'}, None, None),
56     'miejsce_czas': ('div', True, {'class': 'miejsce_czas'}, None, None),
57     
58     'lista_osob': ('div', False, {'class': 'lista_osob'}, None, None),
59     'naglowek_listy': ('div', True, {'class': 'naglowek_listy'}, None, None),
60     'lista_osoba': ('div', True, {'class': 'lista_osoba'}, None, None),
61     'naglowek_osoba': ('div', True, {'class': 'naglowek_osoba'}, None, None),
62     'osoba': ('em', True, {'class': 'osoba'}, None, None),
63     'didaskalia': ('div', True, {'class': 'didaskalia'}, None, None),
64     'kwestia': ('div', False, {'class': 'kwestia'}, None, None),
65     'didask_tekst': ('em', True, {'class': 'didask_tekst'}, None, None),
66     
67     'naglowek_czesc': ('h2', True, None, None, None),
68     'naglowek_akt': ('h2', True, None, None, None),
69     'naglowek_scena': ('h3', True, None, None, None),
70     'naglowek_rozdzial': ('h3', True, None, None, None),
71     'naglowek_podrozdzial': ('h4', True, None, None, None),
72     'srodtytul': ('h5', True, None, None, None),
73
74     'nota': ('div', True, {'class': 'note'}, None, False),
75
76     'akap': ('p', True, {'class': 'paragraph'}, None, True),
77     'akap_dialog': ('p', True, {'class': 'paragraph'}, None, True),
78     'akap_cd': ('p', True, {'class': 'paragraph'}, None, True),
79
80     'sekcja_asterysk': ('p', True, {'class': 'spacer-asterisk'}, None, True),
81     'sekcja_swiatlo': ('p', True, {'class': 'sekcja_swiatlo'}, None, True),
82     'separator_linia': ('p', True, {'class': 'separator_linia'}, None, True),
83
84     'tytul_dziela': ('em', True, {'class': 'book-title'}, None, False),
85     'slowo_obce': ('em', True, {'class': 'foreign-word'}, None, False),
86     'wyroznienie': ('em', True, {'class': 'author-emphasis'}, None, False),
87     'wieksze_odstepy': ('em', True, {'class': 'wieksze_odstepy'}, None, False),
88
89     'ref': ('a', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
90
91     'begin': ('_ignore', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
92     'end': ('_ignore', True, {'class': 'reference'}, {'data-uri': 'href'}, False),
93     'motyw': ('_ignore', True, {'class': 'theme'}, None, False),
94
95     'pa': ('a', True, {'class': 'footnote footnote-pa'}, None, False),
96     'pe': ('a', True, {'class': 'footnote footnote-pe'}, None, False),
97     'pr': ('a', True, {'class': 'footnote footnote-pr'}, None, False),
98     'pt': ('a', True, {'class': 'footnote footnote-pt'}, None, False),
99     'ptrad': ('a', True, {'class': 'footnote footnote-ptrad'}, None, False),
100
101     'werset': ('p', True, {'class': 'werset'}, None, True),
102     'br': ('br', False, None, None, None),
103     'indeks_dolny': ('em', True, {'class': 'indeks_dolny'}, None, False),
104     'mat': ('span', True, {'class': 'mat'}, None, False),
105
106     'mfenced': ('math_mfenced', True, None, None, False),
107     'mfrac': ('math_mfrac', True, None, None, False),
108     'mrow': ('math_mrow', True, None, None, False),
109     'mi': ('math_mi', True, None, None, False),
110     'mn': ('math_mn', True, None, None, False),
111     'mo': ('math_mo', True, None, None, False),
112     'msup': ('math_msup', True, None, None, False),
113
114     'list': ('blockquote', False, {'class': 'list'}, None, None),
115     'wywiad_pyt': ('blockquote', False, {'class': 'wywiad_pyt'}, None, None),
116     'wywiad_odp': ('blockquote', False, {'class': 'wywiad_odp'}, None, None),
117     'rownolegle': ('blockquote', False, {'class': 'rownolegle'}, None, None),
118     'animacja': ('div', False, {'class': 'animacja'}, None, None),
119     'data': ('div', True, {'class': 'data'}, None, None),
120     'podpis': ('div', True, {'class': 'podpis'}, None, None),
121     'naglowek_listu': ('div', True, {'class': 'naglowek_listu'}, None, None),
122     'pozdrowienie': ('div', True, {'class': 'pozdrowienie'}, None, None),
123     'adresat': ('div', True, {'class': 'adresat'}, None, None),
124     'tytul_oryg': ('div', True, {'class': 'tytul_oryg'}, None, None),
125     'miejsce_data': ('div', True, {'class': 'miejsce_data'}, None, None),
126     'audio': ('_ignore', False, None, None, None),
127     'www': ('a', True, {'class': 'www'}, {'href': '.text'}, False),
128
129     'tabela': ('table', False, None, None, None),
130     'tabelka': ('table', False, None, None, None),
131     'wiersz': ('tr', False, None, None, None),
132     'kol': ('td', True, None, None, None),
133
134     'ilustr': ('img', False, None, {
135         'src': lambda e, S: e.attrib['src'],
136         'sizes': ilustr_sizes_getter,
137         'alt': 'alt',
138     }, False),
139     'tab': ('span', False, {'class': 'tab'}, {'szer': 'szer'}, False),
140     
141 }
142
143 id_prefixes = {
144     'pa': 'fn',
145     'pe': 'fn',
146     'pr': 'fn',
147     'pt': 'fn',
148     'ptrad': 'fn',
149     'wers': 'f',
150     'wers_wciety': 'f',
151     'wers_cd': 'f',
152     'wers_akap': 'f',
153     'zastepnik_wersu': 'f',
154     'wers_do_prawej': 'f',
155     'wers_srodek': 'f',
156     'akap': 'f',
157     'akap_cd': 'f',
158     'akap_dialog': 'f',
159 }
160
161
162 #tree = etree.parse(argv[1])
163
164 front1 = set([
165     'dzielo_nadrzedne',
166     'nazwa_utworu',
167     'podtytul',
168     ])
169 front2 = set(['autor_utworu'])
170
171
172 def norm(text):
173     text = text.replace('---', '—').replace('--', '–').replace('...', '…').replace(',,', '„').replace('"', '”').replace('\n', ' ')
174     return text
175
176
177 def toj(elem, S):
178     if elem.tag is etree.Comment: return []
179     tag, hastext, attrs, attr_map, num = tags[elem.tag]
180     contents = []
181     if tag == '_pass':
182         output = contents
183     elif tag == '_ignore':
184         return []
185     else:
186         output = {
187             'tag': tag,
188         }
189         if num:
190             S['index'] += 1
191             output['paragraphIndex'] = S['index']
192             if 'dlugi_cytat' not in S['stack'] and 'poezja_cyt' not in S['stack']:
193                 S['vindex'] += 1
194                 output['visibleNumber'] = S['vindex']
195         id_prefix = id_prefixes.get(elem.tag, 'i')
196         S['id'][id_prefix] += 1
197         output['id'] = id_prefix + str(S['id'][id_prefix])
198         if elem.attrib.get('id'):
199             output['id'] = 'wl-' + elem.attrib.get('id')
200         if attrs:
201             output['attr'] = attrs.copy()
202         if attr_map:
203             output.setdefault('attr', {})
204             for k, v in attr_map.items():
205                 if v == '.text':
206                     val = elem.text
207                 elif callable(v):
208                     val = v(elem, S)
209                 else:
210                     val = elem.attrib[v]
211                 output['attr'][k] = val
212         output['contents'] = contents
213         output = [output]
214     if elem.tag == 'strofa':
215         verses = [etree.Element('wers')]
216         if elem.text:
217             vparts = re.split(r'/\s+', elem.text)
218             for i, v in enumerate(vparts):
219                 if i:
220                     verses.append(etree.Element('wers'))
221                 verses[-1].text = (verses[-1].text or '') + v
222         for child in elem:
223             vparts = re.split(r'/\s+', child.tail or '')
224             child.tail = vparts[0]
225             verses[-1].append(child)
226             for v in vparts[1:]:
227                 verses.append(etree.Element('wers'))
228                 verses[-1].text = v
229
230         if not(len(verses[-1]) or (verses[-1].text or '').strip()):
231             verses.pop()
232
233         elem.clear(keep_tail=True)
234         for verse in verses:
235             if len(verse) == 1 and (verse[0].tag.startswith('wers') or verse[0].tag == 'zastepnik_wersu') and not (verse[0].tail or '').strip():
236                 elem.append(verse[0])
237             else:
238                 elem.append(verse)
239
240         #if not len(elem):
241         #    for v in re.split(r'/\s+', elem.text):
242         #        etree.SubElement(elem, 'wers').text = v
243         #    elem.text = None
244         
245     if hastext and elem.text:
246         contents.append(norm(elem.text))
247     for c in elem:
248         S['stack'].append(elem.tag)
249         contents += toj(c, S)
250         if hastext and c.tail:
251             contents.append(norm(c.tail))
252         S['stack'].pop()
253
254     if elem.tag in front1:
255         S['front1'] += output
256         return []
257     if elem.tag in front2:
258         S['front2'] += output
259         return []
260     return output
261
262 def conv(tree, slug):
263     S = {
264         'index': 0,
265         'vindex': 0,
266         'ilustr': 0,
267         'id': defaultdict(lambda: 0),
268         'stack': [],
269         'front1': [],
270         'front2': [],
271         'slug': slug,
272     }
273     output = toj(tree.getroot(), S)
274     if not len(output): return {}
275     jt = output[0]
276     jt['front1'] = S['front1']
277     jt['front2'] = S['front2']
278     return jt
279
280 #print(json.dumps(jt, indent=2, ensure_ascii=False))