forked from AMDmi3/opening_hours.js
-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathpopulate_nominatim_cache
executable file
·227 lines (196 loc) · 7.32 KB
/
populate_nominatim_cache
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Read _nominatim_url, get the query response and store it as YAML files below ./nominatim_cache.
"""
from __future__ import absolute_import, division, print_function
__version__ = '0.1.0'
__license__ = 'AGPL-3.0'
__author__ = 'Robin Schneider <[email protected]>'
__copyright__ = 'Copyright (C) 2017-2020 Robin Schneider <[email protected]>'
__all__ = ['main']
import sys
import os
import re
import json
import logging
import argparse
from glob import iglob
from collections import OrderedDict
from copy import deepcopy
if sys.version_info[0] == 2:
from io import open
from ruamel import yaml
# import requests
import urllib.request
import urllib.parse
from hc.yaml import dump_holidays_as_yaml
LOG = logging.getLogger(__name__)
NOMINATIM_SORTING = {
'place_id': '10',
'licence': '20',
'osm_type': '30',
'osm_id': '40',
'lat': '50',
'lon': '60',
'display_name': '70',
'address': '80',
}
KEEP_STATE_LEVEL_ADDRESS_ATTRS = [
'country',
'country_code',
]
def handle_country_holiday_def_file(def_file):
c_def = yaml.safe_load(open(def_file, 'r', encoding='utf-8'))
if type(c_def.get('_nominatim_url')) == str:
handle_nominatim_url(c_def['_nominatim_url'], def_file)
for r_name, r_def in c_def.items():
if type(r_def) == dict and type(r_def.get('_nominatim_url')) == str:
if any(c.isupper() for c in str(r_def.get('_state_code', ''))):
raise Exception("Found upper case _state_code {} in file {}!".format(
r_def.get('_state_code', ''),
def_file,
))
handle_nominatim_url(
r_def['_nominatim_url'],
def_file,
state=r_def.get('_state_code', r_name),
)
def handle_nominatim_url(nominatim_url, def_file, state=None):
LOG.debug('Calling handle_nominatim_url for {}, state: {}'.format(
nominatim_url, state))
level = 'state' if type(state) in [str, int] else 'country'
country_code_re = re.match(r'.*?(?P<cc>\w+)\.', def_file)
country_code = country_code_re.group('cc')
cache_file = '{}{}.yaml'.format(
country_code,
'_' + str(state) if level == 'state' else '',
)
nominatim_file = os.path.join('nominatim_cache', cache_file)
LOG.debug('nominatim_file: {}'.format(nominatim_file))
if not os.path.exists(nominatim_file):
LOG.info('Loading {}'.format(nominatim_url))
# Caused http.client.BadStatusLine exception with wired encoding in them.
# nominatim_data = json.loads(requests.get(nominatim_url).text)
req = urllib.request.Request(nominatim_url, headers={
'User-Agent': 'curl/7.38.0'})
nominatim_data = json.loads(
urllib.request.urlopen(req).read().decode('utf-8'))
if isinstance(nominatim_data, list):
# We expect that the URL was for geocoding and not reverse geocoding.
parsed_url = urllib.parse.urlparse(nominatim_url)
url_qs = urllib.parse.parse_qs(parsed_url.query)
reverse_geocoding_qs = {
'format': 'json',
'lat': nominatim_data[0]['lat'],
'lon': nominatim_data[0]['lon'],
'zoom': 18,
'addressdetails': 1,
'accept-language': url_qs['accept-language'],
}
parsed_url = list(parsed_url)
parsed_url[2] = '/reverse'
parsed_url[4] = urllib.parse.urlencode(
reverse_geocoding_qs, doseq=True, safe=",")
correct_nominatim_url = urllib.parse.urlunparse(parsed_url)
return handle_nominatim_url(correct_nominatim_url, def_file, state)
nominatim_data = OrderedDict(sorted(
nominatim_data.items(),
key=lambda k: NOMINATIM_SORTING.get(k[0], k[0])))
if level == 'country':
nominatim_data = yaml.load(
dump_holidays_as_yaml(nominatim_data, add_vspacing=False),
Loader=yaml.RoundTripLoader,
)
nominatim_old_address = deepcopy(nominatim_data['address'])
nominatim_data['address'] = OrderedDict()
address_attrs_commented_out = []
for address_attr in sorted(nominatim_old_address.keys()):
if address_attr in KEEP_STATE_LEVEL_ADDRESS_ATTRS:
nominatim_data['address'][address_attr] = nominatim_old_address[address_attr]
else:
address_attrs_commented_out.append('{}: {}'.format(
address_attr,
nominatim_old_address[address_attr],
))
nominatim_data.yaml_set_comment_before_after_key(
'boundingbox',
before='\n'.join(address_attrs_commented_out),
indent=2,
)
nominatim_data['address'] = OrderedDict(
sorted(nominatim_data['address'].items()))
nominatim_yaml = dump_holidays_as_yaml(
nominatim_data, add_vspacing=False)
LOG.debug(nominatim_yaml)
with open(nominatim_file, 'w') as nominatim_fh:
LOG.info('Writing file {}'.format(nominatim_file))
nominatim_fh.write(nominatim_yaml)
def get_args_parser():
args_parser = argparse.ArgumentParser(
description=__doc__,
# epilog=__doc__,
)
args_parser.add_argument(
'-V', '--version',
action='version',
version=__version__,
)
args_parser.add_argument(
'-d', '--debug',
help="Write debugging and higher to STDOUT|STDERR.",
action="store_const",
dest="loglevel",
const=logging.DEBUG,
)
args_parser.add_argument(
'-v', '--verbose',
help="Write information and higher to STDOUT|STDERR.",
action="store_const",
dest="loglevel",
const=logging.INFO,
)
args_parser.add_argument(
'-q', '--quiet', '--silent',
help="Only write errors and higher to STDOUT|STDERR.",
action="store_const",
dest="loglevel",
const=logging.ERROR,
)
args_parser.add_argument(
'-n', '--no-cache',
help="Do not cache intermediary files.",
action="store_false",
dest="cache",
)
args_parser.add_argument(
'-c', '--cache-dir',
help="Cache directory, defaults to the default cache directory of your operating system.",
)
args_parser.add_argument(
'-i', '--input-file',
help="File path to the input file to process."
" '-' will read from STDIN.",
)
return args_parser
def main(): # pylint: disable=too-many-branches
args_parser = get_args_parser()
args = args_parser.parse_args()
if args.loglevel is None:
args.loglevel = logging.WARNING
logging.basicConfig(
format='%(levelname)s{}: %(message)s'.format(
' (%(filename)s:%(lineno)s)' if args.loglevel <= logging.DEBUG else '',
),
level=args.loglevel,
)
if args.cache:
import requests_cache
requests_cache.install_cache('requests_cache')
if args.input_file:
handle_country_holiday_def_file(args.input_file)
else:
for def_file in iglob('*.yaml'):
handle_country_holiday_def_file(def_file)
if __name__ == '__main__':
main()