· 6 years ago · Jan 17, 2020, 10:10 AM
1import boto3
2from decimal import Decimal
3import json
4import requests
5
6
7print('Loading function')
8
9
10dynamodb = boto3.client('dynamodb')
11s3 = boto3.client('s3')
12rekognition = boto3.client('rekognition')
13
14
15# --------------- Helper Functions ------------------
16
17def index_faces(bucket, key):
18
19 response = rekognition.index_faces(
20 Image={"S3Object":
21 {"Bucket": bucket,
22 "Name": key}},
23 CollectionId="family_collection2")
24 return response
25
26def update_index(tableName,faceId, password,emailid):
27 response = dynamodb.put_item(
28 TableName=tableName,
29 Item={
30 'RekognitionId': {'S': faceId},
31 'Password': {'S': password},
32 'EmailID' : {'S': emailid}
33 }
34 )
35
36# --------------- Main handler ------------------
37
38def lambda_handler(event, context):
39
40 print(" I am being Triggered")
41
42 if event :
43 file_obj = event["Records"][0]
44 bucketname = str(file_obj['s3']['bucket']['name'])
45 print("Bucket Name: ", bucketname)
46 filename = str(file_obj['s3']['object']['key'])
47 print("Filename: ", filename)
48 print("Bucket Name and Filename successfully read");
49
50 try:
51
52 # Calls Amazon Rekognition IndexFaces API to detect faces in S3 object
53 # to index faces into specified collection
54
55 response = index_faces(bucketname, filename)
56
57 # Commit faceId and full name object metadata to DynamoDB
58
59 if response['ResponseMetadata']['HTTPStatusCode'] == 200:
60 faceId = response['FaceRecords'][0]['Face']['FaceId']
61
62 ret = s3.head_object(Bucket=bucketname,Key=filename)
63 personFullName = ret['Metadata']['password']
64 personEmailID = ret['Metadata']['emailid']
65
66 update_index('family_collection2',faceId,personFullName,personEmailID)
67
68 # Print response to console
69 print(response)
70
71 return response
72 except Exception as e:
73 print(e)
74 print("Error processing object {} from bucket {}. ".format(filename, bucketname))
75 raise e