-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
491 lines (458 loc) · 22.1 KB
/
app.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import botocore
import boto3
import pandas as pd
import io
import os
import urllib.parse
import random, time
import json
import datetime
### This function takes a raw data shard from the "raw" bucket,
### uses AWS Locations to GeoCode/ReverseGeoCode based on the columns in the datasets,
### and puts the processed shard into a "processed" bucket.
region = os.environ['AWS_REGION']
s3_client = boto3.client('s3',region_name=region)
location = boto3.client('location',region_name=region)
destination_bucket = os.environ.get('PROCESSED_SHARDS_BUCKET')
location_index = os.environ.get('LOCATION_INDEX')
stepfunctions_client = boto3.client('stepfunctions',region_name=region)
ddb_table = os.environ.get("DDB_TABLE_NAME")
ddb_client = boto3.client("dynamodb")
dynamodb = boto3.resource('dynamodb')
def get_location_for_position(IndexName, Position, MAX_RETRIES = 5):
retry = True
retries = 1
while (retry and (retries < MAX_RETRIES)):
try:
response = location.search_place_index_for_position(
IndexName=location_index,
Position=Position)
retry = False
return(response)
except botocore.exceptions.ClientError as error:
# wait for (2^retries * 100) milliseconds
time.sleep(2**retries * 100/1000)
if error.response['Error']['Code'] == 'ThrottlingException':
print('{}: API call limit exceeded; backing off and retrying...{}: retries: {}'.format(Position,error.response['Error']['Code'],retries))
retry = True
elif error.response['Error']['Code'] == 'InternalServerException':
print('{}: Internal Server Exception; backing off and retrying...{}: retries: {}'.format(Position,error.response['Error']['Code'],retries))
retry = True
elif error.response['Error']['Code'] == 'ValidationException':
print('{}: Exiting...{}'.format(Position,error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'AccessDeniedException':
print('{}: Exiting...{}'.format(Position, error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'ResourceNotFoundException':
print('{}: Exiting...{}'.format(Position,error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'TooManyRequestsException':
print('{}: API call limit exceeded; backing off and retrying...{}: retries: {}'.format(Position,error.response['Error']['Code'],retries))
retry = True
else:
print ("{}: Un-Identified Exception: {} || {}".format(Position, error, error.response['Error']['Code']))
retry = False
retries = retries + 1
print("{}: Giving up... Too many retries..".format(Position))
return("Error")
def write_location_to_cache (table_name, location_to_cache, MAX_RETRIES = 10):
retry = True
retries = 1
week = datetime.datetime.today() + datetime.timedelta(days=1)
expiryDateTime = int(time.mktime(week.timetuple()))
try:
response = ddb_client.put_item(
TableName=table_name,
Item={
"id": {
"S": location_to_cache["PrimaryKey"]
},
"Geometry": {
"S": json.dumps(location_to_cache["Geometry"])
},
"Country": {
"S": location_to_cache["Country"]
},
"Zipcode": {
"S": location_to_cache["Zipcode"]
},
"Latitude": {
"N": location_to_cache["Latitude"]
},
"Longitude": {
"N": location_to_cache["Longitude"]
},
"Label": {
"S": location_to_cache["Label"]
},
"Municipality": {
"S": location_to_cache["Municipality"]
},
"Region": {
"S": location_to_cache["Region"]
},
"SubRegion": {
"S": location_to_cache["SubRegion"]
},
"ttl": {
"N": str(expiryDateTime)
}
})
return(response)
except Exception as e:
print({"error":"cannot write to cache", "exception":str(e)})
return({"error":"cannot write to cache", "exception":str(e)})
def get_location_from_cache (table_name, primary_key, MAX_RETRIES = 10):
retry = True
retries = 1
try:
response = ddb_client.get_item(TableName=table_name, Key={"id": { "S": primary_key}})
cached_location = {}
if 'Item' in response:
for key, value in response['Item'].items():
if key == 'Geometry':
cached_location[key] = json.loads(value['S'])
if key == 'Country':
cached_location[key] = value['S']
if key == 'Zipcode':
cached_location[key] = value['S']
if key == 'Latitude':
cached_location[key] = value['N']
if key == 'Longitude':
cached_location[key] = value['N']
if key == 'Label':
cached_location[key] = value['S']
if key == 'Municipality':
cached_location[key] = value['S']
if key == 'Region':
cached_location[key] = value['S']
if key == 'SubRegion':
cached_location[key] = value['S']
return(cached_location)
else:
return({"error":"not found"})
except Exception as e:
print({"error":"cannot read from cache", "exception":str(e)})
return({"error":"cannot read from cache", "exception":str(e)})
def get_location_for_text (IndexName, Text, MAX_RETRIES = 10):
retry = True
retries = 1
while (retry and (retries < MAX_RETRIES)):
try:
response = location.search_place_index_for_text(
IndexName=location_index,
Text=Text)
retry = False
return(response)
except botocore.exceptions.ClientError as error:
# wait for (2^retries * 100) milliseconds
time.sleep(2**retries * 100/1000)
# status = Get the result of the asynchronous operation.
if error.response['Error']['Code'] == 'ThrottlingException':
print('{}: API call limit exceeded; backing off and retrying...{}: retries: {}'.format(Text,error.response['Error']['Code'],retries))
retry = True
elif error.response['Error']['Code'] == 'InternalServerException':
print('{}: Internal Server Exception; backing off and retrying...{}: retries: {}'.format(Text,error.response['Error']['Code'],retries))
retry = True
elif error.response['Error']['Code'] == 'ValidationException':
print('{}: Exiting...{}'.format(Text,error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'AccessDeniedException':
print('{}: Exiting...{}'.format(Text,error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'ResourceNotFoundException':
print('{}: Exiting...{}'.format(Text,error.response['Error']['Code']))
retry = False
elif error.response['Error']['Code'] == 'TooManyRequestsException':
print('{}: API call limit exceeded; backing off and retrying...{}: retries: {}'.format(Text,error.response['Error']['Code'],retries))
retry = True
else:
print ("{}: Un-Identified Exception: {} || {}".format(Text,error, error.response['Error']['Code']))
retry = False
retries = retries + 1
print("{}: Giving up... Too many retries..".format(Text))
return("Error")
def lambda_handler(event, context):
################################################################
# Get Pre-Processed Shard from S3 via a triggered GET #
################################################################
bucket_name = event["Payload"]["bucket"]
s3_file_key = event["Payload"]["shard"]
# s3_file_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
response = s3_client.get_object(Bucket=bucket_name, Key=s3_file_key)
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
if status == 200:
print(f"Successful S3 get_object response. Status - {status}")
data = pd.read_csv(response.get("Body")).dropna(thresh=2)
data = data.rename(columns=str.title)
columns = data.columns
Countries = []
Points = []
Latitude = []
Longitude = []
Labels = []
Regions = []
SubRegions = []
Municipalities = []
Zipcodes = []
Latitudes = []
Longitudes = []
location_to_cache = {}
###########################
# ReverseGeocoder #
###########################
if "Latitude" and "Longitude" in columns:
for index, row in data.iterrows():
try:
response_from_cache = get_location_from_cache (ddb_table, str(row.Longitude) +","+ str(row.Latitude))
if "error" in response_from_cache:
try:
print("Making API call to Places API")
response = get_location_for_position(location_index, [row.Longitude, row.Latitude])
json_response = response["Results"][0]["Place"]
print(json_response)
except Exception as e:
print("API Response Error: " + str(e))
print("API Response Error")
else:
print("Found Location in Cache")
json_response = response_from_cache
print(json_response)
json_response['Geometry']['Point'] = json.loads(json_response['Geometry']['Point'])
except Exception as e:
print("Exception reading from Cache: " + str(e))
try:
Country = (json_response["Country"])
Countries.append(Country)
except Exception as e:
Country = "0"
Countries.append(0)
try:
Point = (json_response["Geometry"]["Point"])
Points.append(Point)
except Exception as e:
Point = "0"
Points.append(0)
try:
Longitude = (Point[0])
print("Longitude: {}".format(Longitude))
Longitudes.append(Longitude)
except Exception as e:
Longitude = "0"
Longitudes.append(0)
print("Error: Lon unavailable for given input in row", (len(Points)) + 1)
try:
Latitude = (Point[1])
print("Latitude: {}".format(Latitude))
Latitudes.append(Latitude)
except Exception as e:
Latitude = "0"
Latitudes.append(0)
print("Error: Lat unavailable for given input in row", (len(Points)) + 1)
try:
Label = (json_response["Label"])
Labels.append(Label)
except Exception as e:
Label = "0"
Labels.append(0)
print("Error: Address unavailable for given input in row", (len(Points)) + 1)
try:
Zipcode = (json_response["PostalCode"])
Zipcodes.append(Zipcode)
except Exception as e:
Zipcode = "0"
Zipcodes.append(0)
try:
if "Municipality" in (json_response):
Municipality = (json_response["Municipality"])
Municipalities.append(Municipality)
else:
Municipality = "0"
Municipalities.append(0)
except Exception as e:
Municipality = "0"
Municipalities.append(0)
try:
Region = (json_response["Region"])
Regions.append(Region)
except Exception as e:
Region = "0"
Regions.append(0)
print("Error: Region unavailable for given input in row", (len(Points)) + 1)
try:
SubRegion = (json_response["SubRegion"])
SubRegions.append(SubRegion)
except Exception as e:
SubRegion = "0"
SubRegions.append(0)
print("Error: SubRegion unavailable for given input in row", (len(Points)) + 1)
location_to_cache["Geometry"]={}
location_to_cache["Geometry"]["Point"] = str(Point)
location_to_cache["Country"] = Country
location_to_cache["Zipcode"] = Zipcode
location_to_cache["Latitude"] = str(Latitude)
location_to_cache["Longitude"] = str(Longitude)
location_to_cache["Label"] = Label
location_to_cache["Municipality"] = Municipality
location_to_cache["Region"] = Region
location_to_cache["SubRegion"] = SubRegion
location_to_cache["PrimaryKey"] = str(row.Longitude) +","+ str(row.Latitude)
if "error" in response_from_cache:
print("Writing to Cache: {}".format(location_to_cache["PrimaryKey"]))
write_location_to_cache (ddb_table, location_to_cache)
print ("length of Points: {}".format(len(Points)))
print ("length of Countries: {}".format(len(Countries)))
print ("length of Latitude: {}".format(len(Latitudes)))
print ("length of Longitude: {}".format(len(Longitudes)))
print ("length of Labels: {}".format(len(Labels)))
print ("length of Municipalities: {}".format(len(Municipalities)))
print ("length of Regions: {}".format(len(Regions)))
print ("length of SubRegions: {}".format(len(SubRegions)))
data["Points"] = Points
data["Country"] = Countries
data["Latitude"] = Latitudes
data["Longitude"] = Longitudes
data["Label"] = Labels
data["Municipality"] = Municipalities
data["Region"] = Regions
data["SubRegion"] = SubRegions
data["Zipcode"] = Zipcodes
#########################################################
# Geocoder (for different possible column labels) #
#########################################################
elif "Address" in columns:
for index, row in data.iterrows():
try:
response_from_cache = get_location_from_cache (ddb_table, str(row.Address) + row.City + "," + row.State)
if "error" in response_from_cache:
try:
print("Making API call to Places API")
response = get_location_for_text(location_index, str(row.Address) + row.City + "," + row.State)
json_response = response["Results"][0]["Place"]
print(json_response)
except Exception as e:
print("API Response Error: " + str(e))
print("API Response Error")
else:
print("Found Location in Cache")
json_response = response_from_cache
json_response['Geometry']['Point'] = json.loads(json_response['Geometry']['Point'])
print(json_response)
except Exception as e:
print("Exception reading from Cache: " + str(e))
try:
Country = (json_response["Country"])
Countries.append(Country)
except Exception as e:
Country = "0"
Countries.append(0)
try:
Point = (json_response["Geometry"]["Point"])
Points.append(Point)
except Exception as e:
Point = "0"
Points.append(0)
try:
Longitude = (Point[0])
print("Longitude: {}".format(Longitude))
Longitudes.append(Longitude)
except Exception as e:
Longitude = "0"
Longitudes.append(0)
print("Error: Lon unavailable for given input in row", (len(Points)) + 1)
try:
Latitude = (Point[1])
print("Latitude: {}".format(Latitude))
Latitudes.append(Latitude)
except Exception as e:
Latitude = "0"
Latitudes.append(0)
print("Error: Lat unavailable for given input in row", (len(Points)) + 1)
try:
Label = (json_response["Label"])
Labels.append(Label)
except Exception as e:
Label = "0"
Labels.append(0)
print("Error: Address unavailable for given input in row", (len(Points)) + 1)
try:
Zipcode = (json_response["PostalCode"])
Zipcodes.append(Zipcode)
except Exception as e:
Zipcode = "0"
Zipcodes.append(0)
try:
if "Municipality" in (json_response):
Municipality = (json_response["Municipality"])
Municipalities.append(Municipality)
else:
Municipality = "0"
Municipalities.append(0)
except Exception as e:
Municipality = "0"
Municipalities.append(0)
try:
Region = (json_response["Region"])
Regions.append(Region)
except Exception as e:
Region = "0"
Regions.append(0)
print("Error: Region unavailable for given input in row", (len(Points)) + 1)
try:
SubRegion = (json_response["SubRegion"])
SubRegions.append(SubRegion)
except Exception as e:
SubRegion = "0"
SubRegions.append(0)
print("Error: SubRegion unavailable for given input in row", (len(Points)) + 1)
location_to_cache["Geometry"]={}
location_to_cache["Geometry"]["Point"] = str(Point)
location_to_cache["Country"] = Country
location_to_cache["Zipcode"] = Zipcode
location_to_cache["Latitude"] = str(Latitude)
location_to_cache["Longitude"] = str(Longitude)
location_to_cache["Label"] = Label
location_to_cache["Municipality"] = Municipality
location_to_cache["Region"] = Region
location_to_cache["SubRegion"] = SubRegion
location_to_cache["PrimaryKey"] = str(row.Address) + str(row.City) + "," + str(row.State)
if "error" in response_from_cache:
write_location_to_cache (ddb_table, location_to_cache)
print ("length of Points: {}".format(len(Points)))
print ("length of Countries: {}".format(len(Countries)))
print ("length of Latitude: {}".format(len(Latitudes)))
print ("length of Longitude: {}".format(len(Longitudes)))
print ("length of Labels: {}".format(len(Labels)))
print ("length of Municipalities: {}".format(len(Municipalities)))
print ("length of Regions: {}".format(len(Regions)))
print ("length of SubRegions: {}".format(len(SubRegions)))
data["Points"] = Points
data["Country"] = Countries
data["Latitude"] = Latitudes
data["Longitude"] = Longitudes
data["Label"] = Labels
data["Municipality"] = Municipalities
data["Region"] = Regions
data["SubRegion"] = SubRegions
data["Zipcode"] = Zipcodes
##################################################
# Write processed shard to S3 via a PUT #
##################################################
response_lambda={}
response_lambda['Payload']={}
with io.StringIO() as csv_buffer:
data.to_csv(csv_buffer, index=False)
response = s3_client.put_object(
Bucket=destination_bucket, Key=s3_file_key, Body=csv_buffer.getvalue()
)
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
if status == 200:
print(f"Successful S3 put_object response. Status - {status}")
response_lambda['Payload']={"shard": s3_file_key}
else:
print(f"Unsuccessful S3 put_object response. Status - {status}")
response_lambda['Payload']={"status": status}
return(response_lambda)