/
mapit_global_import.py
301 lines (245 loc) · 12.3 KB
/
mapit_global_import.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
# import_global_osm.py:
#
# This script is used to import boundaries from OpenStreetMap into
# MaPit.
#
# It takes KML data generated either by
# get-boundaries-by-admin-level.py, so you need to have run that
# script first.
#
# This script was originally based on import_norway_osm.py by Matthew
# Somerville.
#
# Copyright (c) 2011, 2012 UK Citizens Online Democracy. All rights reserved.
# Email: mark@mysociety.org; WWW: http://www.mysociety.org
import os
import re
import xml.sax
from optparse import make_option
from django.core.management.base import LabelCommand
# Not using LayerMapping as want more control, but what it does is what this does
#from django.contrib.gis.utils import LayerMapping
from django.contrib.gis.gdal import *
from mapit.models import Area, Generation, Country, Type, Code, CodeType, NameType
from mapit.management.command_utils import save_polygons, KML
from glob import glob
import urllib2
from BeautifulSoup import BeautifulSoup
from collections import namedtuple
import json
def make_missing_none(s):
"""If s is empty (considering Unicode spaces) return None, else s"""
if re.search('(?uis)^\s*$', s):
return None
else:
return s
LanguageCodes = namedtuple('LanguageCodes',
['three_letter',
'two_letter',
'english_name',
'french_name'])
def get_iso639_2_table():
"""Scrape and return the table of ISO639-2 and ISO639-1 language codes
The OSM tags of the form "name:en", "name:fr", etc. refer to
ISO639-1 two-letter codes, or ISO639-2 three-letter codes. This
function parses the Library of Congress table of these values, and
returns them as a list of LanguageCodes"""
result = []
url = "http://www.loc.gov/standards/iso639-2/php/code_list.php"
f = urllib2.urlopen(url)
data = f.read()
f.close()
soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES)
table = soup.find('table', {'border': '1'})
for row in table.findAll('tr', recursive=False):
tds = row.findAll('td', recursive=False)
if len(tds) != 4:
continue
strings = ["".join(td.findAll(text=True)).strip() for td in tds]
result_row = LanguageCodes._make(make_missing_none(s) for s in strings)
result.append(result_row)
return result
class Command(LabelCommand):
help = 'Import OSM boundary data from KML files'
args = '<KML-DIRECTORY>'
option_list = LabelCommand.option_list + (
make_option('--commit', action='store_true', dest='commit', help='Actually update the database'),
make_option('--verbose', action='store_true', dest='verbose', help='Provide verbose progress reporting')
)
def handle_label(self, directory_name, **options):
current_generation = Generation.objects.current()
new_generation = Generation.objects.new()
if not new_generation:
raise Exception, "No new generation to be used for import!"
if not os.path.isdir(directory_name):
raise Exception, "'%s' is not a directory" % (directory_name,)
os.chdir(directory_name)
mapit_type_glob = "[A-Z0-9][A-Z0-9][A-Z0-9]"
if not glob(mapit_type_glob):
raise Exception, "'%s' did not contain any directories that look like MapIt types (e.g. O11, OWA, etc.)" % (directory_name,)
def verbose(s):
if options['verbose']:
print s.encode('utf-8')
verbose("Loading any admin boundaries from " + directory_name)
verbose("Finding language codes...")
language_code_to_name = {}
code_keys = ('two_letter', 'three_letter')
for row in get_iso639_2_table():
english_name = getattr(row, 'english_name')
for k in code_keys:
code = getattr(row, k)
if not code:
continue
# Some of the language codes have a bibliographic or
# terminology code, so strip those out:
codes = re.findall(r'(\w+) \([BT]\)', code)
if not codes:
codes = [code]
for c in codes:
language_code_to_name[c] = english_name
global_country = Country.objects.get(code='G')
# print json.dumps(language_code_to_name, sort_keys=True, indent=4)
skip_up_to = None
# skip_up_to = 'relation-80370'
skipping = bool(skip_up_to)
for type_directory in sorted(glob(mapit_type_glob)):
verbose("Loading type " + type_directory)
if not os.path.exists(type_directory):
verbose("Skipping the non-existent " + type_directory)
continue
verbose("Loading all KML in " + type_directory)
files = sorted(os.listdir(type_directory))
total_files = len(files)
for i, e in enumerate(files):
progress = "[%d%% complete] " % ((i * 100) / total_files,)
if skipping:
if skip_up_to in e:
skipping = False
else:
continue
if not e.endswith('.kml'):
verbose("Ignoring non-KML file: " + e)
continue
m = re.search(r'^(way|relation)-(\d+)-', e)
if not m:
raise Exception, u"Couldn't extract OSM element type and ID from: " + e
osm_type, osm_id = m.groups()
kml_filename = os.path.join(type_directory, e)
verbose(progress + "Loading " + unicode(os.path.realpath(kml_filename), 'utf-8'))
# Need to parse the KML manually to get the ExtendedData
kml_data = KML()
xml.sax.parse(kml_filename, kml_data)
useful_names = [n for n in kml_data.data.keys() if not n.startswith('Boundaries for')]
if len(useful_names) == 0:
raise Exception, "No useful names found in KML data"
elif len(useful_names) > 1:
raise Exception, "Multiple useful names found in KML data"
name = useful_names[0]
print " ", name.encode('utf-8')
if osm_type == 'relation':
code_type_osm = CodeType.objects.get(code='osm_rel')
elif osm_type == 'way':
code_type_osm = CodeType.objects.get(code='osm_way')
else:
raise Exception, "Unknown OSM element type:", osm_type
ds = DataSource(kml_filename)
layer = ds[0]
if len(layer) != 1:
raise Exception, "We only expect one feature in each layer"
feat = layer[0]
g = feat.geom.transform(4326, clone=True)
if g.geom_count == 0:
# Just ignore any KML files that have no polygons in them:
verbose(' Ignoring that file - it contained no polygons')
continue
# Nowadays, in generating the data we should have
# excluded any "polygons" with less than four pointsv
# (the final one being the same as the first), but
# just in case:
polygons_too_small = 0
for polygon in g:
if polygon.num_points < 4:
polygons_too_small += 1
if polygons_too_small:
message = "%d out of %d polygon(s) were too small" % (polygons_too_small, g.geom_count)
verbose(' Skipping, since ' + message)
continue
# raise Exception, message
area_type = Type.objects.get(code=type_directory)
try:
osm_code = Code.objects.get(type=code_type_osm,
code=osm_id,
area__generation_high__lte=current_generation,
area__generation_high__gte=current_generation)
except Code.DoesNotExist:
verbose(' No area existed in the current generation with that OSM element type and ID')
osm_code = None
was_the_same_in_current = False
if osm_code:
m = osm_code.area
# First, we need to check if the polygons are
# still the same as in the previous generation:
previous_geos_geometry = m.polygons.collect()
if previous_geos_geometry is None:
verbose(' In the current generation, that area was empty - skipping')
else:
# Simplify it to make sure the polygons are valid:
previous_geos_geometry = previous_geos_geometry.simplify(tolerance=0)
new_geos_geometry = g.geos.simplify(tolerance=0)
if previous_geos_geometry.equals(new_geos_geometry):
was_the_same_in_current = True
else:
verbose(' In the current generation, the boundary was different')
if was_the_same_in_current:
# Extend the high generation to the new one:
verbose(' The boundary was identical in the previous generation; raising generation_high')
m.generation_high = new_generation
else:
# Otherwise, create a completely new area:
m = Area(
name = name,
type = area_type,
country = global_country,
parent_area = None,
generation_low = new_generation,
generation_high = new_generation,
)
poly = [ g ]
if options['commit']:
m.save()
if name not in kml_data.data:
print json.dumps(kml_data.data, sort_keys=True, indent=4)
raise Exception, u"Will fail to find '%s' in the dictionary" % (name,)
old_lang_codes = set(unicode(n.type.code) for n in m.names.all())
for k, translated_name in kml_data.data[name].items():
language_name = None
if k == 'name':
lang = 'default'
language_name = "OSM Default"
else:
name_match = re.search(r'^name:(.+)$', k)
if name_match:
lang = name_match.group(1)
if lang in language_code_to_name:
language_name = language_code_to_name[lang]
if not language_name:
continue
old_lang_codes.discard(unicode(lang))
# Otherwise, make sure that a NameType for this language exists:
NameType.objects.update_or_create({'code': lang},
{'code': lang,
'description': language_name})
name_type = NameType.objects.get(code=lang)
m.names.update_or_create({ 'type': name_type }, { 'name': translated_name })
if old_lang_codes:
verbose('Removing deleted languages codes: ' + ' '.join(old_lang_codes))
m.names.filter(type__code__in=old_lang_codes).delete()
# If the boundary was the same, the old Code
# object will still be pointing to the same Area,
# which just had its generation_high incremented.
# In every other case, there's a new area object,
# so create a new Code and save it:
if not was_the_same_in_current:
new_code = Code(area=m, type=code_type_osm, code=osm_id)
new_code.save()
save_polygons({ code : (m, poly) })