├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── cloudformation └── hotdog_detector.serverless.yaml ├── images ├── Architecture.png └── TestingExample.gif └── lambda_functions └── detect_hotdog.py /.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 | # General 2 | *.DS_Store 3 | .AppleDouble 4 | .LSOverride 5 | 6 | # Icon must end with two \r 7 | Icon 8 | 9 | 10 | # Thumbnails 11 | ._* 12 | 13 | # Files that might appear in the root of a volume 14 | .DocumentRevisions-V100 15 | .fseventsd 16 | .Spotlight-V100 17 | .TemporaryItems 18 | .Trashes 19 | .VolumeIcon.icns 20 | .com.apple.timemachine.donotpresent 21 | 22 | # Directories potentially created on remote AFP share 23 | .AppleDB 24 | .AppleDesktop 25 | Network Trash Folder 26 | Temporary Items 27 | .apdisk 28 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/issues), or [recently closed](https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | serverless-hotdog-detector 2 | Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Hotdog Detector 2 | 3 | This example shows you how to build a [serverless](https://aws.amazon.com/serverless/#getstarted) [hotdog detecting app](https://www.youtube.com/watch?v=ACmydtFDTGs) on AWS using [Amazon API Gateway](https://aws.amazon.com/api-gateway/), [AWS Lambda](https://aws.amazon.com/lambda/), and [Amazon Rekognition](https://aws.amazon.com/rekognition/). 4 | 5 | This example is intended to integrate with [Slack](https://slack.com/) as the application frontend but could easily be modified to work with your own web or mobile application frontend. 6 | 7 | This repository contains sample code the Lambda function depicted in the diagram below as well as an [AWS CloudFormation](https://aws.amazon.com/cloudformation/) template for creating the function and related resources. 8 | 9 | To see some of the other real-world examples of Rekognition in action check out the [Image Recognition and Processing Backend Serverless reference architecture](https://github.com/awslabs/lambda-refarch-imagerecognition) 10 | 11 | ![testing of example gif](images/TestingExample.gif) 12 | 13 | ## Walkthrough of the Architecture 14 | 1. A user posts a message containing the image to perform hotdog detection on in a Slack channel monitored by the chat app. 15 | 1. Slack posts the message to an Amazon API Gateway API for the chat app. 16 | 1. The API triggers an invocation of the chat app Lambda function which performs the following: 17 | 1. Amazon Rekognition’s image recognition and labelling feature scans the image and returns a list of detected labels. 18 | 1. The list of labels is checked for those corresponding to hotdogs to determine if the image contained a hotdog. 19 | 1. A message is posted to the chat channel detailing whether the image was a hotdog or not. 20 | 21 | ![screenshot for instruction](images/Architecture.png) 22 | 23 | ## Running the Example 24 | ### Preparing Slack 25 | First make sure you're logged in to Slack, then follow these instructions to prep your app: 26 | 1. [Create an app](https://api.slack.com/apps?new_app=1) ([Documentation](https://api.slack.com/slack-apps#creating_apps)) 27 | 1. From the `Basic Information` tab under `Settings` take note of the `Verification Token` as it will be required later 28 | 1. Navigate to the `OAuth & Permissions` tab under `Features` 29 | 1. Under the `Permissions Scopes` section add the following permission scopes 30 | * channels:history 31 | * chat:write:bot 32 | * files:read 33 | * files:write:user 34 | 1. Click `Save Changes` 35 | 1. Click `Install App to Team` then `Authorize` then note the `OAuth Access Token` as it will be required later 36 | 37 | ### Launching the App Backend on AWS 38 | #### Option 1: Launch from Serverless Application Repository 39 | This app can be launched into any region that supports the underlying services from the [Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) using the instructions below: 40 | 41 | 1. Navigate to the [application details page](https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:426111819794:applications~hotdog-detector) for the app. 42 | 1. Click `Deploy` 43 | 1. From the region dropdown in the top right ensure you have the desired region to deploy into selected 44 | 1. Input the appropriate application parameters under `Configure application parameters` 45 | 1. Scroll to the bottom of the page and click `Deploy` to deploy the chatbot 46 | 47 | #### Option 2: Launch the CloudFormation Template Manually 48 | If you would like to deploy the template manually, you need a S3 bucket in the target region, and then package the Lambda functions into that S3 bucket by using the `aws cloudformation package` utility. 49 | 50 | Set environment variables for later commands to use: 51 | 52 | ```bash 53 | S3BUCKET=[REPLACE_WITH_YOUR_BUCKET] 54 | REGION=[REPLACE_WITH_YOUR_REGION] 55 | STACKNAME=[REPLACE_WITH_DESIRED_NAME] 56 | VTOKEN=[REPLACE_WITH_VERIFICATION_TOKEN] 57 | ATOKEN=[REPLACE_WITH_OAUTH_ACCESS_TOKEN] 58 | ``` 59 | 60 | Then go to the `cloudformation` folder and use the `aws cloudformation package` utility 61 | 62 | ```bash 63 | cd cloudformation 64 | 65 | aws cloudformation package --region $REGION --s3-bucket $S3BUCKET --template hotdog_detector.serverless.yaml --output-template-file hotdog_detector.output.yaml 66 | ``` 67 | Last, deploy the stack with the resulting yaml (`hotdog_detector.output.yaml`) through the CloudFormation Console or command line: 68 | 69 | ```bash 70 | aws cloudformation deploy --region $REGION --template-file hotdog_detector.output.yaml --stack-name $STACKNAME --capabilities CAPABILITY_NAMED_IAM --parameter-overrides VerificationToken=$VTOKEN AccessToken=$ATOKEN 71 | ``` 72 | 73 | ### Finalize Slack Event Subscription 74 | 1. Navigate to the created stack in the CloudFormation console and note the value for the `RequestURL` output from the created stack as it will be required later 75 | 1. Return to the Slack app settings page for the Slack app created earlier 76 | 1. Navigate to the `Event Subscriptions` tab under `Features` and enable events 77 | 1. In the `Request URL` field enter the `RequestURL` value noted earlier 78 | 1. Click `Add Workspace Event` and select `message.channels` 79 | 1. Click `Save Changes` 80 | 81 | 82 | ## Testing the Example 83 | To test the example open your Slack app and navigate to a channel for the team you configured the Slack app on, then try uploading pictures of different foods to see the app in action. 84 | 85 | 86 | ## Cleaning Up the Stack Resources 87 | 88 | To remove all resources created by this example, do the following: 89 | 90 | 1. Delete the CloudFormation stack. 91 | 1. Delete the CloudWatch log groups associated with each Lambda function created by the CloudFormation stack. 92 | 93 | ## CloudFormation Template Resources 94 | The following sections explain all of the resources created by the CloudFormation template provided with this example. 95 | 96 | ### AWS Lambda 97 | - **HotdogDetectorFunction** - Lambda function that validates incoming Slack event messages, checks them for images containing explicit content, and orchestrates the removal of images found to contain explicit content from Slack. 98 | - **HotdogDetectorFunctionHotdogDetectorAPIPostPermissionTest** - Implicitly created Lambda permission, allows API Gateway Test stage to call Lambda function. 99 | - **HotdogDetectorFunctionHotdogDetectorAPIPostPermissionProd** - Implicitly created Lambda permission, allows API Gateway Prod stage to call Lambda function. 100 | 101 | ### AWS IAM 102 | - **HotdogDetectorFunctionRole** - Implicitly created IAM Role with policy that allows Lambda function to invoke "rekognition:DetectLabels" and "rekognition:DetectModerationLabels" API calls and write log messages to CloudWatch Logs. 103 | 104 | ### Amazon API Gateway 105 | - **HotdogDetectorAPI:** - API for hotdog detector app 106 | - **HotdogDetectorAPIProdStage** - Implicitly created production stage for API 107 | - **HotdogDetectorAPIDeploymentXXXXXXXXX** - Implicitly created deployment for production stage of API 108 | 109 | 110 | ## License 111 | 112 | This reference architecture sample is licensed under Apache 2.0. 113 | -------------------------------------------------------------------------------- /cloudformation/hotdog_detector.serverless.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | 4 | Parameters: 5 | VerificationToken: 6 | Description: Verification token from Slack app settings 7 | Type: String 8 | NoEcho: true 9 | 10 | AccessToken: 11 | Description: OAuth access token from Slack app settings 12 | Type: String 13 | NoEcho: true 14 | 15 | Resources: 16 | HotdogDetectorAPI: 17 | Type: AWS::Serverless::Api 18 | Properties: 19 | StageName: Prod 20 | DefinitionBody: 21 | swagger: "2.0" 22 | info: 23 | version: "2017-06-11T02:20:25Z" 24 | title: !Ref AWS::StackName 25 | basePath: "/Prod" 26 | schemes: 27 | - "https" 28 | paths: 29 | /: 30 | post: 31 | produces: 32 | - "application/json" 33 | responses: 34 | "200": 35 | description: "200 response" 36 | schema: 37 | $ref: "#/definitions/Empty" 38 | x-amazon-apigateway-integration: 39 | responses: 40 | default: 41 | statusCode: "200" 42 | uri: !Sub |- 43 | arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HotdogDetectorFunction.Arn}/invocations 44 | passthroughBehavior: "when_no_match" 45 | httpMethod: "POST" 46 | contentHandling: "CONVERT_TO_TEXT" 47 | type: "aws" 48 | definitions: 49 | Empty: 50 | type: "object" 51 | title: "Empty Schema" 52 | 53 | 54 | HotdogDetectorFunction: 55 | Type: AWS::Serverless::Function 56 | Properties: 57 | Description: Checks Slack message.channels events for images. If an image is found uses Rekognition to determine if it contains a hotdog. 58 | Handler: detect_hotdog.lambda_handler 59 | Runtime: python3.6 60 | Timeout: 10 61 | CodeUri: ../lambda_functions/ 62 | Environment: 63 | Variables: 64 | VERIFICATION_TOKEN: !Ref VerificationToken 65 | ACCESS_TOKEN: !Ref AccessToken 66 | Events: 67 | HotdogDetectorAPIPost: 68 | Type: Api 69 | Properties: 70 | Path: / 71 | Method: post 72 | RestApiId: !Ref HotdogDetectorAPI 73 | Policies: 74 | - RekognitionLabelsPolicy: {} 75 | 76 | Outputs: 77 | RequestURL: 78 | Description: Prod URL for API to use as Request URL for Slack app 79 | Value: !Sub |- 80 | https://${HotdogDetectorAPI}.execute-api.${AWS::Region}.amazonaws.com/Prod/ 81 | -------------------------------------------------------------------------------- /images/Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-hotdog-detector/5cd9c5f321846310ce10b1cd4ed035d6b76dac4a/images/Architecture.png -------------------------------------------------------------------------------- /images/TestingExample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/serverless-hotdog-detector/5cd9c5f321846310ce10b1cd4ed035d6b76dac4a/images/TestingExample.gif -------------------------------------------------------------------------------- /lambda_functions/detect_hotdog.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib 3 | import boto3 4 | 5 | SUPPORTED_TYPES = ['image/jpeg', 'image/jpg', 'image/png'] # Supported image types 6 | MAX_SIZE = 5242880 # Max number of image bytes supported by Amazon Rekognition (5MiB) 7 | 8 | VERIFICATION_TOKEN = os.environ['VERIFICATION_TOKEN'] # Slack verification token from environment variables 9 | ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] # Slack OAuth access token from environment variables 10 | 11 | rekognition = boto3.client('rekognition') 12 | 13 | 14 | def lambda_handler(event, context): 15 | print('Validating message...') 16 | if not verify_token(event): # Ignore event if verification token presented doesn't match 17 | return 18 | 19 | if event.get('challenge') is not None: # Respond to Slack event subscription URL verification challenge 20 | print('Presented with URL verification challenge- responding accordingly...') 21 | challenge = event['challenge'] 22 | return {'challenge': challenge} 23 | 24 | if not validate_event(event): # Ignore event if Slack message doesn't contain any supported images 25 | return 26 | 27 | event_details = event['event'] 28 | file_details = event_details['files'][0] 29 | 30 | channel = event_details['channel'] 31 | url = file_details['url_private'] 32 | file_id = file_details['id'] 33 | 34 | print('Downloading image...') 35 | image_bytes = download_image(url) 36 | print('Checking for hotdogs...') 37 | is_hotdog = detect_hotdog(image_bytes) 38 | message = "" 39 | if is_hotdog: 40 | print('Hotdog detected...') 41 | message = 'Hotdog ✅' 42 | else: 43 | print('Hotdog not detected...') 44 | message = 'Not hotdog ❌' 45 | post_message(channel, message) 46 | 47 | 48 | def verify_token(event): 49 | """ Verifies token presented in incoming event message matches the token copied when creating Slack app. 50 | 51 | Args: 52 | event (dict): Details about incoming event message, including verification token. 53 | 54 | Returns: 55 | (boolean) 56 | True if presented with the valid token. 57 | False otherwise. 58 | 59 | """ 60 | if event['token'] != VERIFICATION_TOKEN: 61 | print('Presented with invalid token- ignoring message...') 62 | return False 63 | return True 64 | 65 | 66 | def validate_event(event): 67 | """ Validates event by checking contained Slack message for image of supported type and size. 68 | 69 | Args: 70 | event (dict): Details about Slack message and any attachements. 71 | 72 | Returns: 73 | (boolean) 74 | True if event contains Slack message with supported image size and type. 75 | False otherwise. 76 | """ 77 | event_details = event['event'] 78 | file_subtype = event_details.get('subtype') 79 | 80 | if file_subtype != 'file_share': 81 | print('Not a file_shared event- ignoring event...') 82 | return False 83 | 84 | file_details = event_details['files'][0] 85 | mime_type = file_details['mimetype'] 86 | file_size = file_details['size'] 87 | 88 | if mime_type not in SUPPORTED_TYPES: 89 | print('File is not an image- ignoring event...') 90 | return False 91 | 92 | if file_size > MAX_SIZE: 93 | print('Image is larger than 5MB and cannot be processed- ignoring event...') 94 | return False 95 | 96 | return True 97 | 98 | 99 | def download_image(url): 100 | """ Download image from private Slack URL using bearer token authorization. 101 | 102 | Args: 103 | url (string): Private Slack URL for uploaded image. 104 | 105 | Returns: 106 | (bytes) 107 | Blob of bytes for downloaded image. 108 | 109 | 110 | """ 111 | request = urllib.request.Request(url, headers={'Authorization': 'Bearer %s' % ACCESS_TOKEN}) 112 | return urllib.request.urlopen(request).read() 113 | 114 | 115 | def detect_hotdog(image_bytes): 116 | """ Checks image for hotdog label using Amazon Rekoginition's object and scene detection deep learning feature. 117 | 118 | Args: 119 | image_bytes (bytes): Blob of image bytes. 120 | 121 | Returns: 122 | (boolean) 123 | True if object and scene detection finds hotdog in blob of image bytes. 124 | False otherwise. 125 | 126 | """ 127 | try: 128 | response = rekognition.detect_labels( 129 | Image={ 130 | 'Bytes': image_bytes, 131 | }, 132 | MinConfidence=80.0 133 | ) 134 | except Exception as e: 135 | print(e) 136 | print('Unable to detect labels for image.') 137 | raise(e) 138 | labels = response['Labels'] 139 | if any(label['Name'] == 'Hot Dog' for label in labels): 140 | return True 141 | return False 142 | 143 | 144 | def post_message(channel, message): 145 | """ Posts message to Slack channel via Slack API. 146 | 147 | Args: 148 | channel (string): Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. 149 | message (string): Message to post to channel 150 | 151 | Returns: 152 | (None) 153 | """ 154 | url = 'https://slack.com/api/chat.postMessage' 155 | data = urllib.parse.urlencode( 156 | ( 157 | ("token", ACCESS_TOKEN), 158 | ("channel", channel), 159 | ("text", message) 160 | ) 161 | ) 162 | data = data.encode("ascii") 163 | headers = {"Content-Type": "application/x-www-form-urlencoded"} 164 | request = urllib.request.Request(url, data, headers) 165 | urllib.request.urlopen(request) 166 | --------------------------------------------------------------------------------