-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_function.py
75 lines (52 loc) · 2.29 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
72
73
74
75
import boto3
from decimal import Decimal
import json
import urllib.request
import urllib.parse
import urllib.error
print('Loading function')
rekognition = boto3.client('rekognition')
# --------------- Helper Functions to call Rekognition APIs ------------------
def detect_text(photo, bucket):
client=boto3.client('rekognition', 'us-east-2')
response=client.detect_text(Image={'S3Object':{'Bucket':bucket,'Name':photo}})
textDetections=response['TextDetections']
detected_text = ""
for text in textDetections:
if not 'ParentId' in text:
detected_text += ('Detected text: ' + text['DetectedText'] + ' @ Confidence: ' + "{:.2f}".format(text['Confidence']) + "%\n")
return detected_text
def upload_to_aws(data, bucket_name, s3_file):
encoded_data = data.encode("utf-8")
s3 = boto3.resource("s3")
s3.Bucket(bucket_name).put_object(Key=s3_file, Body=encoded_data)
# --------------- Main handler ------------------
def lambda_handler(event, context):
'''Demonstrates S3 trigger that uses
Rekognition APIs to detect faces, labels and index faces in S3 Object.
'''
print("Received event: " + json.dumps(event, indent=2))
# Get the object from the event
input_bucket = event['Records'][0]['s3']['bucket']['name']
print (input_bucket)
output_bucket = 'odt-receipt-output-bucket'
print(output_bucket)
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])
print(key)
response = ""
try:
# Calls rekognition DetectText API to detect faces in S3 object
response=detect_text(key,input_bucket)
print(response)
except Exception as e:
print(e)
print("Error processing object {} from bucket {}. ".format(key, input_bucket) +
"Make sure your object and bucket exist and your bucket is in the same region as this function.")
raise e
try:
upload_to_aws(response, output_bucket, key.replace(".jpg", "_output.txt"))
except Exception as e:
print(e)
print("Error processing object {} from bucket {}. ".format(key, output_bucket) +
"Make sure your object and bucket exist and your bucket is in the same region as this function.")
raise e