forked from jirikuncar/marc-json-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
90 lines (76 loc) · 2.69 KB
/
generate.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
import click
import json
import re
from flask.json import tojson_filter
from jinja2 import Template
def clean_name(name):
"""FIXME quick hack.
Please forgive me :).
"""
name = name.lower()
name = name.replace('etc.', '')
name = name.replace(' ', '_')
name = name.replace(',', '_')
name = name.replace('/', '_')
name = name.replace('(', '')
name = name.replace(')', '')
name = name.replace('-', '_')
name = name.replace('.', '')
name = name.replace("'", '_')
name = name.replace('$', '_')
name = re.sub('___*', '_', name)
name = name.strip('_')
return name
def get_indicator(possition, field):
indicators = field.get('indicators', {})
possition = str(possition)
if not indicators or not possition in indicators:
return {'re': '.'}
indicator = indicators[possition]
if indicator['name'] == 'Undefined' or clean_name(indicator['name']) in [
'source_of_code', 'number_source', 'code_source', 'type_of_address',
'source_of_term', 'same_as_associated_field', 'same_as_associated_field']:
return {'re': '.'}
indicator['name'] = clean_name(indicator['name'])
def expand(key):
if '-' in key:
start, stop = key.split('-')
return map(str, range(int(start), int(stop) + 1))
return [key]
indicator['values'] = dict(
(k, v) for kk, v in indicator.get('values', {}).iteritems() for k in expand(kk)
)
if len(indicator.get('values')) > 0:
indicator['re'] = '[{0}]'.format(''.join(
set(indicator.get('values', {}).keys()) | set('#')
).replace('#', '_'))
else:
return {'re': '.'}
return indicator
def reverse_indicator_dict(d):
new_dict = {}
for key, value in d.iteritems():
if key == '#':
key = '_'
new_dict[value] = key
return new_dict
@click.command()
@click.argument('source', type=click.File('r'))
@click.argument('template', type=click.File('r'))
@click.option('--re-fields', help='Regular expression to filter fields.')
def generate(source, template, re_fields=None):
"""Output rendered JSONAlchemy configuration."""
re_fields = re.compile(re_fields) if re_fields else None
data = [(code, value) for code, value in json.load(source).iteritems()
if re_fields is None or re_fields.match(code)]
tpl = Template(template.read())
click.echo(tpl.render(
data=sorted(data),
clean_name=clean_name,
get_indicator=get_indicator,
reverse_indicator_dict=reverse_indicator_dict,
tojson=tojson_filter,
set=lambda *args, **kwargs: list(set(*args, **kwargs)),
))
if __name__ == '__main__':
generate()