Open1

翻訳API with App Comp

iharuiharu

事前準備

Pythonのインストール

python3.12のインストール

pyenv install 3.12

pythonのバージョンを3.12に指定

pyenv local 3.12

AWS CLIのインストール

https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/getting-started-install.html

AWS資格情報を登録する

aws configure list-profiles
# 何もなければ作成へ
# (任意)defaultがある場合は別名に変更
  • AWSマネージメントコンソールからIAMにアクセス

  • アクセスキーを取得

  • 取得したアクセスキーをAWS資格情報に登録する
    profile-nameは任意の資格情報名を入れる

    aws configure --profile profile-name
    

    ダイアログに従って以下のように入力する

    AWS Access Key ID [None]: ********************
    AWS Secret Access Key [None]: ********************
    Default region name [None]: ap-northeast-1
    Default output format [None]: json
    

SAM CLIのインストール

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/install-sam-cli.html

AWS Toolkitのインストール

VSCodeの拡張機能にAWSと入力してインストールする

テストコードをデプロイ

Lambdaの作成

translate-apiディレクトリを作成

import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

SAM build

translate-api

sam build

Build Succeededと出ればOK

SAM deploy

STACK_NAME=     # your-translate-api-stack
PROFILE=        # aws configure list-profilesで確認したprofile
BUCKET_NAME=    # your-translate-api-bucket
sam deploy \
--stack-name $STACK_NAME \
--profile $PROFILE \
--s3-bucket $BUCKET_NAME \
--capabilities CAPABILITY_IAM

Successfully created/updated stackと出ればOK
AWSマネージメントコンソールのCloudFormationでリソースを確認する
https://ap-northeast-1.console.aws.amazon.com/cloudformation

翻訳APIをデプロイ

DynamoDBの作成

  • template.yamlを作成

  • Application Composerで開く

  • 左タブからLambdaをドラック&ドロップ

  • リソースプロパティを設定

    リソースプロパティ 設定値
    論理ID TranslateTable
    パーティションキー timestamp
template.yaml
Transform: AWS::Serverless-2016-10-31
Resources:
  TranslateTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: timestamp
          AttributeType: S
      BillingMode: PAY_PER_REQUEST
      KeySchema:
        - AttributeName: timestamp
          KeyType: HASH
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES

Lambdaの作成

  • template.yamlを作成

  • Application Composerで開く

  • 左タブからLambdaをドラック&ドロップ

  • リソースプロパティを設定

    リソースプロパティ 設定値
    論理ID TranslateLambda
    ランタイム python3.12
    ハンドラー translate-function.lambda_handler
    メモリ 256
    タイムアウト 10
    アクセス許可 - TranslateFullAccess
    - AmazonDynamoDBFullAccess

ハンドラーは{pythonファイル名}.{ハンドラー名}で指定する

  • src/Functiontranslate-lambda.pyを保存する

    translate-lambda.py
    import json
    import logging
    import boto3
    import datetime
    
    
    logger = logging.getLogger()
    logger.setLevel("INFO")
    
    translate = boto3.client("translate")
    dynamodb = boto3.client("dynamodb")
    
    
    def lambda_handler(event, context):
        logger.info(event)
    
        input_text = event["queryStringParameters"]["input_text"]
    
        result = translate.translate_text(
            Text=input_text, SourceLanguageCode="ja", TargetLanguageCode="en"
        )
    
        output_text = result.get("TranslatedText")
    
        dynamodb.put_item(
            TableName="translate-history",
            Item={
                "timestamp": {"S": datetime.datetime.now().strftime("%Y%m%d%H%M")},
                "input_text": {"S": input_text},
                "output_text": {"S": output_text},
            },
        )
    
        return {
            "statusCode": 200,
            "headers": {},
            "body": json.dumps({"output_text": output_text}),
            "isBase64Encoded": False,
        }
    
    

手動で環境変数を追加

Resources:
  TranslateLambda:
      Environment:
        Variables:
          TRANSLATETABLE_TABLE_NAME: !Ref TranslateTable
          TRANSLATETABLE_TABLE_ARN: !GetAtt TranslateTable.Arn
template.yaml
Transform: AWS::Serverless-2016-10-31
Resources:
  TranslateLambda:
    Type: AWS::Serverless::Function
    Properties:
      Description: !Sub
        - Stack ${AWS::StackName} Function ${ResourceName}
        - ResourceName: TranslateLambda
      CodeUri: src/Function
      Handler: translate-function.lambda_handler
      Runtime: python3.12
      MemorySize: 256
      Timeout: 10
      Tracing: Active
      Policies:
        - TranslateFullAccess
        - DynamoDBCrudPolicy:
            TableName: !Ref TranslateTable
      Events:
        TranslateApiGETtranslate:
          Type: Api
          Properties:
            Path: /translate
            Method: GET
            RestApiId: !Ref TranslateApi
      Environment:
        Variables:
          TRANSLATETABLE_TABLE_NAME: !Ref TranslateTable
          TRANSLATETABLE_TABLE_ARN: !GetAtt TranslateTable.Arn
  TranslateLambdaLogGroup:
    Type: AWS::Logs::LogGroup
    DeletionPolicy: Retain
    Properties:
      LogGroupName: !Sub /aws/lambda/${TranslateLambda}
  TranslateTable:
    Type: AWS::DynamoDB::Table
    # 以下同様

ここまででLambdaの設定は完了です!

API Gatewayの作成

  • template.yamlを作成

  • Application Composerで開く

  • 左タブからLambdaをドラック&ドロップ

  • リソースプロパティを設定

    リソースプロパティ 設定値
    論理ID TranslateApi
    メソッド GET
    パス /translate

OpenAPI記法のparametersの設定

/translate:
  get:
    parameters:
    - name: input_text
      in: query
      required: true
      schema:
        type: string

lambdaと線を繋げる
自動でx-amazon-apigateway-integrationtype: aws_proxyになっている