-
Notifications
You must be signed in to change notification settings - Fork 31
/
apply-osmchange.py
200 lines (182 loc) · 7.73 KB
/
apply-osmchange.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
"""Applies an OSMChange file to the database"""
import sys
import os
import time
import urllib2
import StringIO
import gzip
from datetime import datetime
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
from pymongo import Connection
def convert_time(isotime):
"Returns the time string as a time tuple"
t = datetime.strptime(isotime, "%Y-%m-%dT%H:%M:%SZ")
return time.mktime(t.timetuple())
class OsmChangeHandler(ContentHandler):
"""This ContentHandler works with the OSMChange XML file"""
def __init__(self, client):
"""Initializes the OsmChange object"""
self.action = ""
self.record = {}
self.nodes = []
self.ways = []
self.relations = []
self.client = client
def fillDefault(self, attrs):
"""Fills in default attributes for new records"""
self.record['id'] = long(attrs['id'])
self.record['timestamp'] = convert_time(attrs['timestamp'])
self.record['tags'] = {}
if attrs.has_key('user'):
self.record['user'] = attrs['user']
if attrs.has_key('uid'):
self.record['uid'] = long(attrs['uid'])
if attrs.has_key('version'):
self.record['version'] = int(attrs['version'])
if attrs.has_key('changeset'):
self.record['changeset'] = long(attrs['changeset'])
def startElement(self, name, attrs):
"""Parse the XML element at the start"""
if name in ['create', 'modify', 'delete']:
self.action = name
elif name == 'node':
self.record = {}
self.fillDefault(attrs)
self.record['loc'] = {'lat': float(attrs['lat']), 'lon': float(attrs['lon'])}
elif name == 'tag':
# MongoDB doesn't let us have dots in the key names.
k = attrs['k']
k = k.replace('.', ',,')
self.record['tags'][k] = attrs['v']
elif name == 'way':
self.fillDefault(attrs)
self.record['nodes'] = []
elif name == 'relation':
self.fillDefault(attrs)
self.record['members'] = []
elif name == 'nd':
ref = long(attrs['ref'])
self.record['nodes'].append(ref)
nodes2ways = self.client.osm.nodes.find_one({ 'id' : ref })
if nodes2ways:
if 'ways' not in nodes2ways:
nodes2ways['ways'] = []
nodes2ways['ways'].append(self.record['id'])
self.client.osm.nodes.save(nodes2ways)
else:
print "Node %d ref'd by way %d not in file." % \
(ref, self.record['id'])
elif name == 'member':
ref = long(attrs['ref'])
member = {'type': attrs['type'],
'ref': ref,
'role': attrs['role']}
self.record['members'].append(member)
if attrs['type'] == 'way':
ways2relations = self.client.osm.ways.find_one({ 'id' : ref})
if ways2relations:
if 'relations' not in ways2relations:
ways2relations['relations'] = []
ways2relations['relations'].append(self.record['id'])
self.client.osm.ways.save(ways2relations)
elif attrs['type'] == 'node':
nodes2relations = self.client.osm.nodes.find_one({ 'id' : ref})
if nodes2relations:
if 'relations' not in nodes2relations:
nodes2relations['relations'] = []
nodes2relations['relations'].append(self.record['id'])
self.client.osm.nodes.save(nodes2relations)
elif name == 'node':
self.record['loc'] = {'lat': float(attrs['lat']),
'lon': float(attrs['lon'])}
self.fillDefault(attrs)
elif name == 'tag':
# MongoDB doesn't let us have dots in the key names.
k = attrs['k']
k = k.replace('.', ',,')
self.record['tags'][k] = attrs['v']
elif name == 'way':
self.fillDefault(attrs)
self.record['nodes'] = []
elif name == 'relation':
self.fillDefault(attrs)
self.record['members'] = []
elif name == 'nd':
ref = long(attrs['ref'])
self.record['nodes'].append(ref)
elif name == 'member':
ref = long(attrs['ref'])
member = {'type': attrs['type'],
'ref': ref,
'role': attrs['role']}
self.record['members'].append(member)
def endElement(self, name):
"""Finish parsing osm objects or actions"""
if name in ('node', 'way', 'relation'):
self.type = name
if self.action == 'delete':
self.record['visible'] = False
if self.type == 'way':
nodes = self.client.osm.nodes.find({ 'id': { '$in': self.record['nodes'] } },
{ 'loc': 1, '_id': 0 })
self.record['loc'] = []
for node in nodes:
self.record['loc'].append(node['loc'])
getattr(self, name + 's').append(self.record)
elif name in ('create', 'modify', 'delete'):
if name == 'create':
for coll in ('nodes', 'ways', 'relations'):
if getattr(self, coll):
getattr(self.client.osm, coll).insert(getattr(self, coll))
elif name == 'modify':
for coll in ('nodes', 'ways', 'relations'):
if getattr(self, coll):
primitive_list = getattr(self, coll)
for prim in primitive_list:
getattr(self.client.osm, coll).update({'id': prim['id']},
prim)
elif name == 'delete':
for coll in ('nodes', 'ways', 'relations'):
if getattr(self, coll):
primitive_list = getattr(self, coll)
for prim in primitive_list:
getattr(self.client.osm, coll).remove({'id': prim['id']})
self.action = None
if __name__ == "__main__":
client = Connection()
parser = make_parser()
keepGoing = True
while keepGoing:
# Read the state.txt
sf = open('state.txt', 'r')
state = {}
for line in sf:
if line[0] == '#':
continue
(k, v) = line.split('=')
state[k] = v.strip().replace("\\:", ":")
# Grab the sequence number and build a URL out of it
sqnStr = state['sequenceNumber'].zfill(9)
url = "http://planet.openstreetmap.org/minute-replicate/%s/%s/%s.osc.gz" % (sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
print "Downloading change file (%s)." % (url)
content = urllib2.urlopen(url)
content = StringIO.StringIO(content.read())
gzipper = gzip.GzipFile(fileobj=content)
print "Parsing change file."
handler = OsmChangeHandler(client)
parser.setContentHandler(handler)
parser.parse(gzipper)
# Download the next state file
nextSqn = int(state['sequenceNumber']) + 1
sqnStr = str(nextSqn).zfill(9)
url = "http://planet.openstreetmap.org/minute-replicate/%s/%s/%s.state.txt" % (sqnStr[0:3], sqnStr[3:6], sqnStr[6:9])
try:
u = urllib2.urlopen(url)
statefile = open('state.txt', 'w')
statefile.write(u.read())
statefile.close()
except Exception, e:
keepGoing = False
print e
client.disconnect()