Skip to content

Instantly share code, notes, and snippets.

@jbnunn
Last active September 24, 2019 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbnunn/b935ef203d6e694d90405cc433bb06f8 to your computer and use it in GitHub Desktop.
Save jbnunn/b935ef203d6e694d90405cc433bb06f8 to your computer and use it in GitHub Desktop.
Rekognition Indexer
'''
A trigger function for AWS Lambda that listens for object creation in an S3 bucket,
takes images, finds faces, and tags with metadata into a DDB table.
'''
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="family_and_friends")
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']
key = urllib.parse.unquote_plus(
event['Records'][0]['s3']['object']['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('rekognition_family_and_friends',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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment