-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse_photo.py
executable file
·102 lines (86 loc) · 2.95 KB
/
parse_photo.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
from __future__ import print_function
import boto3
import json
import logging
import os
import urllib
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
from datetime import datetime
from dateutil import tz
logger = logging.getLogger()
logger.setLevel(logging.INFO)
region_name=os.environ['AWS_REGION']
dynamodb = boto3.resource('dynamodb', region_name)
photos_table = dynamodb.Table('owasp10-demo-Photos')
tags_table = dynamodb.Table('owasp10-demo-Tags')
photo_tags_table = dynamodb.Table('owasp10-demo-PhotosTags')
rekognition = boto3.client("rekognition", region_name)
def write_image_meta(file_object, bucket_object, event_time):
response = photos_table.put_item(
Item={
'photo_id': file_object['key'],
'upload_date': event_time,
'bucket': bucket_object['name'],
}
)
def write_image_tags(file_object, bucket_object, labels):
for x in labels["Labels"]:
response = tags_table.put_item(
Item={
'tag': x['Name'],
}
)
response = photo_tags_table.put_item(
Item={
'photo_id': file_object['key'],
'tag_id': x['Name'],
'confidence': int(x['Confidence'])
}
)
def detect_labels(key, bucket, max_labels=10, min_confidence=80):
logger.info(key)
logger.info(bucket)
response = rekognition.detect_labels(
Image={
"S3Object": {
"Bucket": bucket,
"Name": key,
}
},
MaxLabels=max_labels,
MinConfidence=min_confidence,
)
return response
def image_moderation (key, bucket, min_confidence=40):
response = rekognition.detect_moderation_labels(
Image={
"S3Object": {
"Bucket": bucket,
"Name": key,
}
},
MinConfidence=min_confidence,
)
return response
def run_reko(event, context):
logger.info('Event Data: ' + json.dumps(event))
file_object = event['Records'][0]['s3']['object']
file_key = urllib.parse.unquote_plus(file_object['key'], encoding ='utf8')
bucket_object = event['Records'][0]['s3']['bucket']
event_time = event['Records'][0]['eventTime']
moderation = image_moderation(file_key, bucket_object['name'])
if moderation['ModerationLabels']:
logger.info('Moderation Failed: ' + json.dumps(moderation))
logger.info('Deleting Object: ' + bucket_object['name'] + '/' + file_key)
client = boto3.client('s3')
response = client.delete_object(
Bucket=bucket_object['name'],
Key=file_key
)
logger.info(response)
else:
labels = detect_labels(file_key, bucket_object['name'])
write_image_meta(file_object, bucket_object, event_time)
write_image_tags(file_object, bucket_object, labels)
logger.info('Reko Labels: ' + json.dumps(labels))