[PYTHON] [AWS Hands-on] Let's create a celebrity identification service with a serverless architecture!

About this article

-** This is a public release of the "AWS Hands-on" materials that were conducted outside of work for colleagues at the company. ** ** -** Using a serverless architecture, the content is to create a celebrity image analysis API service in about an hour. ** ** --Although Python is used as the language, it is structured so that it can be enjoyed without basic knowledge. --The following resources are required to implement hands-on. --PC that can connect to the Internet (whether Windows or Mac) --AWS IAM user account ――We have paid close attention to the preparation of this material, but we do not guarantee its accuracy. In addition, the creator does not take any responsibility for the damage caused by this material.

Postscript: Slide version released

--Speaker Deck has ** released a slide version of this hands-on material **. ――I think the slide version has a better design and is easier to see. ――On the other hand, this article of Qiita has the advantage that you can copy and paste the source code. ――I think it would be good if both the slide version and the Qiita version were used together. - https://speakerdeck.com/hayate_h/awshanzuon-sabaresuakitekutiyade-you-ming-ren-shi-bie-sabisuwozuo-rou -  

Introduction (Overview)

What to make

-Use Amazon Rekognition (Image Analysis AI) And create a celebrity identification API. --The system configuration diagram is as follows. --Since there is no explicit server, it is easy to build because of the "serverless architecture". ――It also reduces the labor and cost of operation management. image.png

Operation image

――For example, prepare a photo of Japan's world-famous actor "Ken Watanabe" and load it into the AI created this time. -* In the screenshot below, the image is blurred to protect intellectual property rights. --Select the image of "Ken Watanabe" from the "Select File" button. image.png --After selecting the file, click the "Send" button ... --"He / She is Ken Watanabe with 100% confidence."Is displayed. -** In this hands-on, we will create a backend for this service. ** ** image.png

Architecture description

  1. Upload an image of a celebrity from your client PC via API Gateway.
  2. When you receive the image file, the Lambda function will start.
  3. Within the Lambda function, send the image file to Amazon Rekognition's recognize_celebrities feature to identify the celebrity in the image.
  4. Format the retrieved celebrity information for output and return it through API Gateway.
  5. The identification result is displayed on the calling browser. image.png

About AWS Services

Introducing the AWS service to use

--I will briefly introduce the three services used this time. ――Let's proceed with hands-on with the idea of "getting used to it rather than learning". image.png

AWS Glossary: What is "Serverless"?

—— Services and architectures that users do not need to be aware of the server. --Note: This does not mean that the server does not exist at all. The server is managed by AWS. --It works just by putting the program code. Therefore, operation management becomes easier. image.png

AWS Glossary: What is a "managed service"?

――It is a service that AWS takes charge of (a part of) operation management. ――The content and scope of operation management that you take charge of varies depending on the service, but in many cases, we provide not only "take backups regularly" but also "automatically scale when access increases". .. ――When the scope of operation management is wide and there is almost no effort for users, it is often referred to as a “fully managed service”. ――Even if it is "managed", it is not always "serverless". image.png

Development procedure

Sign in

--Access the AWS Management Console and sign in with your IAM user information.

-** Sign-in supplementary information ** ――In this hands-on, we are proceeding on the premise that the IAM policy of ** "AdministratorAccess" is given to the IAM user who implements the hands-on **. --If the "AdministratorAccess" authority is not granted, an error such as not being able to create a resource may occur in the following procedure. --In that case, attach an appropriate policy and re-execute. ――In addition, the IAM settings described on the following site were very helpful. --It has been confirmed that all hands-on procedures can be performed. -I'm thinking about IAM settings when putting external development members into an AWS account --kmiya_bbm's blog

Region and language confirmation

--Confirm that the upper right corner of the screen is "Tokyo (Region)" and the lower left corner of the screen is "Japanese". --If you need to change it, refer to the next page and perform the switching work. image.png

[Supplement] How to change the region

--Press the place name in the upper right corner of the screen and select "Asia Pacific (Tokyo) ap-northeast-1". image.png

[Supplement] How to change the language

--Press the language at the bottom left of the screen and select "Japanese". image.png

Creating a Lambda function

Create a new Lambda function

--First, let's create a Lambda function and learn the basic usage. image.png

--On the management console screen, enter "Lambda" in the search window and select the displayed "Lambda". image.png

--When the Lambda screen opens, click the "Create Function" button. image.png

--On the function creation screen, select and enter the following. --Select "Create from scratch" --Enter "<< name >> -rekognition-handson" in "function name" --Example: higuchi-rekognition-handson --Select "Python 3.8" for "Runtime" --Open "Permissions"-"Change Default Execution Role" and select "Create New Role with Basic Lambda Permissions" --After completing the above settings, click the "Create Function" button at the bottom right of the screen. image.png

--The Lambda function is created. image.png

――I will write the code that works from now on. --Scroll down to "Function Code". This is the editor that writes the logic. image.png

How to use Lambda function

--First, let's write a simple Python code to learn how Lambda works. image.png

--For example, write the following code that combines and outputs character strings. --The content is to set a character string in the variable and return the combined one. ――Specifically, ‘Pen’ + ‘Pineapple’ + ‘Apple’ + ‘Pen’ → ‘PenPineappleApplePen’.


def lambda_handler(event, context):
    a = 'Pen'
    b = 'Pineapple'
    c = 'Apple'
    x = a + b + c + a
    return {
        'statusCode': 200,
        'body': x

--After writing, click the "Deploy" button, and then click "Test" on the upper right. image.png

--The "Test Event Settings" screen is displayed. After making the following settings, click the "Create" button. --Select "Create new test event". --Enter "SimpleEvent" for the event name image.png

--Click "Test" on the upper right. --The test will be executed in the test event you created earlier. image.png

--Lambda has been tested. --If you see "Success" at the top of the screen, the code is proof that it worked. image.png

--Click Details to expand the execution result of the function. ――Here, “body” is “PenPineappleApplePen”, which is the output you expected. image.png

--Detailed logs when running Lambda can be found in "CloudWatch Logs". --Click "Monitoring"-> "View CloudWatch Logs" to move to the "CloudWatch Logs" page. image.png

--You can check the log by selecting "20xx / xx / xx [$ LATEST] xxxxxx" on the "Log Stream" screen. Please use it when debugging. --If you set Logger etc., the log will be output here. image.png

Editing Lambda functions

--From here, we will work to link the ** Lambda function with the image analysis AI (Rekognition) . --You need the proper permissions to call Rekognition from your Lambda function. --Specifically, you need to attach an IAM policy that allows access to Rekognition to the IAM role granted to Lambda. - First, let's go from granting authority. ** ** image.png

Change IAM roles (privileges)

--Select "Settings" at the top of the Lambda screen image.png

--Select "Edit" from "Basic Settings" at the bottom of the "Settings" screen. image.png

--Go to the bottom of the "Edit Preferences" screen and click "Show xxx roles in the IAM console." image.png

--In a separate tab, the IAM role screen will open. --Click the "Attach Policy" button. image.png

--Enter "Rekognition" in the search window, check the "Amazon RekognitionReadOnlyAccess" policy, and click the "Attach Policy" button. image.png

--On the IAM console screen, make sure that "AmazonRekognitionReadOnlyAccess" is attached. --You have now given Lambda permission to call Rekognition. image.png

--Returns to the Lambda Edit Preferences screen. --Change the timeout to "10 seconds". --After the above settings, click the "Save" button. image.png

Lambda function updates

--Rewrite the Lambda function with the celebrity identification code. --Overwrite the "function code" with the following contents and press the "Deploy" button. image.png

Code to paste


import boto3
import base64
import logging
import traceback

#logger settings
logger = logging.getLogger()

#Create a rekognition instance
rekognition = boto3.client('rekognition')

# lambda_handler function definition (main logic)
def lambda_handler(event, context):
    logger.info(f'Received event = {event}')
    #Since the binary data is received in the Base64 format encoded, it is decoded into bytes type.
    received_body = base64.b64decode(event['body-json'])
    #Excludes file information given by AWS (bytes character string)'\r\n'The main body information of the file uploaded by the 4th and subsequent ones)
    images  = received_body.split(b'\r\n',4)
    image   = images[4]
    #Pass the acquired Blob format image information to Rekognition to identify the celebrity
    response = rekognition.recognize_celebrities(
        Image={'Bytes': image}
    logger.info(f'Rekognition response = {response}')
        #Extract the reliability of the celebrity name from the Rekognition response and respond to the API caller.
        label   = response['CelebrityFaces'][0]
        name    = label['Name']
        conf    = round(label['Face']['Confidence'])
        output  = f'He/She is {name} with {conf}% confidence.'
        logger.info(f'API response = {output}')
        return output
    except IndexError as e:
        #If you can't get celebrity information from Rekognition's response, tell them to use another photo.
        logger.info(f"Coudn't detect celebrities in the Photo. Exception = {e}")
        return "Couldn't detect celebrities in the uploaded photo. Please upload another photo."

Code description (# part that could not be written in the comment)

--First line ʻimport boto3 --I'm importing the modules needed to work with AWS services. --boto3 is an SDK used to operate AWS resources in Python. - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html --Lines 25-27response = rekognition.recognize_celebrities (Image = {'Bytes': image}) --How to use rekognition is described in the boto3 documentation. - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.recognize_celebrities --Line 37return statement` --This is actually an anti-pattern return statement. --Actually, it's a good idea to use a response format that matches the format of Lambda's proxy integration. --This time, in order to check the operation on the browser, the proxy integration is not explicitly used, and the output format is intentionally ignored. --For details, search for "API Gateway integrated response". - https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/api-gateway-integration-settings-integration-response.html

Add API Gateway

――From here, we will link API Gateway and Lambda. image.png

--Enter "API" in the search window from "Services" at the top of the screen, and select "API Gateway" as a candidate. image.png

--Click "Create API" at the top right of the screen. image.png

--Click the "Build" button of REST API. image.png

--Set the following settings on the "Create new API" screen, and click the "Create API" button. --Select "New API" --API name: Enter "<< Name >> -api-handson" (Example: higuchi-api-handson) --Endpoint type: Select "Region" image.png

--API will be developed by "resources" x "methods". --For example, "GET to / users" or "POST to / users / 12345". image.png

--First, create a resource. Select Create Resource from Actions. image.png

--Enter "Rekognition" in the resource name and click the "Create Resource" button. image.png

--Next, create the method. After selecting the resource, select Actions → Create Method. image.png

--Select "POST" from the pull-down menu and press the "Check Button". image.png

--Select "Lambda function" in the integration type, select "<< Name >> -rekognition-handson" created earlier in the Lambda function, and click the "Save" button. image.png

--The confirmation screen for "Adding permissions to your Lambda function" will be displayed. Click the "OK" button. image.png

--Select "Integration Request". image.png

--Expand "Mapping Templates" at the bottom of the screen and select "If Template Is Not Defined (Recommended)" in the "Request Body Passthrough" item. --In the "Content-Type" item, click "Add Mapping Template". image.png

--In the "Content-Type" item, enter multipart / form-data and press the check button. image.png

--A template generation screen will be added at the bottom of the screen. --From the template generation pull-down, select "Method Request Passthrough" and press the "Save" button. image.png

--Select "Settings" on the left side of the screen, and click "Add Binary Media Type" in the "Binary Media Type" item at the bottom of the "Settings" screen. image.png

--Enter multipart / form-data and press the" Save Changes "button. image.png

--After selecting "Resources" in the left pane of the screen, select "Deploy API" from "Actions" at the top of the screen. image.png

--On the API deployment screen, make the following settings and click the "Deploy" button. --Deployed stage: Select "New stage" --Stage name: Enter "dev" image.png

--From the left pane of the screen, select "Stage" and then select "dev"-"rekognition"-"POST". --The URL of the API created as "Call URL" is displayed on the right side of the screen. Copy it. image.png

Creating an HTML file

--Paste the API Gateway URL you created earlier in the **** API Gateway URL Paste **** part of the HTML below, and save it with the file name "index.html". --A simple HTML file that just submits the selected file using a form.


<!DOCTYPE html>
<html lang="ja">
        <meta charset="UTF-8">
        <title>Celebrity recognition AI hands-on</title>
        <p>Celebrity recognition is performed using Amazon Rekognition, an image identification AI!</p>
        <form action="****Paste API Gateway URL****" enctype="multipart/form-data" method="POST">
            <input type="file" name="Select a photo file" />
            <input type="submit" name="upload"/>

--Open the created Index.html in your browser. (Select a file and drag and drop it onto the browser to open it) image.png

Operation check

――For example, let's try it with Japan's world-class comedian (?) "Watabe of the World". -* In the screenshot below, the image is blurred to protect intellectual property rights. image.png

--Select a file and press the "Send" button ... --"He / She is Ken Watabe with 100% confidence."Is displayed! --The celebrity identification service is complete! ――As expected, it is "Watabe of the world". image.png

Clean up

--The following resources will be deleted. - API Gateway - Lambda --CloudWatch log group (Lambda execution log) --IAM roll for Lambda image.png

Remove API Gateway

--From the API Gateway screen, select the created "<< Name >>-api-handson". image.png

--From the API Gateway screen, select the created "<< Name >>-api-handson". image.png

--With "Resource" selected in the left pane of the screen, select "Delete API" from the action. image.png

--The confirmation screen before deletion is displayed. After entering the API name, click "Delete API". image.png

Delete CloudWatch logs

--Search and select "Lambda" from "Services" at the top of the screen to move to the Lambda console screen. image.png

--On the list screen, select "<< Name >> -rekognition-handson". image.png

--Select "Monitoring" at the top of the screen and press the "View CloudWatch Log" button. image.png

--Transitions to the CloudWatch Logs screen. Select Delete log group from Actions. image.png

--A confirmation screen will be displayed, so click the "Delete" button. image.png

Delete IAM role

--Return to the Lambda screen and open "Settings". image.png

--At the bottom of the Lambda screen, press "Edit" in "Basic Settings". image.png

--Go to the bottom of the "Edit Preferences" screen and select "Show xxx roles in the IAM console." image.png

--Transitions to the IAM role screen. Select "Delete Role" at the top right of the screen. image.png

--A confirmation screen will appear, so click "Yes, delete". image.png

Remove Lambda function

--Return to the Lambda screen and select "Delete Function" from "Action" at the top of the screen. image.png

--A confirmation screen will be displayed. Select "Delete". image.png

--The message "It was deleted successfully." Is displayed. image.png

-** This is the end of cleaning up. Thank you for your hard work. ** **

Supplementary information


--There are certain free tiers for various AWS services. ――This configuration is assumed to fit in the AWS free usage tier unless you call a large number of APIs. ――For reference, here is an estimate of the charges that will be incurred when the free tier is exceeded. -(As of October 13, 2020, Tokyo Region, monthly)

Service classification Classification Fee Supplement
Data communication charges In to AWS 0.000USD/GB
Out from AWS 0.114USD/GB First 1GB-10TB
CloudWatch Log collection 0.760USD/GB
Log save 0.033USD/GB
Lambda Request billing 0.20USD/1 million
Execution time billing 0.0000002083USD
/128MB,100 ms
API Gateway REST API 4.25USD/1 million First 303,3 million calls received
Rekognition Image 0.0013USD/1 image First 1 million

Reference materials / documents

-AWS Hands-on for Beginners Serverless # 1 Build Translation Web API with Serverless Architecture | AWS -Put binary data (wav) from AWS API Gateway + Lambda to S3 using multipart / form-data – Qiita

Recommended Posts

[AWS Hands-on] Let's create a celebrity identification service with a serverless architecture!
Let's make a web chat using WebSocket with AWS serverless (Python)!
How to create a serverless machine learning API with AWS Lambda
Let's create a free group with Python
Create a web service with Docker + Flask
Create a private repository with AWS CodeArtifact
Let's create a chat function with Vue.js + AWS Lambda + dynamo DB [AWS settings]
I tried to make a url shortening service serverless with AWS CDK
Create a Layer for AWS Lambda Python with Docker
Let's create a script that registers with Ideone.com in Python.
Let's create a PRML diagram with Python, Numpy and matplotlib.
Create a homepage with django
Create a heatmap with pyqtgraph
Create a directory with python
Let's create a tic-tac-toe AI with Pylearn 2-Save and load models-
Serverless scraping on a regular basis with AWS lambda + scrapy Part 1
[AWS] Create API with API Gateway + Lambda
Let's make a GUI with python.
Let's make a spot sale service 2
Let's make a breakout with wxPython
Create a virtual environment with Python!
Let's make a spot sale service 1
Create a SlackBot service on Pepper
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Create a poisson stepper with numpy.random
Let's make a spot sale service 3
Create a file uploader with Django
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
[AWS] Create a Python Lambda environment with CodeStar and do Hello World