-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.py
353 lines (280 loc) · 11 KB
/
transform.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# coding: utf-8
import lxml.etree as ET
from lxml.html import html5parser
from lxml import objectify
import re
import datetime
import roman
import cobalt
import cobalt.render
import pycountry
import yaml
def tag(elem):
tagname = elem.tag
if '}' not in tagname:
return None
return tagname[tagname.index("}") + 1:]
def format_num(level, n):
return '(%s)' % level_num(level, n)
def level_num(level, n):
if level == 0:
return int(n)
if level in [1, 2]:
return chr(ord('a') + int(n) - 1)
if level in [3, 4]:
return roman.toRoman(int(n)).lower()
return '?? level=%s num=%s ??' % (level, n)
raise ValueError("Formatting number for level %s??" % level)
class Transformer(object):
num_re = re.compile('^([^\d]*)((\d+)\.?)[\s:]*(.*)', re.I)
ns = None
def __init__(self):
self.xslt = ET.XSLT(ET.parse('html_to_akn.xsl'))
def transform_all(self, fnames, language, title):
self.act = cobalt.Act()
for node in self.act.body.iterchildren():
self.act.body.remove(node)
for fname in fnames:
print fname
self.transform(fname)
# do remaining transforms
xml = self.act.to_xml()
xml = ET.tostring(self.xslt(ET.fromstring(xml)), pretty_print=True)
self.act = cobalt.Act(xml)
# frbr_uri
self.act.frbr_uri = "/za/act/1996/constitution"
# metadata
self.act.work_date = "1996-12-04"
now = datetime.datetime.now()
self.act.expression_date = now.strftime("%Y-%m-%d")
self.act.manifestation_date = now.strftime("%Y-%m-%d")
self.act.language = language
self.act.title = title
self.act.meta.identification.FRBRExpression.FRBRauthor.set('href', '#myconstitution')
ref = self.act._make('TLCOrganization')
ref.set('id', 'myconstitution')
ref.set('href', 'http://myconstitution.co.za/')
ref.set('showAs', 'MyConstitution.co.za')
self.act.meta.references.insert(0, ref)
self.act.meta.identification.FRBRManifestation.FRBRauthor.set('href', '#cobalt')
def transform(self, fname):
# sanitize into proper XML
text = open(fname).read()
html = html5parser.fromstring(text)
text = ET.tostring(html)
html = objectify.fromstring(text)
self.ns = html.nsmap[None]
self.nsmap = html.nsmap
self.maker = objectify.ElementMaker(annotate=False, namespace=self.act.namespace, nsmap=self.act.act.nsmap)
root = self.xpath(html, "//h:div[@id='wrapper']")[0]
name = fname.split('/')[-1].split('.')[0]
schedule = 'schedule' in fname
self.main(root, name, schedule)
def main(self, root, name, is_schedule=False):
context = None
parent = None
part = None
for elem in root.iterchildren():
tagname = tag(elem)
if not tagname:
continue
if tagname == 'h1':
num = self.num_re.match(elem.text)
if is_schedule:
# schedule
schedule = self.act.new_component(name=name)
schedule.title = elem.text
article = schedule._make('article')
schedule.mainBody.append(article)
article.set('id', name)
context = article
elif not num:
# assume preamble
try:
self.act.act.preamble
raise ValueError("Duplicate preamble?")
except AttributeError:
pass
preamble = self.maker.preamble()
self.act.act.insert(1, preamble)
context = preamble
else:
# normal chapter
chapter = self.maker.chapter()
chapter.append(self.maker.num(num.groups()[1]))
chapter.append(self.maker.heading(num.groups()[3]))
chapter.set('id', 'chapter-%s' % num.groups()[2])
self.act.body.append(chapter)
context = chapter
parent = context
elif tagname in ['h2', 'h3']:
num = self.num_re.match(elem.text)
if not num and elem.text.split(' ', 1)[0] in ['Part', 'Ingcenye', 'iCandelo', 'Deel', 'Ingxenye', 'Karolo', 'Incenye', u'Tshipiḓa', 'Xiphemu']:
# parts
part = self.maker.part()
if ':' in elem.text:
num = elem.text.split(':', 1)[0].split(' ')[-1]
heading = elem.text.split(':', 1)[1]
else:
num = elem.text.split(' ')[-1]
heading = None
part.append(self.maker.num(num))
part.set('id', 'part-%s' % num)
if heading:
part.append(self.maker.heading(heading))
parent.append(part)
context = part
elif not num:
context.append(self.maker.p(elem.text))
else:
# section
section = self.maker.section()
section.append(self.maker.num(num.groups()[1]))
section.append(self.maker.heading(num.groups()[3]))
section.set('id', 'section-%s' % num.groups()[2])
p = part if part is not None else parent
p.append(section)
context = section
else:
id = context.get('id')
# check for a decent container?
if name == 'schedule-1a' and context.tag.split('}')[-1] != 'content':
context.append(self.maker.content())
context = context.content
# tail and node text?
self.process(context, [elem], 0, id)
def xpath(self, node, xp):
return node.xpath(xp, namespaces={'h': self.ns})
def gather_text(self, name, elem):
# gather all text content in elem and place it into context
context = getattr(self.maker, name)(elem.text)
for child in elem.iterchildren():
if tag(child) == 'br':
eol = self.maker.eol()
eol.tail = child.tail
context.append(eol)
return context
def process(self, context, elements, level, idprefix):
list_count = 0
for i, elem in enumerate(elements):
tagname = tag(elem)
if tagname == 'ol':
if level > 0:
blockList = self.maker.blockList()
temp_id = idprefix + ".list%s" % list_count
blockList.set('id', temp_id)
list_count += 1
context.append(blockList)
self.process(blockList, elem.iterchildren(), level + 1, temp_id)
else:
self.process(context, elem.iterchildren(), level, idprefix)
elif tagname == 'li':
if level == 0:
ss = self.maker.subsection()
ss.append(self.maker.num(format_num(level, i + 1)))
temp_id = idprefix + '.%s' % level_num(level, i + 1)
ss.set('id', temp_id)
context.append(ss)
item = self.maker.content()
ss.append(item)
else:
item = self.maker.item()
item.append(self.maker.num(format_num(level, i + 1)))
temp_id = idprefix + '.%s' % level_num(level, i + 1)
item.set('id', temp_id)
context.append(item)
if elem.text:
item.append(self.gather_text('p', elem))
self.process(item, elem.iterchildren(), level + 1, temp_id)
elif tagname in ['p', 'div', 'table', 'ul', 'blockquote']:
if context.tag.split('}')[1] not in ['content', 'preamble', 'item']:
para = self.maker.paragraph()
para.set('id', context.get('id') + ".paragraph0")
para.append(self.maker.content())
context.append(para)
context = para.content
# let the xsl handle this
context.append(elem)
elif tagname == 'table':
context.append(elem)
else:
raise ValueError("Unhandled tag: %s" % tagname)
def make_html(act, fname):
renderer = cobalt.render.HTMLRenderer(act)
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="http://indigo-web.openup.org.za/dist/0.1.2/css/akoma-ntoso.min.css">
<style>
.akoma-ntoso {
max-width: 750px;
}
.akoma-ntoso .akn-article,
.akoma-ntoso .akn-chapter,
.akoma-ntoso .akn-section,
.akoma-ntoso .akn-subsection,
.akoma-ntoso .akn-paragraph,
.akoma-ntoso .akn-item,
.akoma-ntoso .akn-content > .akn-p {
position: relative;
display: block;
}
.akoma-ntoso .akn-remark {
font-style: italic;
position: absolute;
left: 110%;
margin: 0px;
padding: 0px;
display: block;
width: 45%;
top: 0px;
background: #fff9df;
padding: 5px;
border: 3px solid white;
color: #777;
}
.akoma-ntoso .akn-remark:hover {
z-index: 5;
color: inherit;
}
</style>
</head>
<body class="akoma-ntoso">
__BODY__
</body>
</html>
"""
html = html.replace('__BODY__', renderer.render_xml(act.to_xml()))
with open(fname, 'w') as f:
f.write(html)
def load_languages():
config = yaml.load(open("constitution/_config.yml", "r"))
languages = {
x['values']['language']: x['values'] for x in config['defaults'] if len(x.get('scope', {}).get('path')) >= 2
}
for code in languages.iterkeys():
if len(code) == 3:
languages[code]['long_code'] = code
else:
languages[code]['long_code'] = pycountry.languages.get(alpha_2=code).alpha_3
languages[code]['language'] = pycountry.languages.get(alpha_3=languages[code]['long_code']).name
return languages
if __name__ == '__main__':
langs = load_languages()
for code, lang in langs.iteritems():
#if code not in ['en']:
# continue
print("Doing %s" % code)
parts = ['0-5-preamble.html'] + ['%02d.html' % i for i in range(1, 14)]
# TODO schedules
parts = parts + ['schedule-%s.html' % x for x in '1 1a 2 3 4 5 6 6a 6b 7'.split()]
#parts = ['schedule-%s.html' % x for x in ['3']]
parts = ['constitution/_site/%s/%s' % (code, p) for p in parts]
tr = Transformer()
tr.transform_all(parts, language=lang['long_code'], title=lang['book-title'])
fname = 'docs/%s.xml' % code
with open(fname, 'w') as f:
f.write(tr.act.to_xml())
make_html(tr.act, 'docs/%s.html' % code)