-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
71 lines (51 loc) · 1.9 KB
/
lambda_function.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
from __future__ import print_function
import boto3
from decimal import Decimal
import json
import urllib
print('Loading function')
dynamodb = boto3.client('dynamodb')
s3 = boto3.client('s3')
rekognition = boto3.client('rekognition')
# --------------- Helper Functions ------------------
def index_faces(bucket, key):
response = rekognition.index_faces(
Image={"S3Object":
{"Bucket": bucket,
"Name": key}},
CollectionId="minor_facerecognition")
return response
def update_index(tableName,faceId, fullName):
response = dynamodb.put_item(
TableName=tableName,
Item={
'RekognitionId': {'S': faceId},
'FullName': {'S': fullName}
}
)
# --------------- Main handler ------------------
def lambda_handler(event, context):
# Get the object from the event
bucket = event['Records'][0]['s3']['bucket']['name']
print("Records: ",event['Records'])
key = event['Records'][0]['s3']['object']['key']
print("Key: ",key)
# key = key.encode()
# key = urllib.parse.unquote_plus(key)
try:
# Calls Amazon Rekognition IndexFaces API to detect faces in S3 object
# to index faces into specified collection
response = index_faces(bucket, key)
# Commit faceId and full name object metadata to DynamoDB
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
faceId = response['FaceRecords'][0]['Face']['FaceId']
ret = s3.head_object(Bucket=bucket,Key=key)
personFullName = ret['Metadata']['fullname']
update_index('facerecognition',faceId,personFullName)
# Print response to console
print(response)
return response
except Exception as e:
print(e)
print("Error processing object {} from bucket {}. ".format(key, bucket))
raise e