├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── Commands.txt ├── LICENSE ├── NOTICE ├── README.md ├── StepfunctionInput.json ├── code ├── Rek_CheckBlackList_Dups.py ├── Rek_Demo.yaml ├── Rek_DetectFaces.py ├── Rek_DetectModerationLabels.py ├── Rek_ProcessFailure.py ├── Rek_ProcessImage.py ├── Rek_ProcessIndex.py ├── Rek_RecognizeCelebrities.py └── Rek_UpdateBlacklist.py └── images ├── Solution-Architecture.png ├── StepFunctions.png ├── StepFunctions_Failure.png ├── blackList └── barbie3.jpg └── test ├── Barack_Obama.jpg ├── Donald-Trump.jpg ├── I_woke_up_looking_this_good.jpg ├── Image Sources.txt ├── Kayla_Person-small.jpg ├── Les_Twins_profile.jpg ├── Mouth_Open.jpg ├── Texting-Smiling-Person.jpg ├── barbie1.jpg ├── barbie2.jpg ├── eyes_closed.jpg ├── funny-face.jpg ├── person1.jpg ├── person2.jpg ├── person3.jpg ├── person4.jpg ├── silhouette-of-a-man.jpg └── tom-cruise.jpg /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | lib/certifi-2017.7.27.1.dist-info/DESCRIPTION.rst 3 | 4 | lib/ 5 | code/certifi-2017.11.5.dist-info/ 6 | code/certifi/ 7 | 8 | code/chardet-3.0.4.dist-info/ 9 | code/chardet/ 10 | code/elasticsearch-5.4.0.dist-info/ 11 | code/elasticsearch/ 12 | code/idna-2.6.dist-info/ 13 | code/idna/ 14 | code/requests-2.18.4.dist-info/ 15 | code/requests/ 16 | code/urllib3-1.22.dist-info/ 17 | code/urllib3/ 18 | code/requests_aws4auth-0.9.dist-info/ 19 | code/requests_aws4auth/ 20 | code/Rek_demo_output.yaml 21 | code/elasticsearch-6.0.0.dist-info/ 22 | code/elasticsearch5/ 23 | code/*.rst 24 | code/NOTICE 25 | code/LICENSE 26 | 27 | -------------------------------------------------------------------------------- /Commands.txt: -------------------------------------------------------------------------------- 1 | aws s3 mb s3://rekdemo2017 --region us-west-2 2 | 3 | aws cloudformation package --template-file Rek_Demo.yaml --output-template-file Rek_demo_output.yaml --s3-bucket rekdemo2017 --region us-west-2 4 | 5 | aws cloudformation deploy --region us-west-2 --template-file Rek_demo_output.yaml --stack-name RekDemoStack --capabilities CAPABILITY_IAM -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Amazon Rekognition Policing User Content 2 | Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Amazon Rekognition Reviewing User Content 2 | 3 | A Stepfunctions driven workflow to use Amazon Rekognition to scan incoming images through a set of business rules and apply filtering, using AWS services like Amazon Rekognition, AWS Step Functions, Amazon DynamoDB and AWS Lambda. 4 | 5 | # Solution Architecture 6 | 7 | ![Solution Architecture](images/Solution-Architecture.png) 8 | 9 | Images can be captured by a camera (or a mobile device) and uploaded to S3. The image capture mechanism can be a website too. Once the image lands on the S3 bucket, the step functions flow can be triggered using a S3 event + Lambda (The S3 event triggering code is not included in this repository). 10 | Step functions then executes a series of checks with Amazon Rekognition and builds a json template of its findings, as it progresses through the workflow. The process is successful if all the steps succeed and unsuccessful if any of them fails. The results are logged into Amazon Elasticsearch service and you use Kibana to visualize the results. 11 | 12 | This repository contains the sample code for Lambda functions and Step functions as well as a SAM template to deploy the resources in an AWS region of your choice. 13 | 14 | The following checks are implemented as a part of this workflow: 15 | * Check for faces in the uploaded image. 16 | * Fail if no face or more than one face detected. 17 | * Fail if mouth is detected as open, eyes detected as closed, face not looking in the right direction etc. 18 | * Check for known celebrities 19 | * Fail if the uploaded image matches a known celebrity. 20 | * Image moderation filter 21 | * Fail if image contains explicit nudity or suggestive content 22 | * Blacklist / duplicate check 23 | * Fail if the image is already uploaded by somebody else 24 | * Fail if the image matches a custom black list that you maintain 25 | 26 | # Deployment and Execution 27 | 28 | ## Instructions 29 | This code depends on a bunch of libraries (not included in this distribution) which you will have to install yourself. You will be needing [AWS CLI](http://docs.aws.amazon.com/cli/latest/userguide/installing.html) as well. 30 | 31 | 1. Download the contents of this repository on your local machine (say: project-directory) 32 | 2. The solution is implemented in python, so make sure you have a working python environment on your local machine. 33 | 3. Open a command prompt, navigate to the project directory. Navigate to the /code sub directory and install the following libraries: 34 | 1. ```bash 35 | pip install requests_aws4auth --target . 36 | ``` 37 | 2. ``` bash 38 | pip install elasticsearch --target . 39 | ``` 40 | 4. Create a S3 bucket for deployment (note: use the same region throughout the following steps, I have used us-east-2, you can replace it with the region of your choice. Refer to the [region table](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) for service availability.) 41 | 1. ```bash 42 | aws s3 mb s3://rekdemo2017 --region us-west-2 43 | ``` 44 | 5. Prepare the SAM template: Open the Rek_Demo.yaml with your favorite editor and change the change the BucketName property of 'RekS3Bucket' to your choosing (say: S3Bucket). This is the bucket which will house the input images and the blacklist images to the StepFunctions state machine. 45 | 46 | 6. Package the contents and prepare deployment package using the following command 47 | 1. ```bash 48 | aws cloudformation package --template-file Rek_Demo.yaml --output-template-file Rek_demo_output.yaml --s3-bucket rekdemo2017 --region us-west-2 49 | ``` 50 | 7. Deploy the package 51 | 1. ```bash 52 | aws cloudformation deploy --template-file Rek_demo_output.yaml --stack-name RekDemoStack --capabilities CAPABILITY_IAM --region us-west-2 53 | ``` 54 | 8. If you want to make changes to the Lambda functions, you can do so on your local machine and redeploy them using the steps 6 and 7 above. The package and deploy commands take care of zipping up the new Lambda files(along with the dependencies) and uploading them to AWS for execution. 55 | 56 | 57 | ## Outputs 58 | Following are the outputs from the SAM template 59 | 60 | 1. **Elasticsearch Domain and Kibana endpoints:** You can use these endpoints to view the statistics about the uploaded images. Please note, you might have to modify the access policies for your ES instance, to allow access. Blog [here](https://aws.amazon.com/blogs/database/set-access-control-for-amazon-elasticsearch-service/). 61 | 62 | ## Execution 63 | The StepfunctionInput.json file contains sample invocations that you can use to trigger the worklow. The Step Functions state machine expects input to be passed in a particular format. You can change the values, but the structure is expected by the lambda functions that are triggered by the state function. 64 | 65 | 1. Upload Images: 66 | 1. Upload the images from the **project-directory**/images/test/ folder to **S3Bucket**/reInvent2017/RekognitionDemo/InputImages/. 67 | 2. Upload the images from the **project-directory**/images/blackList/ folder to **S3Bucket**/reInvent2017/RekognitionDemo/BlacklistImages/. 68 | 2. Navigate to your Step Functions console, choose the state machine that was deployed. 69 | 3. Click on 'New Execution'. 70 | 4. In the input window, you can paste any of the sample inputs from StepfunctionInput.json, or point to your own image file. 71 | 5. Click on 'Start Execution'. 72 | 73 | 74 | # Code Walkthrough 75 | 76 | ## Step functions flow (success) 77 | 78 | ![Step Functions flow](images/StepFunctions.png) 79 | 80 | For a successful iteration, you can expect all the states successfully executed. Below is the sample input to the 'ProcessSuccess' state. You can expect this input to the lambda function associated with this state and apply your custom processing logic in this lambda function. 81 | 82 | ```json 83 | { 84 | "Params": { 85 | "Bucket": "mayankdemo1-us-west-2", 86 | "Key": "reInvent2017/RekognitionDemo/InputImages/person1.jpg" 87 | }, 88 | "OverallResult": { 89 | "Reason": "", 90 | "Details": [ 91 | { 92 | "Pass": true, 93 | "ErrorMessages": [ 94 | "Gender of Face = Female" 95 | ], 96 | "Stage": "DetectFaces" 97 | }, 98 | { 99 | "ErrorMessages": [], 100 | "Stage": "RecognizeCelebrities", 101 | "Pass": true 102 | }, 103 | { 104 | "Pass": true, 105 | "ErrorMessages": [], 106 | "Stage": "DetectModerationLabels" 107 | }, 108 | { 109 | "ErrorMessages": [], 110 | "Stage": "CheckBlackList_Dups", 111 | "Pass": true 112 | }, 113 | { 114 | "ErrorMessages": [ 115 | "Image added to collection." 116 | ], 117 | "Pass": true, 118 | "Stage": "ProcessImage" 119 | } 120 | ], 121 | "Pass": true 122 | } 123 | } 124 | ``` 125 | 126 | ## Step functions flow (failure) 127 | 128 | ![Step Functions flow](images/StepFunctions_Failure.png) 129 | 130 | For a failed iteration, you can expect only some of the states successfully executed. Below is the sample input to the 'ProcessFailure' state, when a duplicate is detected. You can expect this input to the lambda function associated with this state and apply your custom processing logic in this lambda function. 131 | 132 | ```json 133 | { 134 | "Params": { 135 | "Bucket": "mayankdemo1-us-west-2", 136 | "Key": "reInvent2017/RekognitionDemo/InputImages/person1.jpg" 137 | }, 138 | "OverallResult": { 139 | "Reason": "BLACKLIST_DUPS_DETECTED", 140 | "Details": [ 141 | { 142 | "ErrorMessages": [ 143 | "Gender of Face = Female" 144 | ], 145 | "Stage": "DetectFaces", 146 | "Pass": true 147 | }, 148 | { 149 | "Pass": true, 150 | "ErrorMessages": [], 151 | "Stage": "RecognizeCelebrities" 152 | }, 153 | { 154 | "ErrorMessages": [], 155 | "Stage": "DetectModerationLabels", 156 | "Pass": true 157 | }, 158 | { 159 | "ErrorMessages": [ 160 | "Duplicate Image Detected." 161 | ], 162 | "Pass": false, 163 | "Stage": "CheckBlackList_Dups" 164 | } 165 | ], 166 | "Pass": false 167 | } 168 | } 169 | ``` 170 | 171 | ## License 172 | 173 | This library is licensed under the Apache 2.0 License. 174 | -------------------------------------------------------------------------------- /StepfunctionInput.json: -------------------------------------------------------------------------------- 1 | /*Test 1*/ 2 | { 3 | "Params" : { 4 | "Bucket": "mayankdemo1-us-west-2", 5 | "Key": "reInvent2017/RekognitionDemo/InputImages/silhouette-of-a-man.jpg" 6 | }, 7 | "OverallResult" : { 8 | "Pass" : "True", 9 | "Reason" : "", 10 | "Details" : [] 11 | } 12 | } 13 | 14 | 15 | /*Test 2*/ 16 | 17 | { 18 | "Params" : { 19 | "Bucket": "mayankdemo1-us-west-2", 20 | "Key": "reInvent2017/RekognitionDemo/InputImages/Les_Twins_profile.jpg" 21 | }, 22 | "OverallResult" : { 23 | "Pass" : "True", 24 | "Reason" : "", 25 | "Details" : [] 26 | } 27 | } 28 | 29 | /*Test 3*/ 30 | 31 | { 32 | "Params" : { 33 | "Bucket": "mayankdemo1-us-west-2", 34 | "Key": "reInvent2017/RekognitionDemo/InputImages/Texting-Smiling-Person.jpg" 35 | }, 36 | "OverallResult" : { 37 | "Pass" : "True", 38 | "Reason" : "", 39 | "Details" : [] 40 | } 41 | } 42 | 43 | 44 | 45 | 46 | /*Test 4*/ 47 | 48 | { 49 | "Params" : { 50 | "Bucket": "mayankdemo1-us-west-2", 51 | "Key": "reInvent2017/RekognitionDemo/InputImages/tom-cruise.jpg" 52 | }, 53 | "OverallResult" : { 54 | "Pass" : "True", 55 | "Reason" : "", 56 | "Details" : [] 57 | } 58 | } 59 | 60 | /*Test 5*/ 61 | 62 | { 63 | "Params" : { 64 | "Bucket": "mayankdemo1-us-west-2", 65 | "Key": "reInvent2017/RekognitionDemo/InputImages/person3.jpg" 66 | }, 67 | "OverallResult" : { 68 | "Pass" : "True", 69 | "Reason" : "", 70 | "Details" : [] 71 | } 72 | } 73 | 74 | 75 | /*Test 6*/ 76 | 77 | { 78 | "Params" : { 79 | "Bucket": "mayankdemo1-us-west-2", 80 | "Key": "reInvent2017/RekognitionDemo/InputImages/person1.jpg" 81 | }, 82 | "OverallResult" : { 83 | "Pass" : "True", 84 | "Reason" : "", 85 | "Details" : [] 86 | } 87 | } -------------------------------------------------------------------------------- /code/Rek_CheckBlackList_Dups.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | import os 8 | 9 | print('Loading function') 10 | 11 | rekognition = boto3.client('rekognition') 12 | s3 = boto3.client('s3') 13 | 14 | blacklist_bucket = os.environ['BLACKLIST_BUCKET'] 15 | blacklist_prefix = urllib.unquote_plus(os.environ['BLACKLIST_PREFIX'].encode('utf8')) 16 | 17 | # --------------- Helper Functions to call Rekognition APIs ------------------ 18 | 19 | 20 | 21 | 22 | def check_Blacklist_Duplicates(bucket, key, inputParams): 23 | 24 | returnResult = { 25 | 'Stage' : 'CheckBlackList_Dups', 26 | 'Pass': True, 27 | 'ErrorMessages': [] 28 | } 29 | 30 | blackListMatchDetected = False 31 | duplicateMatchDetected = False 32 | # Check in the blackList first 33 | response = rekognition.search_faces_by_image( 34 | CollectionId='BlackListImages', Image={"S3Object": {"Bucket": bucket, "Name": key}}, MaxFaces=1) 35 | #print ('Checking BlackList') 36 | # print(response) 37 | # Check for at least one face returned 38 | if (response.get('FaceMatches') is not None and len(response['FaceMatches']) > 0): 39 | blackListMatchDetected = True 40 | returnResult['Pass'] = False 41 | returnResult['ErrorMessages'].append('Blacklist Match Detected.') 42 | #print ('blackListMatchDetected = {}'.format(blackListMatchDetected)) 43 | 44 | if not blackListMatchDetected: 45 | # Check in our image collection, for duplicates 46 | response = rekognition.search_faces_by_image( 47 | CollectionId='ImageList', Image={"S3Object": {"Bucket": bucket, "Name": key}}, MaxFaces=1) 48 | 49 | #print ('Checking Duplicates') 50 | # print(response) 51 | if (response.get('FaceMatches') is not None and response['FaceMatches']): 52 | duplicateMatchDetected = True 53 | # print ('duplicateMatchDetected = {}'.format(duplicateMatchDetected)) 54 | returnResult['Pass'] = False 55 | returnResult['ErrorMessages'].append('Duplicate Image Detected.') 56 | 57 | # process overall result 58 | inputParams['OverallResult']['Details'].append(returnResult) 59 | inputParams['OverallResult']['Pass'] = inputParams['OverallResult']['Pass'] and returnResult['Pass'] 60 | if (returnResult['Pass'] is False): 61 | inputParams['OverallResult']['Reason'] = 'BLACKLIST_DUPS_DETECTED' 62 | else: 63 | inputParams['OverallResult']['Reason'] = '' 64 | 65 | return inputParams 66 | 67 | def create_collections(): 68 | 69 | doesBlackListImagesExist = False 70 | doesImageListExist = False 71 | 72 | # Get all the collections 73 | response = rekognition.list_collections(MaxResults=100) 74 | 75 | for collectionId in response['CollectionIds']: 76 | if(collectionId == 'BlackListImages'): 77 | doesBlackListImagesExist = True 78 | if(collectionId == 'ImageList'): 79 | doesImageListExist = True 80 | 81 | # Create a blacklist collection 82 | if not doesBlackListImagesExist: 83 | print('Creating collection : BlackListImages...') 84 | rekognition.create_collection(CollectionId='BlackListImages') 85 | # Add BlackList Images 86 | print('Adding BlackList Images..') 87 | imageList = s3.list_objects_v2( 88 | Bucket=blacklist_bucket, Prefix=blacklist_prefix) 89 | #print(imageList) 90 | for image in imageList['Contents']: 91 | if(image['Size'] == 0): 92 | continue 93 | print('Adding ' + image['Key']) 94 | rekognition.index_faces(CollectionId='BlackListImages', Image={"S3Object": { 95 | "Bucket": blacklist_bucket, "Name": image['Key']}}) 96 | 97 | # Create a image collection 98 | if not doesImageListExist: 99 | print('Creating collection : ImageList') 100 | rekognition.create_collection(CollectionId='ImageList') 101 | return None 102 | 103 | # --------------- Main handler ------------------ 104 | 105 | 106 | def lambda_handler(event, context): 107 | 108 | #print("Received event: " + json.dumps(event, indent=2)) 109 | 110 | # Get the object from the event 111 | bucket = event['Params']['Bucket'] 112 | key = urllib.unquote_plus(event['Params']['Key'].encode('utf8')) 113 | try: 114 | 115 | # try: 116 | # # delete collections. 117 | # rekognition.delete_collection(CollectionId ='BlackListImages') 118 | # rekognition.delete_collection(CollectionId ='ImageList') 119 | 120 | # except Exception as e: 121 | # print ('Error deleting collections.') 122 | 123 | # Create image collections. 124 | create_collections() 125 | 126 | response = check_Blacklist_Duplicates(bucket, key, event) 127 | 128 | # Print response to console. 129 | # print(response) 130 | 131 | return response 132 | except Exception as e: 133 | print(e) 134 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 135 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 136 | raise e 137 | -------------------------------------------------------------------------------- /code/Rek_Demo.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Resources: 4 | 5 | StatesExecutionRole: 6 | Type: "AWS::IAM::Role" 7 | Properties: 8 | AssumeRolePolicyDocument: 9 | Version: "2012-10-17" 10 | Statement: 11 | - 12 | Effect: "Allow" 13 | Principal: 14 | Service: 15 | - !Sub states.${AWS::Region}.amazonaws.com 16 | Action: "sts:AssumeRole" 17 | Path: "/" 18 | Policies: 19 | - 20 | PolicyName: StatesExecutionPolicy 21 | PolicyDocument: 22 | Version: "2012-10-17" 23 | Statement: 24 | - 25 | Effect: Allow 26 | Action: 27 | - "lambda:InvokeFunction" 28 | Resource: "*" 29 | 30 | RekLambdaExecutionRole: 31 | Type: "AWS::IAM::Role" 32 | Properties: 33 | AssumeRolePolicyDocument: 34 | Version: "2012-10-17" 35 | Statement: 36 | - 37 | Effect: "Allow" 38 | Principal: 39 | Service: 40 | - lambda.amazonaws.com 41 | Action: "sts:AssumeRole" 42 | Path: "/" 43 | Policies: 44 | - 45 | PolicyName: "AccessES" 46 | PolicyDocument: 47 | Version: "2012-10-17" 48 | Statement: 49 | - 50 | Effect: "Allow" 51 | Action: "es:*" 52 | Resource: !Join ["", [!GetAtt ElasticsearchDomain.DomainArn, "/*" ]] 53 | ManagedPolicyArns: 54 | - arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess 55 | - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 56 | - arn:aws:iam::aws:policy/AmazonRekognitionFullAccess 57 | 58 | RekS3Bucket: 59 | Type: AWS::S3::Bucket 60 | Properties: 61 | BucketName: !Sub mayankdemo1-${AWS::Region} 62 | 63 | ElasticsearchDomain: 64 | Type: "AWS::Elasticsearch::Domain" 65 | Properties: 66 | DomainName: "aws-rekognition-sample" 67 | ElasticsearchVersion: "5.5" 68 | ElasticsearchClusterConfig: 69 | InstanceCount: "1" 70 | InstanceType: "m4.large.elasticsearch" 71 | ZoneAwarenessEnabled: "false" 72 | EBSOptions: 73 | EBSEnabled: "true" 74 | VolumeSize: 35 75 | VolumeType: "gp2" 76 | SnapshotOptions: 77 | AutomatedSnapshotStartHour: "0" 78 | AccessPolicies: 79 | Version: "2012-10-17" 80 | Statement: 81 | - 82 | Effect: "Allow" 83 | Principal: 84 | AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root" 85 | Action: "es:*" 86 | Resource: !Sub "arn:aws:es:${AWS::Region}:${AWS::AccountId}:domain/aws-rekognition-sample/*" 87 | AdvancedOptions: 88 | rest.action.multi.allow_explicit_index: "true" 89 | 90 | RekDetectFaces: 91 | Type: AWS::Serverless::Function 92 | Properties: 93 | Handler: Rek_DetectFaces.lambda_handler 94 | Description: "Lambda function to detect face attributes using Rekognition" 95 | Runtime: python2.7 96 | FunctionName: Rek_DetectFaces 97 | Role: !GetAtt RekLambdaExecutionRole.Arn 98 | MemorySize: 128 99 | Timeout: 60 100 | 101 | RekRecognizeCelebrities: 102 | Type: AWS::Serverless::Function 103 | Properties: 104 | Handler: Rek_RecognizeCelebrities.lambda_handler 105 | Description: "Lambda function which uses Rekognition to detect presence of celebrities" 106 | Runtime: python2.7 107 | FunctionName: Rek_RecognizeCelebrities 108 | Role: !GetAtt RekLambdaExecutionRole.Arn 109 | MemorySize: 128 110 | Timeout: 60 111 | 112 | 113 | RekDetectModerationLabels: 114 | Type: AWS::Serverless::Function 115 | Properties: 116 | Handler: Rek_DetectModerationLabels.lambda_handler 117 | Description: "Lambda function which uses Rekognition to detect image moderation labels" 118 | Runtime: python2.7 119 | FunctionName: Rek_DetectModerationLabels 120 | Role: !GetAtt RekLambdaExecutionRole.Arn 121 | MemorySize: 128 122 | Timeout: 60 123 | 124 | RekCheckBlackListDups: 125 | Type: AWS::Serverless::Function 126 | Properties: 127 | Handler: Rek_CheckBlackList_Dups.lambda_handler 128 | Description: "A Lambda function to compare the given image against blacklist and duplicate image collections" 129 | Runtime: python2.7 130 | FunctionName: Rek_CheckBlackList_Dups 131 | Role: !GetAtt RekLambdaExecutionRole.Arn 132 | MemorySize: 128 133 | Timeout: 60 134 | Environment: 135 | Variables: 136 | BLACKLIST_PREFIX: reInvent2017/RekognitionDemo/BlacklistImages/ 137 | BLACKLIST_BUCKET: !Ref RekS3Bucket 138 | 139 | RekUpdateBlackList: 140 | Type: AWS::Serverless::Function 141 | Properties: 142 | Handler: Rek_UpdateBlacklist.lambda_handler 143 | Description: "A Lambda function, which will be triggered from an S3 event and adds the image to the image blacklist." 144 | Runtime: python2.7 145 | FunctionName: Rek_UpdateBlacklist 146 | Role: !GetAtt RekLambdaExecutionRole.Arn 147 | MemorySize: 128 148 | Timeout: 60 149 | Events: 150 | PhotoUpload: 151 | Type: S3 152 | Properties: 153 | Bucket: !Ref RekS3Bucket 154 | Events: s3:ObjectCreated:* 155 | Filter: 156 | S3Key: 157 | Rules: 158 | - 159 | Name: prefix 160 | Value: reInvent2017/RekognitionDemo/BlacklistImages/ 161 | - 162 | Name: suffix 163 | Value: jpg 164 | 165 | 166 | RekProcessImage: 167 | Type: AWS::Serverless::Function 168 | Properties: 169 | Handler: Rek_ProcessImage.lambda_handler 170 | Description: "A Lambda function to add the image to the collection using Rekognition" 171 | Runtime: python2.7 172 | FunctionName: Rek_ProcessImage 173 | Role: !GetAtt RekLambdaExecutionRole.Arn 174 | MemorySize: 128 175 | Timeout: 60 176 | 177 | RekProcessFailure: 178 | Type: AWS::Serverless::Function 179 | Properties: 180 | Handler: Rek_ProcessFailure.lambda_handler 181 | Description: "A Lambda function to process failure routines when the image does not clear of the stages" 182 | Runtime: python2.7 183 | FunctionName: Rek_ProcessFailure 184 | Role: !GetAtt RekLambdaExecutionRole.Arn 185 | MemorySize: 128 186 | Timeout: 60 187 | 188 | RekProcessIndex: 189 | Type: AWS::Serverless::Function 190 | Properties: 191 | Handler: Rek_ProcessIndex.lambda_handler 192 | Description: "A Lambda function to add a record to the elastic search domain" 193 | Runtime: python2.7 194 | FunctionName: Rek_ProcessIndex 195 | Role: !GetAtt RekLambdaExecutionRole.Arn 196 | MemorySize: 128 197 | Timeout: 60 198 | Environment: 199 | Variables: 200 | ES_ENDPOINT: !GetAtt ElasticsearchDomain.DomainEndpoint 201 | 202 | ReInvent2017RekognitionDemo: 203 | Type: "AWS::StepFunctions::StateMachine" 204 | Properties: 205 | DefinitionString: 206 | !Sub 207 | - |- 208 | { 209 | "Comment": "A state machine to automate User Generated Content policing.", 210 | "StartAt": "DetectFaces", 211 | "States": { 212 | "DetectFaces": { 213 | "Type": "Task", 214 | "Resource": "${Rek_DetectFaces_Arn}", 215 | "Next": "IsFaceProper", 216 | "InputPath": "$", 217 | "ResultPath": "$", 218 | "OutputPath": "$" 219 | }, 220 | "IsFaceProper": { 221 | "Type": "Choice", 222 | "Choices": [ 223 | { 224 | "Variable": "$.OverallResult.Pass", 225 | "BooleanEquals": true, 226 | "Next": "CheckForCelebrities" 227 | }, 228 | { 229 | "Variable": "$.OverallResult.Pass", 230 | "BooleanEquals": false, 231 | "Next": "ProcessFailure" 232 | } 233 | ], 234 | "Default": "ProcessFailure" 235 | }, 236 | "CheckForCelebrities": { 237 | "Type": "Task", 238 | "Resource": "${Rek_RecognizeCelebrities_Arn}", 239 | "Next": "IsCelebtrityDetected", 240 | "InputPath": "$", 241 | "ResultPath": "$", 242 | "OutputPath": "$" 243 | }, 244 | "IsCelebtrityDetected": { 245 | "Type": "Choice", 246 | "Choices": [ 247 | { 248 | "Variable": "$.OverallResult.Pass", 249 | "BooleanEquals": false, 250 | "Next": "ProcessFailure" 251 | }, 252 | { 253 | "Variable": "$.OverallResult.Pass", 254 | "BooleanEquals": true, 255 | "Next": "CheckImageModeration" 256 | } 257 | ], 258 | "Default": "ProcessFailure" 259 | }, 260 | 261 | "CheckImageModeration": { 262 | "Type": "Task", 263 | "Resource": "${Rek_DetectModerationLabels_Arn}", 264 | "Next": "IsImageModerated", 265 | "InputPath": "$", 266 | "ResultPath": "$", 267 | "OutputPath": "$" 268 | }, 269 | 270 | "IsImageModerated": { 271 | "Type": "Choice", 272 | "Choices": [ 273 | { 274 | "Variable": "$.OverallResult.Pass", 275 | "BooleanEquals": true, 276 | "Next": "SearchBlackList_Dups" 277 | }, 278 | { 279 | "Variable": "$.OverallResult.Pass", 280 | "BooleanEquals": false, 281 | "Next": "ProcessFailure" 282 | } 283 | ], 284 | "Default": "ProcessFailure" 285 | }, 286 | "SearchBlackList_Dups": { 287 | "Type": "Task", 288 | "Resource": "${Rek_CheckBlackList_Dups_Arn}", 289 | "Next": "CheckBlackList_Dups", 290 | "InputPath": "$", 291 | "ResultPath": "$", 292 | "OutputPath": "$" 293 | }, 294 | "CheckBlackList_Dups": { 295 | "Type": "Choice", 296 | "Choices": [ 297 | { 298 | "Variable": "$.OverallResult.Pass", 299 | "BooleanEquals": true, 300 | "Next": "ProcessSuccess" 301 | }, 302 | { 303 | "Variable": "$.OverallResult.Pass", 304 | "BooleanEquals": false, 305 | "Next": "ProcessFailure" 306 | } 307 | ], 308 | "Default": "ProcessFailure" 309 | }, 310 | "ProcessFailure": { 311 | "Type": "Task", 312 | "Next": "IndexImage", 313 | "Resource": "${Rek_ProcessFailure_Arn}", 314 | "InputPath": "$", 315 | "ResultPath": "$", 316 | "OutputPath": "$" 317 | }, 318 | "ProcessSuccess": { 319 | "Type": "Task", 320 | "Resource": "${Rek_ProcessImage_Arn}", 321 | "Next": "IndexImage", 322 | "InputPath": "$", 323 | "ResultPath": "$", 324 | "OutputPath": "$" 325 | }, 326 | 327 | "IndexImage": { 328 | "Type": "Task", 329 | "Resource": "${Rek_ProcessIndex_Arn}", 330 | "End": true, 331 | "InputPath": "$", 332 | "ResultPath": "$", 333 | "OutputPath": "$" 334 | } 335 | } 336 | } 337 | - {Rek_DetectFaces_Arn: !GetAtt [ RekDetectFaces, Arn ], Rek_RecognizeCelebrities_Arn: !GetAtt [ RekRecognizeCelebrities, Arn ],Rek_DetectModerationLabels_Arn: !GetAtt [ RekDetectModerationLabels, Arn ],Rek_CheckBlackList_Dups_Arn: !GetAtt [ RekCheckBlackListDups, Arn ],Rek_ProcessFailure_Arn: !GetAtt [ RekProcessFailure, Arn ],Rek_ProcessImage_Arn: !GetAtt [ RekProcessImage, Arn ],Rek_ProcessIndex_Arn: !GetAtt [ RekProcessIndex, Arn ]} 338 | RoleArn: !GetAtt [ StatesExecutionRole, Arn ] 339 | 340 | Outputs: 341 | ElasticsearchDomainEndPoint: 342 | Description: The Domain endpoint of the ElasticSearch service instance 343 | Value: !Join ["", ["https://", !GetAtt ElasticsearchDomain.DomainEndpoint]] 344 | ElasticsearchDomainKibanaEndPoint: 345 | Description: The Domain endpoint for accesing Kibana on the ES service endpoint 346 | Value: !Join ["", ["https://", !GetAtt ElasticsearchDomain.DomainEndpoint, "/_plugin/kibana/" ]] 347 | 348 | -------------------------------------------------------------------------------- /code/Rek_DetectFaces.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | 8 | print('Loading function') 9 | 10 | rekognition = boto3.client('rekognition') 11 | 12 | 13 | # --------------- Helper Functions to call Rekognition APIs ------------------ 14 | 15 | 16 | def detect_faces(bucket, key, inputParams): 17 | DetectFacesResult = { 18 | 'Stage': 'DetectFaces', 19 | 'Pass': True, 20 | 'ErrorMessages': [] 21 | } 22 | response = rekognition.detect_faces( 23 | Image={"S3Object": {"Bucket": bucket, "Name": key}}, Attributes=['ALL']) 24 | # print(str(len(response['FaceDetails']))) 25 | if (len(response['FaceDetails']) == 0): 26 | # print ('No Face Detected.') 27 | DetectFacesResult['Pass'] = False 28 | DetectFacesResult['ErrorMessages'].append('No Face Detected.') 29 | elif (len(response['FaceDetails']) > 1): 30 | # print ('More than one face detected.') 31 | DetectFacesResult['Pass'] = False 32 | DetectFacesResult['ErrorMessages'].append( 33 | 'More than one face detected.') 34 | else: 35 | faceDetail = response['FaceDetails'][0] 36 | if (faceDetail.get('MouthOpen') is not None and faceDetail['MouthOpen']['Value'] is True and Decimal(str(faceDetail['MouthOpen']['Confidence'])) >= 90.0): 37 | # print('Face Detected with Mouth Open.') 38 | DetectFacesResult['Pass'] = False 39 | DetectFacesResult['ErrorMessages'].append( 40 | 'Face Detected with Mouth Open.') 41 | if (faceDetail.get('Sunglasses') is not None and faceDetail['Sunglasses']['Value'] is True and Decimal(str(faceDetail['Sunglasses']['Confidence'])) >= 90.0): 42 | # print('Face Detected with Sunglasses.') 43 | DetectFacesResult['Pass'] = False 44 | DetectFacesResult['ErrorMessages'].append( 45 | 'Face Detected with Sunglasses.') 46 | if (faceDetail.get('EyesOpen') is not None and faceDetail['EyesOpen']['Value'] is False and Decimal(str(faceDetail['EyesOpen']['Confidence'])) >= 90.0): 47 | # print('Face Detected with eyes closed.') 48 | DetectFacesResult['Pass'] = False 49 | DetectFacesResult['ErrorMessages'].append( 50 | 'Face Detected with eyes closed.') 51 | if(faceDetail.get('Gender') is not None): 52 | # print ('Gender of Face = {}'.format(faceDetail['Gender']['Value'])) 53 | DetectFacesResult['ErrorMessages'].append( 54 | 'Gender of Face = {}'.format(faceDetail['Gender']['Value'])) 55 | # Check for age range 56 | ageRange = faceDetail.get('AgeRange') 57 | if(ageRange is not None and int(str(ageRange['Low'])) <= 18): 58 | # print ('Face corresponds to a minor') 59 | DetectFacesResult['Pass'] = False 60 | DetectFacesResult['ErrorMessages'].append('Face corresponds to a minor.') 61 | 62 | # Check for pose 63 | pose = faceDetail.get('Pose') 64 | if(pose is not None and (Decimal(str(pose['Pitch'])) <= -20 or Decimal(str(pose['Pitch'])) >= 20 or Decimal(str(pose['Roll'])) <= -20 or Decimal(str(pose['Roll'])) >= 20 or Decimal(str(pose['Yaw'])) <= -20 or Decimal(str(pose['Yaw'])) >= 20)): 65 | # print ('Face not looking in the right direction.') 66 | DetectFacesResult['Pass'] = False 67 | DetectFacesResult['ErrorMessages'].append( 68 | 'Face not looking in the right direction.') 69 | 70 | 71 | 72 | # process overall result 73 | inputParams['OverallResult']['Details'].append(DetectFacesResult) 74 | inputParams['OverallResult']['Pass'] = inputParams['OverallResult']['Pass'] and DetectFacesResult['Pass'] 75 | if (DetectFacesResult['Pass'] is False): 76 | inputParams['OverallResult']['Reason'] = 'FACIAL_ANALYSIS_FAILURE' 77 | else: 78 | inputParams['OverallResult']['Reason'] = '' 79 | 80 | return inputParams 81 | 82 | 83 | # --------------- Main handler ------------------ 84 | 85 | 86 | def lambda_handler(event, context): 87 | #print("Received event: " + json.dumps(event, indent=2)) 88 | 89 | # Get the object from the event 90 | bucket = event['Params']['Bucket'] 91 | key = urllib.unquote_plus(event['Params']['Key'].encode('utf8')) 92 | try: 93 | # Calls rekognition DetectFaces API to detect faces in S3 object 94 | returnResult = detect_faces(bucket, key, event) 95 | 96 | # Print response to console. 97 | # print(response) 98 | 99 | return returnResult 100 | except Exception as e: 101 | print(e) 102 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 103 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 104 | raise e 105 | -------------------------------------------------------------------------------- /code/Rek_DetectModerationLabels.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | 8 | print('Loading function') 9 | 10 | rekognition = boto3.client('rekognition') 11 | 12 | 13 | # --------------- Helper Functions to call Rekognition APIs ------------------ 14 | 15 | 16 | def detect_moderation_labels(bucket, key, inputParams): 17 | returnResult = { 18 | 'Stage' : 'DetectModerationLabels', 19 | 'Pass': True, 20 | 'ErrorMessages': [] 21 | } 22 | response = rekognition.detect_moderation_labels( 23 | Image={"S3Object": {"Bucket": bucket, "Name": key}}, MinConfidence=10) 24 | for modLabel in response['ModerationLabels']: 25 | if((modLabel['ParentName'] == 'Explicit Nudity' or modLabel['Name'] == 'Explicit Nudity') and Decimal(str(modLabel['Confidence'])) >= 70): 26 | # print('Image has Explicit Content.') 27 | returnResult['Pass'] = False 28 | returnResult['ErrorMessages'].append('Image has Explicit Content.') 29 | break 30 | if((modLabel['ParentName'] == 'Suggestive' or modLabel['Name'] == 'Suggestive') and Decimal(str(modLabel['Confidence'])) >= 70): 31 | # print('Image has Suggestive Content.') 32 | returnResult['Pass'] = False 33 | returnResult['ErrorMessages'].append('Image has Suggestive Content.') 34 | break 35 | 36 | # process overall result 37 | inputParams['OverallResult']['Details'].append(returnResult) 38 | inputParams['OverallResult']['Pass'] = inputParams['OverallResult']['Pass'] and returnResult['Pass'] 39 | if (returnResult['Pass'] is False): 40 | inputParams['OverallResult']['Reason'] = 'IMAGE_MODERATION_APPLIED' 41 | else: 42 | inputParams['OverallResult']['Reason'] = '' 43 | 44 | return inputParams 45 | 46 | 47 | # --------------- Main handler ------------------ 48 | 49 | 50 | def lambda_handler(event, context): 51 | 52 | #print("Received event: " + json.dumps(event, indent=2)) 53 | 54 | # Get the object from the event 55 | bucket = event['Params']['Bucket'] 56 | key = urllib.unquote_plus(event['Params']['Key'].encode('utf8')) 57 | try: 58 | # Calls rekognition DetectModerationLabels API to detect faces in S3 object 59 | response = detect_moderation_labels(bucket, key, event) 60 | 61 | # Print response to console. 62 | # print(response) 63 | 64 | return response 65 | except Exception as e: 66 | print(e) 67 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 68 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 69 | raise e 70 | -------------------------------------------------------------------------------- /code/Rek_ProcessFailure.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | 5 | 6 | print('Loading function') 7 | 8 | 9 | # --------------- Main handler ------------------ 10 | 11 | 12 | def lambda_handler(event, context): 13 | 14 | #print("Received event: " + json.dumps(event, indent=2)) 15 | # do some failure processing here 16 | return event 17 | -------------------------------------------------------------------------------- /code/Rek_ProcessImage.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | import os 8 | 9 | print('Loading function') 10 | 11 | rekognition = boto3.client('rekognition') 12 | s3 = boto3.client('s3') 13 | 14 | # --------------- Helper Functions to call Rekognition APIs ------------------ 15 | 16 | 17 | def create_collections(): 18 | 19 | doesImageListExist = False 20 | 21 | # Get all the collections 22 | response = rekognition.list_collections(MaxResults=100) 23 | 24 | for collectionId in response['CollectionIds']: 25 | if(collectionId == 'ImageList'): 26 | doesImageListExist = True 27 | 28 | # Create a collection to store and Index faces 29 | if not doesImageListExist: 30 | print('Creating collection : ImageList') 31 | rekognition.create_collection(CollectionId='ImageList') 32 | 33 | return None 34 | 35 | # --------------- Main handler ------------------ 36 | 37 | 38 | def lambda_handler(event, context): 39 | 40 | 41 | # Get the object from the event 42 | bucket = event['Params']['Bucket'] 43 | key = urllib.unquote_plus(event['Params']['Key'].encode('utf8')) 44 | returnResult = { 45 | 'Stage' : 'ProcessImage', 46 | 'Pass': True, 47 | 'ErrorMessages': [] 48 | } 49 | try: 50 | 51 | #Uncomment the delete code to clear off the Imagelist collection and start off fresh. 52 | # try: 53 | # # delete collections. 54 | # rekognition.delete_collection(CollectionId ='ImageList') 55 | # except Exception as e: 56 | # print ('Error deleting collections.') 57 | 58 | # Create image collections. 59 | create_collections() 60 | 61 | 62 | print('Adding image to collection') 63 | response = rekognition.index_faces(CollectionId='ImageList', Image={"S3Object": { 64 | "Bucket": bucket, "Name": key}}) 65 | returnResult['ErrorMessages'].append('Image added to collection.') 66 | 67 | # process overall result 68 | event['OverallResult']['Details'].append(returnResult) 69 | event['OverallResult']['Pass'] = event['OverallResult']['Pass'] and returnResult['Pass'] 70 | if (returnResult['Pass'] is False): 71 | event['OverallResult']['Reason'] = 'IMAGE_NOT_ADDED' 72 | else: 73 | event['OverallResult']['Reason'] = '' 74 | # Print response to console. 75 | # print(response) 76 | 77 | return event 78 | except Exception as e: 79 | print(e) 80 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 81 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 82 | raise e 83 | -------------------------------------------------------------------------------- /code/Rek_ProcessIndex.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | import datetime 5 | import json 6 | from elasticsearch import Elasticsearch, RequestsHttpConnection 7 | import requests 8 | from requests_aws4auth import AWS4Auth 9 | 10 | import json 11 | import os 12 | 13 | s3 = boto3.client('s3') 14 | 15 | print('Loading function') 16 | 17 | es_conn_string = os.environ['ES_ENDPOINT'] 18 | 19 | indexDoc = { 20 | "dataRecord": { 21 | "properties": { 22 | "createdDate": { 23 | "type": "date", 24 | "format": "dateOptionalTime" 25 | }, 26 | "objectKey": { 27 | "type": "string" 28 | }, 29 | "objectBucket": { 30 | "type": "string" 31 | }, 32 | "overallResult": { 33 | "type": "string" 34 | }, 35 | "reason": { 36 | "type": "string" 37 | } 38 | } 39 | }, 40 | "settings": { 41 | "number_of_shards": 1, 42 | "number_of_replicas": 0 43 | } 44 | } 45 | 46 | 47 | def connectES(esEndPoint): 48 | print ('Connecting to the ES Endpoint {0}...'.format(esEndPoint)) 49 | try: 50 | # print (esEndPoint) 51 | # Use AWS4Auth for signing the requst to ES. This is required since the Lambda function is operating under an IAM role. 52 | # please note, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION and AWS_SESSION_TOKEN environment variables are available to all Lambda functions. 53 | auth = AWS4Auth(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'], 54 | os.environ['AWS_REGION'], 'es', session_token=os.environ['AWS_SESSION_TOKEN']) 55 | esClient = Elasticsearch( 56 | hosts=[{'host': esEndPoint, 'port': 443}], 57 | use_ssl=True, 58 | verify_certs=True, 59 | connection_class=RequestsHttpConnection, 60 | http_auth=auth) 61 | print('Connection successful.') 62 | return esClient 63 | except Exception as E: 64 | print("Unable to connect to {0}".format(esEndPoint)) 65 | print("Error: ", E) 66 | return None 67 | # exit(3) 68 | 69 | 70 | def createIndex(esClient): 71 | try: 72 | print('Checking for index...') 73 | res = esClient.indices.exists('image-metadata-store') 74 | print('Index Exists: {}'.format(res)) 75 | if res is False: 76 | print('Creating index image-metadata-store') 77 | esClient.indices.create('image-metadata-store', body=indexDoc) 78 | return True 79 | except Exception as E: 80 | print("Unable to Create/access Index {0}".format("image-metadata-store")) 81 | print("Error: ", E) 82 | return False 83 | # exit(4) 84 | 85 | 86 | def indexDocElement(esClient, imageMetaData): 87 | try: 88 | print('Indexing document...') 89 | metadataBody = { 90 | 'createdDate': datetime.datetime.now(), 91 | 'objectKey': imageMetaData['Params']['Key'], 92 | 'objectBucket': imageMetaData['Params']['Bucket'], 93 | 'overallResult': imageMetaData['OverallResult']['Pass'], 94 | 'reason': imageMetaData['OverallResult']['Reason']} 95 | #print (metadataBody) 96 | esClient.index( 97 | index='image-metadata-store', doc_type='images', body=metadataBody) 98 | print('Document Indexed successfully.') 99 | return True 100 | except Exception as E: 101 | print("Document not indexed") 102 | print("Error: ", E) 103 | return False 104 | # exit(5) 105 | 106 | 107 | def lambda_handler(event, context): 108 | 109 | #print("Received event: " + json.dumps(event, indent=2)) 110 | #print (event) 111 | 112 | try: 113 | esClient = connectES(es_conn_string) 114 | if esClient is not None: 115 | if createIndex(esClient) is True: 116 | return indexDocElement(esClient, event) 117 | else: 118 | return False 119 | else: 120 | return False 121 | except Exception as e: 122 | print(e) 123 | print("Error: ", e) 124 | raise e 125 | -------------------------------------------------------------------------------- /code/Rek_RecognizeCelebrities.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | 8 | print('Loading function') 9 | 10 | rekognition = boto3.client('rekognition') 11 | 12 | 13 | # --------------- Helper Functions to call Rekognition APIs ------------------ 14 | 15 | 16 | def recognize_celebrities(bucket, key, inputParams): 17 | returnResult = { 18 | 'Stage' : 'RecognizeCelebrities', 19 | 'Pass': True, 20 | 'ErrorMessages': [] 21 | } 22 | response = rekognition.recognize_celebrities(Image={"S3Object": {"Bucket": bucket, "Name": key}}) 23 | # look for 'person' label with confidence of 90% or more 24 | celebrityDetected = False 25 | celebrityName = '' 26 | for face in response['CelebrityFaces']: 27 | if Decimal(str(face['MatchConfidence'])) > 90: 28 | celebrityDetected = True 29 | celebrityName = face['Name'] 30 | break 31 | if celebrityDetected: 32 | # print('Celebrity Detected: {}.'.format(celebrityDetected)) 33 | # print('Your picture is very similar to {}.'.format(celebrityName)) 34 | returnResult['Pass'] = False 35 | returnResult['ErrorMessages'].append('Your picture is very similar to {}.'.format(celebrityName)) 36 | 37 | # process overall result 38 | inputParams['OverallResult']['Details'].append(returnResult) 39 | inputParams['OverallResult']['Pass'] = inputParams['OverallResult']['Pass'] and returnResult['Pass'] 40 | if (returnResult['Pass'] is False): 41 | inputParams['OverallResult']['Reason'] = 'CELEBRITY_DETECTED' 42 | else: 43 | inputParams['OverallResult']['Reason'] = '' 44 | 45 | return inputParams 46 | 47 | 48 | 49 | # --------------- Main handler ------------------ 50 | 51 | 52 | def lambda_handler(event, context): 53 | #print("Received event: " + json.dumps(event, indent=2)) 54 | 55 | # Get the object from the event 56 | bucket = event['Params']['Bucket'] 57 | key = urllib.unquote_plus(event['Params']['Key'].encode('utf8')) 58 | try: 59 | # Calls rekognition RecognizeCelebrities API to detect faces in S3 object 60 | response = recognize_celebrities(bucket, key, event) 61 | 62 | # Print response to console. 63 | #print(response) 64 | 65 | return response 66 | except Exception as e: 67 | print(e) 68 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 69 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 70 | raise e 71 | -------------------------------------------------------------------------------- /code/Rek_UpdateBlacklist.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import boto3 4 | from decimal import Decimal 5 | import json 6 | import urllib 7 | import os 8 | 9 | print('Loading function') 10 | 11 | rekognition = boto3.client('rekognition') 12 | s3 = boto3.client('s3') 13 | 14 | 15 | # --------------- Helper Functions to call Rekognition APIs ------------------ 16 | 17 | 18 | def add_image_to_Collection(bucket, key, prefix): 19 | 20 | doesBlackListImagesExist = False 21 | 22 | # Get all the collections 23 | response = rekognition.list_collections(MaxResults=100) 24 | 25 | for collectionId in response['CollectionIds']: 26 | if(collectionId == 'BlackListImages'): 27 | doesBlackListImagesExist = True 28 | 29 | # Create a blacklist collection 30 | if not doesBlackListImagesExist: 31 | #print('Creating collection : BlackListImages') 32 | rekognition.create_collection(CollectionId='BlackListImages') 33 | # Since the collection did not exist, add the existing images from the blacklist bucket, to the blacklist image collection 34 | #print('Adding BlackList Images') 35 | imageList = s3.list_objects_v2( 36 | Bucket=bucket, Prefix=prefix) 37 | #print(json.dumps(imageList,indent=4, separators=(',', ': '))) 38 | #print(imageList) 39 | if imageList['Contents'] is not None: 40 | for image in imageList['Contents']: 41 | if(image['Size'] == 0): 42 | continue 43 | print('Adding ' + bucket + '/' + image['Key']) 44 | rekognition.index_faces(CollectionId='BlackListImages', Image={"S3Object": { 45 | "Bucket": bucket, "Name": image['Key']}}) 46 | else: 47 | # Just add the image which fired the Lambda function. 48 | print('Adding ' + bucket + '/' + key) 49 | rekognition.index_faces(CollectionId='BlackListImages', Image={"S3Object": { 50 | "Bucket": bucket, "Name": key}}) 51 | 52 | return None 53 | 54 | # --------------- Main handler ------------------ 55 | 56 | 57 | def lambda_handler(event, context): 58 | 59 | #print("Received event: " + json.dumps(event, indent=2)) 60 | 61 | # Get the object from the event 62 | bucket = event['Records'][0]['s3']['bucket']['name'] 63 | key = urllib.unquote_plus( 64 | event['Records'][0]['s3']['object']['key'].encode('utf8')) 65 | prefix = key[:key.rfind('/')] 66 | try: 67 | 68 | # try: 69 | # # delete collections. REMOVE IN PROD. 70 | # rekognition.delete_collection(CollectionId ='BlackListImages') 71 | # except Exception as e: 72 | # print ('Error deleting collections.') 73 | 74 | 75 | # Create image collections. 76 | add_image_to_Collection(bucket, key, prefix) 77 | 78 | # Print response to console. 79 | # print(response) 80 | 81 | return True 82 | except Exception as e: 83 | print(e) 84 | print("Error processing object {} from bucket {}. ".format(key, bucket) + 85 | "Make sure your object and bucket exist and your bucket is in the same region as this function.") 86 | raise e 87 | -------------------------------------------------------------------------------- /images/Solution-Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/Solution-Architecture.png -------------------------------------------------------------------------------- /images/StepFunctions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/StepFunctions.png -------------------------------------------------------------------------------- /images/StepFunctions_Failure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/StepFunctions_Failure.png -------------------------------------------------------------------------------- /images/blackList/barbie3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/blackList/barbie3.jpg -------------------------------------------------------------------------------- /images/test/Barack_Obama.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Barack_Obama.jpg -------------------------------------------------------------------------------- /images/test/Donald-Trump.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Donald-Trump.jpg -------------------------------------------------------------------------------- /images/test/I_woke_up_looking_this_good.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/I_woke_up_looking_this_good.jpg -------------------------------------------------------------------------------- /images/test/Image Sources.txt: -------------------------------------------------------------------------------- 1 | https://static.pexels.com/photos/355164/pexels-photo-355164.jpeg -------------------------------------------------------------------------------- /images/test/Kayla_Person-small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Kayla_Person-small.jpg -------------------------------------------------------------------------------- /images/test/Les_Twins_profile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Les_Twins_profile.jpg -------------------------------------------------------------------------------- /images/test/Mouth_Open.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Mouth_Open.jpg -------------------------------------------------------------------------------- /images/test/Texting-Smiling-Person.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/Texting-Smiling-Person.jpg -------------------------------------------------------------------------------- /images/test/barbie1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/barbie1.jpg -------------------------------------------------------------------------------- /images/test/barbie2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/barbie2.jpg -------------------------------------------------------------------------------- /images/test/eyes_closed.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/eyes_closed.jpg -------------------------------------------------------------------------------- /images/test/funny-face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/funny-face.jpg -------------------------------------------------------------------------------- /images/test/person1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/person1.jpg -------------------------------------------------------------------------------- /images/test/person2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/person2.jpg -------------------------------------------------------------------------------- /images/test/person3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/person3.jpg -------------------------------------------------------------------------------- /images/test/person4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/person4.jpg -------------------------------------------------------------------------------- /images/test/silhouette-of-a-man.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/silhouette-of-a-man.jpg -------------------------------------------------------------------------------- /images/test/tom-cruise.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/amazon-rekognition-reviewing-user-content/a309c28e59b4eab0086267ae76d10e3de715bdb5/images/test/tom-cruise.jpg --------------------------------------------------------------------------------