AWS用Lambda搭建一個無服務的圖片鑑黃Restful API,不超過10行代碼

目的

無需購買服務器搭建一個圖片鑑黃接口 (Python語言)

Lambda介紹 : https://aws.amazon.com/cn/lambda/

AWS的Lambda控制檯首頁: https://console.aws.amazon.com/lambda/home

圖片鑑黃文檔:https://docs.aws.amazon.com/zh_cn/rekognition/latest/dg/procedure-moderate-images.html

1.創建函數

在這裏插入圖片描述

選擇第一個:從頭開始創作 --> 輸入:函數名稱 --> 運行時環境選擇Python
在這裏插入圖片描述

AWS支持多種語言,.Net、Go、Java、Node.js、Python和Ruby
在這裏插入圖片描述
在這裏插入圖片描述
選擇“創建具有基本Lambda權限的新角色”,如果你已經有了角色,就選擇第二個吧。



2.權限配置

你可以編輯此無服務函數佔用的最大內存數,通常256MB和512MB就可用了
在這裏插入圖片描述

然後去配置此Lambda函數可以訪問哪些AWS的資源;先點擊權限 --> 然後點擊配置名稱 ,就可以去配置角色了
在這裏插入圖片描述

現在,我們去添加此Lambda函數可訪問的AWS服務,點擊附加策略
在這裏插入圖片描述

添加AWS的識別服務策略 官方文檔
在這裏插入圖片描述

如果此Lambda函數希望訪問S3桶的數據,那就需要添加
在這裏插入圖片描述



3.代碼編寫

在這裏插入圖片描述
點擊測試,會有以下輸出
在這裏插入圖片描述

完整的代碼如下:

import json
import boto3

def recognize_S3_image(photo, bucket):
    # 識別圖片源來自S3桶
    client = boto3.client('rekognition')
    response = client.detect_moderation_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}})
    return handle_result(response)

def recognize_base64_image(image_base64_encoded):
    # 識別圖片源來自base64編碼
    client = boto3.client('rekognition')
    response = client.detect_moderation_labels(Image={'Bytes':image_base64_encoded})
    print("識別成功!")
    return handle_result(response)
    
def handle_result(response):
    max_confidence = 0
    optimal_name = ""
    parent_name = ""
    for label in response['ModerationLabels']:
        if label['Confidence'] > max_confidence:
            max_confidence = label['Confidence']
            optimal_name = label['Name']
            parent_name = label['ParentName']
    return max_confidence, optimal_name
    
def lambda_handler(event, context):
    print("============================================")
    print(event) 
    # 獲取
    # image_base64_encoded = event["image"]
    # if image_base64_encoded is None and len(image_base64_encoded) < 0:
    #     return
    # max_confidence, optimal_name = recognize_base64_image(image_base64_encoded)

    # 識別S3桶圖片 
    max_confidence, optimal_name = recognize_S3_image('test_porn.jpeg', 'yooul-recognition')
  
    return {
        'statusCode': 200,
        'body': {
            "confidence" : max_confidence,
            "label" : optimal_name
        }
    }


4.公網訪問

需要配置API Gateway
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章