0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「AWS Hands-on for Beginners AWS Managed AI/ML サービス はじめの一歩」をAWS CLIでやってみる

Posted at

上記、「AWS Hands-on for Beginners AWS Managed AI/ML サービス はじめの一歩」をAWS CLIでやってみる
image.png
ハンズオンから引用

Amazon Forecastは下記画像の通り、新規利用はできませんでした。

image.png

02 Amazon Personalize を用いてレコメンデーションを行う(1)

S3バケット作成

S3バケット作成

コマンド
# バケット名
date_var=$(date +%Y%m%d) \
&& echo ${date_var}
S3_BUCKET_NAME="h4b-personalize-${date_var}" \
&& echo ${S3_BUCKET_NAME}

# S3バケット作成
aws s3 mb s3://${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # バケット名
[cloudshell-user@ip-10-130-51-169 ~]$ date_var=$(date +%Y%m%d) \
> && echo ${date_var}
20241020
[cloudshell-user@ip-10-130-51-169 ~]$ S3_BUCKET_NAME="h4b-personalize-${date_var}" \
> && echo ${S3_BUCKET_NAME}
h4b-personalize-20241020
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # S3バケット作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3 mb s3://${S3_BUCKET_NAME}
make_bucket: h4b-personalize-20241020

バケットポリシー作成

コマンド
# バケットポリシー(JSON)
BACKET_POLICY=$(cat << EOF
{
    "Version": "2012-10-17",
    "Id": "PersonalizeS3BucketAccessPolicy",
    "Statement": [
        {
            "Sid": "PersonalizeS3BucketAccessPolicy",
            "Effect": "Allow",
            "Principal": {
                "Service": "personalize.amazonaws.com"
            },
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::${S3_BUCKET_NAME}",
                "arn:aws:s3:::${S3_BUCKET_NAME}/*"
            ]
        }
    ]
}
EOF
) \
&& echo ${BACKET_POLICY}

# JSONフォーマットの確認
echo ${BACKET_POLICY} | python -m json.tool

# バケットポリシー
aws s3api put-bucket-policy \
    --bucket ${S3_BUCKET_NAME} \
    --policy "${BACKET_POLICY}"

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # バケットポリシー(JSON)
[cloudshell-user@ip-10-130-51-169 ~]$ BACKET_POLICY=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Id": "PersonalizeS3BucketAccessPolicy",
>     "Statement": [
>         {
>             "Sid": "PersonalizeS3BucketAccessPolicy",
>             "Effect": "Allow",
>             "Principal": {
>                 "Service": "personalize.amazonaws.com"
>             },
>             "Action": [
>                 "s3:GetObject",
>                 "s3:ListBucket"
>             ],
>             "Resource": [
>                 "arn:aws:s3:::${S3_BUCKET_NAME}",
>                 "arn:aws:s3:::${S3_BUCKET_NAME}/*"
>             ]
>         }
>     ]
> }
> EOF
> ) \
> && echo ${BACKET_POLICY}
{ "Version": "2012-10-17", "Id": "PersonalizeS3BucketAccessPolicy", "Statement": [ { "Sid": "PersonalizeS3BucketAccessPolicy", "Effect": "Allow", "Principal": { "Service": "personalize.amazonaws.com" }, "Action": [ "s3:GetObject", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::h4b-personalize-20241020", "arn:aws:s3:::h4b-personalize-20241020/*" ] } ] }
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-51-169 ~]$ echo ${BACKET_POLICY} | python -m json.tool
{
    "Version": "2012-10-17",
    "Id": "PersonalizeS3BucketAccessPolicy",
    "Statement": [
        {
            "Sid": "PersonalizeS3BucketAccessPolicy",
            "Effect": "Allow",
            "Principal": {
                "Service": "personalize.amazonaws.com"
            },
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::h4b-personalize-20241020",
                "arn:aws:s3:::h4b-personalize-20241020/*"
            ]
        }
    ]
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # バケットポリシー
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3api put-bucket-policy \
>     --bucket ${S3_BUCKET_NAME} \
>     --policy "${BACKET_POLICY}"

ファイル解凍

ハンズオンからダウンロードした下記ファイルをCloudShellにアップロードしておく

ファイル名:JAPAN_FIELD_WEBINAR_Hands-on-for-Beginners-AIML_2021.zip

コマンド
# ファイル解凍
unzip JAPAN_FIELD_WEBINAR_Hands-on-for-Beginners-AIML_2021.zip 

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ファイル解凍
[cloudshell-user@ip-10-130-51-169 ~]$ unzip JAPAN_FIELD_WEBINAR_Hands-on-for-Beginners-AIML_2021.zip 
Archive:  JAPAN_FIELD_WEBINAR_Hands-on-for-Beginners-AIML_2021.zip
   creating: resources/
  inflating: __MACOSX/._resources    
  inflating: resources/.DS_Store     
  inflating: __MACOSX/resources/._.DS_Store  
  inflating: resources/08_kanazawa32.png  
  inflating: __MACOSX/resources/._08_kanazawa32.png  
  inflating: resources/02_ratings.csv  
  inflating: __MACOSX/resources/._02_ratings.csv  
  inflating: resources/02_sample_bucket_policy.txt  
  inflating: __MACOSX/resources/._02_sample_bucket_policy.txt  
  inflating: resources/08_sample_movie.mp4  
  inflating: __MACOSX/resources/._08_sample_movie.mp4  
  inflating: resources/06_sample.mp3  
  inflating: __MACOSX/resources/._06_sample.mp3  
  inflating: resources/04_pvs.csv    
  inflating: __MACOSX/resources/._04_pvs.csv  
  inflating: resources/07_sample_text.txt  
  inflating: __MACOSX/resources/._07_sample_text.txt  
  inflating: resources/08_kanazawa10.JPG  
  inflating: __MACOSX/resources/._08_kanazawa10.JPG  

アップロード

コマンド
# アップロードファイル名
UPLOAD_FILENAME="02_ratings.csv" \
&& echo ${UPLOAD_FILENAME}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-130-51-169 ~]$ UPLOAD_FILENAME="02_ratings.csv" \
> && echo ${UPLOAD_FILENAME}
02_ratings.csv
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # アップロード
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/
upload: resources/02_ratings.csv to s3://h4b-personalize-20241020/02_ratings.csv

S3バケット内オブジェクト確認

コマンド
# S3バケット内オブジェクト確認 (最新のオブジェクト)
aws s3api list-object-versions \
    --bucket ${S3_BUCKET_NAME} \
    --query 'Versions | sort_by(@, &LastModified)[-1]' \
    --output json

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # S3バケット内オブジェクト確認 (最新のオブジェクト)
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3api list-object-versions \
>     --bucket ${S3_BUCKET_NAME} \
>     --query 'Versions | sort_by(@, &LastModified)[-1]' \
>     --output json
{
    "ETag": "\"5908a03c26b36cb3abd59b26992a8158\"",
    "Size": 2080371,
    "StorageClass": "STANDARD",
    "Key": "02_ratings.csv",
    "VersionId": "null",
    "IsLatest": true,
    "LastModified": "2024-10-20T07:01:19+00:00",
    "Owner": {
        "DisplayName": "user01",
        "ID": "974cd83317461904fcbad632a42045ad8cd85cb24065c65f2ca62b7e35d84078"
    }
}

IAM

IAMポリシー

コマンド
# IAMポリシー名
IAM_POLICY_NAME="AmazonPersonalize-ExecutionPolicy-h4b" \
&& echo ${IAM_POLICY_NAME}

# ポリシードキュメントの作成
POLICY_DOCUMENT_JSON=$(cat << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::${S3_BUCKET_NAME}"
            ]
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::${S3_BUCKET_NAME}/*"
            ]
        }
    ]
}
EOF
) \
&& echo ${POLICY_DOCUMENT_JSON}

# JSONフォーマットの確認
echo ${POLICY_DOCUMENT_JSON} | python -m json.tool

# ポリシーの作成
aws iam create-policy \
    --policy-name ${IAM_POLICY_NAME} \
    --policy-document "${POLICY_DOCUMENT_JSON}" \
    --path /service-role/

# ARN取得
IAM_POLICY_ARN=$(
    aws iam list-policies \
        --query "Policies[?PolicyName=='${IAM_POLICY_NAME}'].Arn" \
        --output text
) \
&& echo ${IAM_POLICY_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMポリシー名
[cloudshell-user@ip-10-130-51-169 ~]$ IAM_POLICY_NAME="AmazonPersonalize-ExecutionPolicy-h4b" \
> && echo ${IAM_POLICY_NAME}
AmazonPersonalize-ExecutionPolicy-h4b
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ポリシードキュメントの作成
[cloudshell-user@ip-10-130-51-169 ~]$ POLICY_DOCUMENT_JSON=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Action": [
>                 "s3:ListBucket"
>             ],
>             "Effect": "Allow",
>             "Resource": [
>                 "arn:aws:s3:::${S3_BUCKET_NAME}"
>             ]
>         },
>         {
>             "Action": [
>                 "s3:GetObject",
>                 "s3:PutObject"
>             ],
>             "Effect": "Allow",
>             "Resource": [
>                 "arn:aws:s3:::${S3_BUCKET_NAME}/*"
>             ]
>         }
>     ]
> }
> EOF
> ) \
> && echo ${POLICY_DOCUMENT_JSON}
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:ListBucket" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::h4b-personalize-20241020" ] }, { "Action": [ "s3:GetObject", "s3:PutObject" ], "Effect": "Allow", "Resource": [ "arn:aws:s3:::h4b-personalize-20241020/*" ] } ] }
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-51-169 ~]$ echo ${POLICY_DOCUMENT_JSON} | python -m json.tool
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::h4b-personalize-20241020"
            ]
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::h4b-personalize-20241020/*"
            ]
        }
    ]
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ポリシーの作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam create-policy \
>     --policy-name ${IAM_POLICY_NAME} \
>     --policy-document "${POLICY_DOCUMENT_JSON}" \
>     --path /service-role/
{
    "Policy": {
        "PolicyName": "AmazonPersonalize-ExecutionPolicy-h4b",
        "PolicyId": "ANPAWFKRCMKOSTCPP7HGJ",
        "Arn": "arn:aws:iam::999999999999:policy/service-role/AmazonPersonalize-ExecutionPolicy-h4b",
        "Path": "/service-role/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2024-10-20T07:42:49+00:00",
        "UpdateDate": "2024-10-20T07:42:49+00:00"
    }
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ IAM_POLICY_ARN=$(
>     aws iam list-policies \
>         --query "Policies[?PolicyName=='${IAM_POLICY_NAME}'].Arn" \
>         --output text
> ) \
> && echo ${IAM_POLICY_ARN}
arn:aws:iam::999999999999:policy/service-role/AmazonPersonalize-ExecutionPolicy-h4b

IAMロール

コマンド
# 変数
IAM_ROLE_NAME="AmazonPersonalize-ExecutionRole-h4b" \
&& echo ${IAM_ROLE_NAME}

# 信頼関係ポリシードキュメントの作成
ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "personalize.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
EOF
) \
&& echo ${ASSUME_ROLE_POLICY_DOCUMENT}

# JSONフォーマットの確認
echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool

# IAMロールの作成
aws iam create-role \
    --role-name ${IAM_ROLE_NAME} \
    --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}" \
    --path /service-role/

# ARN取得
IAM_ROLE_ARN=$(
    aws iam get-role \
        --role-name ${IAM_ROLE_NAME} \
        --query 'Role.Arn' --output text
) \
&& echo ${IAM_ROLE_ARN}

# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${IAM_ROLE_NAME} \
    --policy-arn ${IAM_POLICY_ARN} \

# AWS管理ポリシー
AWS_MGMT_POLICY_NAME="AmazonPersonalizeFullAccess" \
&& echo ${AWS_MGMT_POLICY_NAME}

# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${IAM_ROLE_NAME} \
    --policy-arn arn:aws:iam::aws:policy/service-role/${AWS_MGMT_POLICY_NAME}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # 変数
[cloudshell-user@ip-10-130-51-169 ~]$ IAM_ROLE_NAME="AmazonPersonalize-ExecutionRole-h4b" \
> && echo ${IAM_ROLE_NAME}
AmazonPersonalize-ExecutionRole-h4b
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # 信頼関係ポリシードキュメントの作成
[cloudshell-user@ip-10-130-51-169 ~]$ ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Effect": "Allow",
>             "Principal": {
>                 "Service": "personalize.amazonaws.com"
>             },
>             "Action": "sts:AssumeRole"
>         }
>     ]
> }
> EOF
> ) \
> && echo ${ASSUME_ROLE_POLICY_DOCUMENT}
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "personalize.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-51-169 ~]$ echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "personalize.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMロールの作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam create-role \
>     --role-name ${IAM_ROLE_NAME} \
>     --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}" \
>     --path /service-role/
{
    "Role": {
        "Path": "/service-role/",
        "RoleName": "AmazonPersonalize-ExecutionRole-h4b",
        "RoleId": "AROAWFKRCMKO5QON6N6YM",
        "Arn": "arn:aws:iam::999999999999:role/service-role/AmazonPersonalize-ExecutionRole-h4b",
        "CreateDate": "2024-10-20T07:45:17+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "personalize.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ IAM_ROLE_ARN=$(
>     aws iam get-role \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'Role.Arn' --output text
> ) \
> && echo ${IAM_ROLE_ARN}
arn:aws:iam::999999999999:role/service-role/AmazonPersonalize-ExecutionRole-h4b
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam attach-role-policy \
>     --role-name ${IAM_ROLE_NAME} \
>     --policy-arn ${IAM_POLICY_ARN} \
> 
[cloudshell-user@ip-10-130-51-169 ~]$ # AWS管理ポリシー
[cloudshell-user@ip-10-130-51-169 ~]$ AWS_MGMT_POLICY_NAME="AmazonPersonalizeFullAccess" \
> && echo ${AWS_MGMT_POLICY_NAME}
AmazonPersonalizeFullAccess
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam attach-role-policy \
>     --role-name ${IAM_ROLE_NAME} \
>     --policy-arn arn:aws:iam::aws:policy/service-role/${AWS_MGMT_POLICY_NAME}

Amazon Personalize

データセットグループ作成

コマンド
# データセットグループ名
DATASET_GROUP_NAME="h4b-movie-ratings" \
&& echo ${DATASET_GROUP_NAME}

# データセットグループ作成
aws personalize create-dataset-group --name ${DATASET_GROUP_NAME}

# ARN取得
DATASET_GROUP_ARN=$(
aws personalize list-dataset-groups  \
    --query "datasetGroups[?name=='${DATASET_GROUP_NAME}'].datasetGroupArn" \
    --output text
) \
&& echo ${DATASET_GROUP_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # データセットグループ名
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_GROUP_NAME="h4b-movie-ratings" \
> && echo ${DATASET_GROUP_NAME}
h4b-movie-ratings
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # データセットグループ作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-dataset-group --name ${DATASET_GROUP_NAME}
{
    "datasetGroupArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_GROUP_ARN=$(
> aws personalize list-dataset-groups  \
>     --query "datasetGroups[?name=='${DATASET_GROUP_NAME}'].datasetGroupArn" \
>     --output text
> ) \
> && echo ${DATASET_GROUP_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings

データセットグループ確認

コマンド
# データセットグループ確認
aws personalize describe-dataset-group --dataset-group-arn ${DATASET_GROUP_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # データセットグループ確認
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-dataset-group --dataset-group-arn ${DATASET_GROUP_ARN}
{
    "datasetGroup": {
        "name": "h4b-movie-ratings",
        "datasetGroupArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings",
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T16:11:14.345000+09:00",
        "lastUpdatedDateTime": "2024-10-20T16:11:20.042000+09:00"
    }
}

スキーマセットJSON作成

コマンド
# スキーマセットJSON作成
SCHEMA_JSON=$(cat << EOF 
{
  "type": "record",
  "name": "Interactions",
  "namespace": "com.amazonaws.personalize.schema",
  "fields": [
    {
      "name": "USER_ID",
      "type": "string"
    },
    {
      "name": "ITEM_ID",
      "type": "string"
    },
    {
      "name": "TIMESTAMP",
      "type": "long"
    }
  ],
  "version": "1.0"
}
EOF
) \
&& echo ${SCHEMA_JSON} | python -m json.tool

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # スキーマセットJSON作成
[cloudshell-user@ip-10-130-51-169 ~]$ SCHEMA_JSON=$(cat << EOF 
> {
>   "type": "record",
>   "name": "Interactions",
>   "namespace": "com.amazonaws.personalize.schema",
>   "fields": [
>     {
>       "name": "USER_ID",
>       "type": "string"
>     },
>     {
>       "name": "ITEM_ID",
>       "type": "string"
>     },
>     {
>       "name": "TIMESTAMP",
>       "type": "long"
>     }
>   ],
>   "version": "1.0"
> }
> EOF
> ) \
> && echo ${SCHEMA_JSON} | python -m json.tool
{
    "type": "record",
    "name": "Interactions",
    "namespace": "com.amazonaws.personalize.schema",
    "fields": [
        {
            "name": "USER_ID",
            "type": "string"
        },
        {
            "name": "ITEM_ID",
            "type": "string"
        },
        {
            "name": "TIMESTAMP",
            "type": "long"
        }
    ],
    "version": "1.0"
}

スキーマセット作成

コマンド
# スキーマ名
SCHEMA_NAME="h4b-schema" \
&& echo ${SCHEMA_NAME}

# スキーマセット作成
aws personalize create-schema \
    --name ${SCHEMA_NAME} \
    --schema "${SCHEMA_JSON}"

# ARN取得
SCHEMA_ARN=$(
aws personalize list-schemas \
    --query "schemas[?name=='${SCHEMA_NAME}'].schemaArn" \
    --output text
) \
&& echo ${SCHEMA_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # スキーマ名
[cloudshell-user@ip-10-130-51-169 ~]$ SCHEMA_NAME="h4b-schema" \
> && echo ${SCHEMA_NAME}
h4b-schema
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # スキーマセット作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-schema \
>     --name ${SCHEMA_NAME} \
>     --schema "${SCHEMA_JSON}"
{
    "schemaArn": "arn:aws:personalize:ap-northeast-1:999999999999:schema/h4b-schema"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ SCHEMA_ARN=$(
> aws personalize list-schemas \
>     --query "schemas[?name=='${SCHEMA_NAME}'].schemaArn" \
>     --output text
> ) \
> && echo ${SCHEMA_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:schema/h4b-schema

スキーマセット確認

コマンド
aws personalize describe-schema \
    --schema-arn ${SCHEMA_ARN} \
    --query "schema.schema" \
    --output text

出力
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-schema \
>     --schema-arn ${SCHEMA_ARN} \
>     --query "schema.schema" \
>     --output text
{
  "type": "record",
  "name": "Interactions",
  "namespace": "com.amazonaws.personalize.schema",
  "fields": [
    {
      "name": "USER_ID",
      "type": "string"
    },
    {
      "name": "ITEM_ID",
      "type": "string"
    },
    {
      "name": "TIMESTAMP",
      "type": "long"
    }
  ],
  "version": "1.0"
}

データセット作成

コマンド
# データセット名
DATASET_NAME="movie-ratings" \
&& echo ${DATASET_NAME}

# データセットタイプ
DATASET_TYPE="INTERACTIONS" \
&& echo ${DATASET_TYPE}

# データセット作成
aws personalize create-dataset \
    --dataset-type ${DATASET_TYPE} \
    --schema-arn ${SCHEMA_ARN} \
    --dataset-group-arn ${DATASET_GROUP_ARN} \
    --name ${DATASET_NAME}

# ARN取得
DATASET_ARN=$(
aws personalize list-datasets \
    --query "datasets[?name=='${DATASET_NAME}'].datasetArn" \
    --output text
) \
&& echo ${DATASET_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # データセット名
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_NAME="movie-ratings" \
> && echo ${DATASET_NAME}
movie-ratings
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # データセットタイプ
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_TYPE="INTERACTIONS" \
> && echo ${DATASET_TYPE}
INTERACTIONS
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # データセット作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-dataset \
>     --dataset-type ${DATASET_TYPE} \
>     --schema-arn ${SCHEMA_ARN} \
>     --dataset-group-arn ${DATASET_GROUP_ARN} \
>     --name ${DATASET_NAME}
{
    "datasetArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset/h4b-movie-ratings/INTERACTIONS"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_ARN=$(
> aws personalize list-datasets \
>     --query "datasets[?name=='${DATASET_NAME}'].datasetArn" \
>     --output text
> ) \
> && echo ${DATASET_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:dataset/h4b-movie-ratings/INTERACTIONS

データセット確認

コマンド
# データセット確認
aws personalize describe-dataset --dataset-arn ${DATASET_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # データセット確認
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-dataset --dataset-arn ${DATASET_ARN}
{
    "dataset": {
        "name": "movie-ratings",
        "datasetArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset/h4b-movie-ratings/INTERACTIONS",
        "datasetGroupArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings",
        "datasetType": "INTERACTIONS",
        "schemaArn": "arn:aws:personalize:ap-northeast-1:999999999999:schema/h4b-schema",
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T16:25:03.202000+09:00",
        "lastUpdatedDateTime": "2024-10-20T16:25:22.134000+09:00"
    }
}

データインポートジョブ作成

コマンド
# ジョブ名
JOB_NAME="h4b-movie-ratings-import-job" \
&& echo ${JOB_NAME}

# データインポートジョブ作成
aws personalize create-dataset-import-job \
    --job-name ${JOB_NAME} \
    --dataset-arn ${DATASET_ARN} \
    --data-source dataLocation=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME} \
    --role-arn ${IAM_ROLE_ARN}

# ARN取得
DATASET_IMPORT_JOB_ARN=$(
aws personalize list-dataset-import-jobs \
    --query "datasetImportJobs[?jobName=='${JOB_NAME}'].datasetImportJobArn" \
    --output text
) \
&& echo ${DATASET_IMPORT_JOB_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ジョブ名
[cloudshell-user@ip-10-130-51-169 ~]$ JOB_NAME="h4b-movie-ratings-import-job" \
> && echo ${JOB_NAME}
h4b-movie-ratings-import-job
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # データインポートジョブ作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-dataset-import-job \
>     --job-name ${JOB_NAME} \
>     --dataset-arn ${DATASET_ARN} \
>     --data-source dataLocation=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME} \
>     --role-arn ${IAM_ROLE_ARN}
{
    "datasetImportJobArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-import-job/h4b-movie-ratings-import-job"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ DATASET_IMPORT_JOB_ARN=$(
> aws personalize list-dataset-import-jobs \
>     --query "datasetImportJobs[?jobName=='${JOB_NAME}'].datasetImportJobArn" \
>     --output text
> ) \
> && echo ${DATASET_IMPORT_JOB_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:dataset-import-job/h4b-movie-ratings-import-job

ジョブステータスの確認

コマンド
# ジョブステータスの確認
aws personalize describe-dataset-import-job \
    --dataset-import-job-arn ${DATASET_IMPORT_JOB_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ジョブステータスの確認
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-dataset-import-job \
>     --dataset-import-job-arn ${DATASET_IMPORT_JOB_ARN}
{
    "datasetImportJob": {
        "jobName": "h4b-movie-ratings-import-job",
        "datasetImportJobArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-import-job/h4b-movie-ratings-import-job",
        "datasetArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset/h4b-movie-ratings/INTERACTIONS",
        "dataSource": {
            "dataLocation": "s3://h4b-personalize-20241020/02_ratings.csv"
        },
        "roleArn": "arn:aws:iam::999999999999:role/service-role/AmazonPersonalize-ExecutionRole-h4b",
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T16:52:43.850000+09:00",
        "lastUpdatedDateTime": "2024-10-20T16:55:49.764000+09:00",
        "importMode": "FULL",
        "publishAttributionMetricsToS3": false
    }
}

03 Amazon Personalize を用いてレコメンデーションを行う(2)

Create solutions

ソリューション作成

コマンド
# ソリューション名
SOLUTIO_NNAME="h4b-solution" \
&& echo ${SOLUTIO_NNAME}

# レシピ名
RECIPE_NAME=aws-user-personalization-v2 \
&& echo ${RECIPE_NAME}

aws personalize create-solution \
    --name ${SOLUTIO_NNAME} \
    --dataset-group-arn ${DATASET_GROUP_ARN} \
    --recipe-arn "arn:aws:personalize:::recipe/${RECIPE_NAME}"

# ARN取得
SOLUTIO_ARN=$(
aws personalize list-solutions \
    --query "solutions[?name=='${SOLUTIO_NNAME}'].solutionArn" \
    --output text
) \
&& echo ${SOLUTIO_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ソリューション名
[cloudshell-user@ip-10-130-51-169 ~]$ SOLUTIO_NNAME="h4b-solution" \
> && echo ${SOLUTIO_NNAME}
h4b-solution
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # レシピ名
[cloudshell-user@ip-10-130-51-169 ~]$ RECIPE_NAME=aws-user-personalization-v2 \
> && echo ${RECIPE_NAME}
aws-user-personalization-v2
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-solution \
>     --name ${SOLUTIO_NNAME} \
>     --dataset-group-arn ${DATASET_GROUP_ARN} \
>     --recipe-arn "arn:aws:personalize:::recipe/${RECIPE_NAME}"
{
    "solutionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ SOLUTIO_ARN=$(
> aws personalize list-solutions \
>     --query "solutions[?name=='${SOLUTIO_NNAME}'].solutionArn" \
>     --output text
> ) \
> && echo ${SOLUTIO_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution

ソリューション確認

コマンド
# ソリューション確認
aws personalize describe-solution \
    --solution-arn ${SOLUTIO_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ソリューション確認
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-solution \
>     --solution-arn ${SOLUTIO_ARN}
{
    "solution": {
        "name": "h4b-solution",
        "solutionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution",
        "performHPO": false,
        "performAutoML": false,
        "performAutoTraining": true,
        "recipeArn": "arn:aws:personalize:::recipe/aws-user-personalization-v2",
        "datasetGroupArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings",
        "solutionConfig": {
            "autoTrainingConfig": {
                "schedulingExpression": "rate(7 days)"
            }
        },
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T17:04:46.299000+09:00",
        "lastUpdatedDateTime": "2024-10-20T17:04:46.299000+09:00"
    }
}

トレーニング実施

トレーニングの完了まで約30分かかります

コマンド
# トレーニング実施
aws personalize create-solution-version \
    --solution-arn ${SOLUTIO_ARN}

SOLUTIONVERSION_ARN=$(
aws personalize list-solution-versions --solution-arn ${SOLUTIO_ARN} \
    --query 'sort_by(solutionVersions, &creationDateTime)[-1].solutionVersionArn' \
    --output text
) \
&& echo ${SOLUTIONVERSION_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # トレーニング実施
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-solution-version \
>     --solution-arn ${SOLUTIO_ARN}
{
    "solutionVersionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution/90f9ca49"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ SOLUTIONVERSION_ARN=$(
> aws personalize list-solution-versions --solution-arn ${SOLUTIO_ARN} \
>     --query 'sort_by(solutionVersions, &creationDateTime)[-1].solutionVersionArn' \
>     --output text
> ) \
> && echo ${SOLUTIONVERSION_ARN}
arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution/90f9ca49

トレーニングのステータス確認

コマンド
# トレーニングのステータス確認
aws personalize describe-solution-version \
    --solution-version-arn ${SOLUTIONVERSION_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-solution-version     --solution-version-arn ${SOLUTIONVERSION_ARN}
{
    "solutionVersion": {
        "name": "h4b-solution/90f9ca49",
        "solutionVersionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution/90f9ca49",
        "solutionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution",
        "performHPO": false,
        "performAutoML": false,
        "recipeArn": "arn:aws:personalize:::recipe/aws-user-personalization-v2",
        "datasetGroupArn": "arn:aws:personalize:ap-northeast-1:999999999999:dataset-group/h4b-movie-ratings",
        "solutionConfig": {
            "autoTrainingConfig": {
                "schedulingExpression": "rate(7 days)"
            }
        },
        "trainingHours": 2.077,
        "trainingMode": "FULL",
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T17:08:14.499000+09:00",
        "lastUpdatedDateTime": "2024-10-20T17:34:38.037000+09:00",
        "trainingType": "MANUAL"
    }
}

Create campaign

キャンペーンの作成

コマンド
# キャンペーン名
CAMPAIG_NNAME="h4b-campain" \
&& echo ${CAMPAIG_NNAME}

# 最小プロビジョニングキャンペーン数
MIN_PROVISIONED_TPS=1 \
&& echo ${MIN_PROVISIONED_TPS}

# キャンペーンの作成
aws personalize create-campaign \
    --name ${CAMPAIG_NNAME} \
    --solution-version-arn ${SOLUTIONVERSION_ARN} \
    --min-provisioned-tps ${MIN_PROVISIONED_CAMPAIGN}

# ARN取得
CAMPAIG_ARN=$(
aws personalize list-campaigns \
    --query "campaigns[?name=='${CAMPAIG_NNAME}'].campaignArn" \
    --output text
) \
&& echo ${CAMPAIG_ARN} 

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # キャンペーン名
[cloudshell-user@ip-10-130-51-169 ~]$ CAMPAIG_NNAME="h4b-campain" \
> && echo ${CAMPAIG_NNAME}
h4b-campain
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # 最小プロビジョニングキャンペーン数
[cloudshell-user@ip-10-130-51-169 ~]$ MIN_PROVISIONED_TPS=1 \
> && echo ${MIN_PROVISIONED_TPS}
1
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # キャンペーンの作成
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize create-campaign \
>     --name ${CAMPAIG_NNAME} \
>     --solution-version-arn ${SOLUTIONVERSION_ARN} \
>     --min-provisioned-tps ${MIN_PROVISIONED_CAMPAIGN}
{
    "campaignArn": "arn:aws:personalize:ap-northeast-1:999999999999:campaign/h4b-campain"
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # ARN取得
[cloudshell-user@ip-10-130-51-169 ~]$ CAMPAIG_ARN=$(
> aws personalize list-campaigns \
>     --query "campaigns[?name=='${CAMPAIG_NNAME}'].campaignArn" \
>     --output text
> ) \
> && echo ${CAMPAIG_ARN} 
arn:aws:personalize:ap-northeast-1:999999999999:campaign/h4b-campain

キャンペーンの確認

コマンド
# キャンペーンの確認
aws personalize describe-campaign --campaign-arn ${CAMPAIG_ARN} 

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # キャンペーンの確認
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize describe-campaign --campaign-arn ${CAMPAIG_ARN} 
{
    "campaign": {
        "name": "h4b-campain",
        "campaignArn": "arn:aws:personalize:ap-northeast-1:999999999999:campaign/h4b-campain",
        "solutionVersionArn": "arn:aws:personalize:ap-northeast-1:999999999999:solution/h4b-solution/90f9ca49",
        "minProvisionedTPS": 1,
        "campaignConfig": {
            "enableMetadataWithRecommendations": true
        },
        "status": "ACTIVE",
        "creationDateTime": "2024-10-20T17:48:08.717000+09:00",
        "lastUpdatedDateTime": "2024-10-20T18:00:45.468000+09:00"
    }
}

レコメンデーション取得

コマンド
# レコメンデーション取得
aws personalize-runtime get-recommendations \
    --campaign-arn ${CAMPAIG_ARN} \
    --user-id 5 \
    --no-cli-pager

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # レコメンデーション取得
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize-runtime get-recommendations \
>     --campaign-arn ${CAMPAIG_ARN} \
>     --user-id 5 \
>     --no-cli-pager
{
    "itemList": [
        {
            "itemId": "356",
            "score": 0.002081
        },
        {
            "itemId": "47",
            "score": 0.0019847
        },
        {
            "itemId": "586",
            "score": 0.0018731
        },
        {
            "itemId": "474",
            "score": 0.0018585
        },
        {
            "itemId": "1265",
            "score": 0.0018452
        },
        {
            "itemId": "520",
            "score": 0.0018053
        },
        {
            "itemId": "368",
            "score": 0.0016982
        },
        {
            "itemId": "593",
            "score": 0.0015663
        },
        {
            "itemId": "648",
            "score": 0.001549
        },
        {
            "itemId": "442",
            "score": 0.0015333
        },
        {
            "itemId": "733",
            "score": 0.0015269
        },
        {
            "itemId": "1073",
            "score": 0.0015176
        },
        {
            "itemId": "357",
            "score": 0.0014609
        },
        {
            "itemId": "597",
            "score": 0.0014488
        },
        {
            "itemId": "350",
            "score": 0.0014229
        },
        {
            "itemId": "6",
            "score": 0.0014207
        },
        {
            "itemId": "589",
            "score": 0.0014199
        },
        {
            "itemId": "527",
            "score": 0.0013948
        },
        {
            "itemId": "2",
            "score": 0.0013944
        },
        {
            "itemId": "110",
            "score": 0.0013901
        },
        {
            "itemId": "318",
            "score": 0.0013649
        },
        {
            "itemId": "1270",
            "score": 0.0013598
        },
        {
            "itemId": "551",
            "score": 0.0013477
        },
        {
            "itemId": "377",
            "score": 0.0013399
        },
        {
            "itemId": "500",
            "score": 0.0013172
        }
    ],
    "recommendationId": "RID-14-4bcb-adbc-09c3909904a0-CID-0e0643"
}

削除

Amazon Personalize

コマンド
# Campain削除 (約30分)
aws personalize delete-campaign \
    --campaign-arn ${CAMPAIG_ARN} 

# Solution削除
aws personalize delete-solution \
    --solution-arn ${SOLUTIO_ARN}
    
# Dataset削除
aws personalize delete-dataset \
    --dataset-arn ${DATASET_ARN}

# Dataset group削除
aws personalize delete-dataset-group \
    --dataset-group-arn ${DATASET_GROUP_ARN}

# スキーマ削除
aws personalize delete-schema \
    --schema-arn arn:aws:personalize:ap-northeast-1:999999999999:schema/h4b-schema

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # Campain削除 (約30分)
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize delete-campaign \
>     --campaign-arn ${CAMPAIG_ARN} 
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # Solution削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize delete-solution \
>     --solution-arn ${SOLUTIO_ARN}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # Dataset削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize delete-dataset \
>     --dataset-arn ${DATASET_ARN}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # Dataset group削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize delete-dataset-group \
>     --dataset-group-arn ${DATASET_GROUP_ARN}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # スキーマ削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws personalize delete-schema \
>     --schema-arn arn:aws:personalize:ap-northeast-1:999999999999:schema/h4b-schema

IAM

コマンド
# ロールにアタッチされているポリシーをリスト
POLICIES=$(
    aws iam list-attached-role-policies \
        --role-name ${IAM_ROLE_NAME} \
        --query 'AttachedPolicies[*].PolicyArn' \
        --output text
) \
&& echo ${POLICIES}

# リスト内のポリシーをデタッチする
for POLICY in ${POLICIES}; do
    aws iam detach-role-policy \
        --role-name ${IAM_ROLE_NAME} \
        --policy-arn ${POLICY}
done

# IAMロールの削除
aws iam delete-role \
    --role-name ${IAM_ROLE_NAME}

# IAMポリシーの削除
aws iam delete-policy \
    --policy-arn ${IAM_POLICY_ARN}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # ロールにアタッチされているポリシーをリスト
[cloudshell-user@ip-10-130-51-169 ~]$ POLICIES=$(
>     aws iam list-attached-role-policies \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'AttachedPolicies[*].PolicyArn' \
>         --output text
> ) \
> && echo ${POLICIES}
arn:aws:iam::999999999999:policy/service-role/AmazonPersonalize-ExecutionPolicy-h4b arn:aws:iam::aws:policy/service-role/AmazonPersonalizeFullAccess
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # リスト内のポリシーをデタッチする
[cloudshell-user@ip-10-130-51-169 ~]$ for POLICY in ${POLICIES}; do
>     aws iam detach-role-policy \
>         --role-name ${IAM_ROLE_NAME} \
>         --policy-arn ${POLICY}
> done
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMロールの削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam delete-role \
>     --role-name ${IAM_ROLE_NAME}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # IAMポリシーの削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws iam delete-policy \
>     --policy-arn ${IAM_POLICY_ARN}

S3

コマンド
# オブジェクト一覧取得
OBJECT_LIST=$(
    aws s3api list-object-versions \
        --bucket ${S3_BUCKET_NAME} \
        --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
) \
&& echo ${OBJECT_LIST}

# JSONフォーマットの確認
echo ${OBJECT_LIST} | python -m json.tool

# バケットを空にする
aws s3api delete-objects \
    --bucket ${S3_BUCKET_NAME} \
    --delete "${OBJECT_LIST}"

# S3バケットを削除
aws s3api delete-bucket \
    --bucket ${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-51-169 ~]$ # オブジェクト一覧取得
[cloudshell-user@ip-10-130-51-169 ~]$ OBJECT_LIST=$(
>     aws s3api list-object-versions \
>         --bucket ${S3_BUCKET_NAME} \
>         --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
> ) \
> && echo ${OBJECT_LIST}
{ "Objects": [ { "Key": "02_ratings.csv", "VersionId": "null" } ] }
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-51-169 ~]$ echo ${OBJECT_LIST} | python -m json.tool
{
    "Objects": [
        {
            "Key": "02_ratings.csv",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # バケットを空にする
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3api delete-objects \
>     --bucket ${S3_BUCKET_NAME} \
>     --delete "${OBJECT_LIST}"
{
    "Deleted": [
        {
            "Key": "02_ratings.csv",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-51-169 ~]$ 
[cloudshell-user@ip-10-130-51-169 ~]$ # S3バケットを削除
[cloudshell-user@ip-10-130-51-169 ~]$ aws s3api delete-bucket \
>     --bucket ${S3_BUCKET_NAME}

04 Amazon Forecast を用いて時系列数値予測を行う(1)

Amazon Forecastを使用できなかったため、未実施

05 Amazon Forecast を用いて時系列数値予測を行う(2)

Amazon Forecastを使用できなかったため、未実施

06 Amazon Transcribe を用いて文字起こしを行う

S3バケット作成

S3バケット作成

コマンド
# バケット名
date_var=$(date +%Y%m%d) \
&& echo ${date_var}
S3_BUCKET_NAME="h4b-transcribe-${date_var}" \
&& echo ${S3_BUCKET_NAME}

# S3バケット作成
aws s3 mb s3://${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # バケット名
[cloudshell-user@ip-10-130-32-74 ~]$ date_var=$(date +%Y%m%d) \
> && echo ${date_var}
20241020
[cloudshell-user@ip-10-130-32-74 ~]$ S3_BUCKET_NAME="h4b-transcribe-${date_var}" \
> && echo ${S3_BUCKET_NAME}
h4b-transcribe-20241020
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 mb s3://${S3_BUCKET_NAME}
make_bucket: h4b-transcribe-20241020

アップロード

コマンド
# アップロードファイル名
UPLOAD_FILENAME="06_sample.mp3" \
&& echo ${UPLOAD_FILENAME}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-130-32-74 ~]$ UPLOAD_FILENAME="06_sample.mp3" \
> && echo ${UPLOAD_FILENAME}
06_sample.mp3
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # アップロード
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/
upload: resources/06_sample.mp3 to s3://h4b-transcribe-20241020/06_sample.mp3

S3バケット内オブジェクト確認

コマンド
# S3バケット内オブジェクト確認 (最新のオブジェクト)
aws s3api list-object-versions \
    --bucket ${S3_BUCKET_NAME} \
    --query 'Versions | sort_by(@, &LastModified)[-1]' \
    --output json

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット内オブジェクト確認 (最新のオブジェクト)
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api list-object-versions \
>     --bucket ${S3_BUCKET_NAME} \
>     --query 'Versions | sort_by(@, &LastModified)[-1]' \
>     --output json
{
    "ETag": "\"18fc7f0024c99b45f741d528d0411086\"",
    "Size": 27944,
    "StorageClass": "STANDARD",
    "Key": "06_sample.mp3",
    "VersionId": "null",
    "IsLatest": true,
    "LastModified": "2024-10-20T12:13:05+00:00",
    "Owner": {
        "DisplayName": "user01",
        "ID": "974cd83317461904fcbad632a42045ad8cd85cb24065c65f2ca62b7e35d84078"
    }
}

トランスクリプションジョブ作成

変数

コマンド
# ジョブ名
TRANSCRIPTION_JOB_NAME="h4b-transcribe-job" \
&& echo ${TRANSCRIPTION_JOB_NAME}

# 言語
TRANSCRIPTION_LANG_CODE="ja-JP" \
&& echo ${TRANSCRIPTION_LANG_CODE}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # ジョブ名
[cloudshell-user@ip-10-130-32-74 ~]$ TRANSCRIPTION_JOB_NAME="h4b-transcribe-job" \
> && echo ${TRANSCRIPTION_JOB_NAME}
h4b-transcribe-job
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # 言語
[cloudshell-user@ip-10-130-32-74 ~]$ TRANSCRIPTION_LANG_CODE="ja-JP" \
> && echo ${TRANSCRIPTION_LANG_CODE}
ja-JP

トランスクリプションジョブ作成

コマンド
# トランスクリプションジョブ作成
aws transcribe start-transcription-job \
    --transcription-job-name "${TRANSCRIPTION_JOB_NAME}" \
    --language-code "${TRANSCRIPTION_LANG_CODE}" \
    --media MediaFileUri=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME} \
    --output-bucket-name "${S3_BUCKET_NAME}"

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # トランスクリプションジョブ作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws transcribe start-transcription-job \
>     --transcription-job-name "${TRANSCRIPTION_JOB_NAME}" \
>     --language-code "${TRANSCRIPTION_LANG_CODE}" \
>     --media MediaFileUri=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME} \
>     --output-bucket-name "${S3_BUCKET_NAME}"
{
    "TranscriptionJob": {
        "TranscriptionJobName": "h4b-transcribe-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "ja-JP",
        "Media": {
            "MediaFileUri": "s3://h4b-transcribe-20241020/06_sample.mp3"
        },
        "StartTime": "2024-10-20T21:22:47.922000+09:00",
        "CreationTime": "2024-10-20T21:22:47.886000+09:00"
    }
}

確認

コマンド
# 確認
aws transcribe get-transcription-job \
    --transcription-job-name "${TRANSCRIPTION_JOB_NAME}"

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # 確認
[cloudshell-user@ip-10-130-32-74 ~]$ aws transcribe get-transcription-job \
>     --transcription-job-name "${TRANSCRIPTION_JOB_NAME}"
{
    "TranscriptionJob": {
        "TranscriptionJobName": "h4b-transcribe-job",
        "TranscriptionJobStatus": "COMPLETED",
        "LanguageCode": "ja-JP",
        "MediaSampleRateHertz": 22050,
        "MediaFormat": "mp3",
        "Media": {
            "MediaFileUri": "s3://h4b-transcribe-20241020/06_sample.mp3"
        },
        "Transcript": {
            "TranscriptFileUri": "https://s3.ap-northeast-1.amazonaws.com/h4b-transcribe-20241020/h4b-transcribe-job.json"
        },
        "StartTime": "2024-10-20T21:22:47.922000+09:00",
        "CreationTime": "2024-10-20T21:22:47.886000+09:00",
        "CompletionTime": "2024-10-20T21:22:55.911000+09:00",
        "Settings": {
            "ChannelIdentification": false,
            "ShowAlternatives": false
        }
    }
}

出力確認

S3バケット内のオブジェクトを確認

コマンド
# S3バケット内オブジェクト確認 (最新のオブジェクト)
S3_OBJECT_NAME=$(
aws s3api list-objects-v2 \
    --bucket ${S3_BUCKET_NAME} \
    --query "Contents|sort_by(@, &LastModified)[-1].Key" \
    --output text
) \
&& echo ${S3_OBJECT_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット内オブジェクト確認 (最新のオブジェクト)
[cloudshell-user@ip-10-130-32-74 ~]$ S3_OBJECT_NAME=$(
> aws s3api list-objects-v2 \
>     --bucket ${S3_BUCKET_NAME} \
>     --query "Contents|sort_by(@, &LastModified)[-1].Key" \
>     --output text
> ) \
> && echo ${S3_OBJECT_NAME}
h4b-transcribe-job.json

S3からファイルをダウンロード

コマンド
# ダウンロード
aws s3 cp s3://${S3_BUCKET_NAME}/${S3_OBJECT_NAME} ./

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # ダウンロード
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 cp s3://${S3_BUCKET_NAME}/${S3_OBJECT_NAME} ./
download: s3://h4b-transcribe-20241020/h4b-transcribe-job.json to ./h4b-transcribe-job.json

ダウンロードしたファイルを確認

コマンド
cat ${S3_OBJECT_NAME} | jq .results.transcripts

出力
[cloudshell-user@ip-10-130-32-74 ~]$ cat ${S3_OBJECT_NAME} | jq .results.transcripts
[
  {
    "transcript": "半音順調ですか?手を動かすの楽しいですよ"
  }
]

削除

S3

コマンド
# オブジェクト一覧取得
OBJECT_LIST=$(
    aws s3api list-object-versions \
        --bucket ${S3_BUCKET_NAME} \
        --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
) \
&& echo ${OBJECT_LIST}

# JSONフォーマットの確認
echo ${OBJECT_LIST} | python -m json.tool

# バケットを空にする
aws s3api delete-objects \
    --bucket ${S3_BUCKET_NAME} \
    --delete "${OBJECT_LIST}"

# S3バケットを削除
aws s3api delete-bucket \
    --bucket ${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # オブジェクト一覧取得
[cloudshell-user@ip-10-130-32-74 ~]$ OBJECT_LIST=$(
>     aws s3api list-object-versions \
>         --bucket ${S3_BUCKET_NAME} \
>         --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
> ) \
> && echo ${OBJECT_LIST}
{ "Objects": [ { "Key": ".write_access_check_file.temp", "VersionId": "null" }, { "Key": "06_sample.mp3", "VersionId": "null" }, { "Key": "h4b-transcribe-job.json", "VersionId": "null" } ] }
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-32-74 ~]$ echo ${OBJECT_LIST} | python -m json.tool
{
    "Objects": [
        {
            "Key": ".write_access_check_file.temp",
            "VersionId": "null"
        },
        {
            "Key": "06_sample.mp3",
            "VersionId": "null"
        },
        {
            "Key": "h4b-transcribe-job.json",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # バケットを空にする
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api delete-objects \
>     --bucket ${S3_BUCKET_NAME} \
>     --delete "${OBJECT_LIST}"
{
    "Deleted": [
        {
            "Key": "h4b-transcribe-job.json",
            "VersionId": "null"
        },
        {
            "Key": ".write_access_check_file.temp",
            "VersionId": "null"
        },
        {
            "Key": "06_sample.mp3",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケットを削除
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api delete-bucket \
>     --bucket ${S3_BUCKET_NAME}

トランスクリプションジョブ削除

コマンド
# すべてのジョブ名を取得し、削除するスクリプト
for job_name in $(aws transcribe list-transcription-jobs --query 'TranscriptionJobSummaries[*].TranscriptionJobName' --output text); do
    echo "Deleting transcription job: $job_name"
    aws transcribe delete-transcription-job --transcription-job-name "${job_name}"
done

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # すべてのジョブ名を取得し、削除するスクリプト
[cloudshell-user@ip-10-130-32-74 ~]$ for job_name in $(aws transcribe list-transcription-jobs --query 'TranscriptionJobSummaries[*].TranscriptionJobName' --output text); do
>     echo "Deleting transcription job: $job_name"
>     aws transcribe delete-transcription-job --transcription-job-name "${job_name}"
> done
Deleting transcription job: h4b-transcribe-job

07 Amazon Comprehend を用いて自然言語処理を行う

Real-time analysis

コマンド
ARTICLE="IAM ロール画面に遷移するので、こちらの「ポリシーをアタッチします」ボタンをクリックしてください。IAM ロールには複数の IAM ポリシーをアタッチすることができるので、Amazon Comprehend の機能を利用するためのポリシーをアタッチしていきます。(なお、IAM に関するハンズオン も用意しておりますので、あわせてご覧いただければと思います。)" \
&& echo ${ARTICLE}

aws comprehend detect-sentiment --language-code "ja" --text "${ARTICLE}"

出力
[cloudshell-user@ip-10-130-32-74 ~]$ ARTICLE="IAM ロール画面に遷移するので、こちらの「ポリシーをアタッチします」ボタンをクリックしてくだ さい。IAM ロールには複数の IAM ポリシーをアタッチすることができるので、Amazon Comprehend の機能を利用するためのポリシーをアタッチしていきます。(なお、IAM に関するハンズオン も用意しておりますので、あわせてご覧いただければと思います。)" \
> && echo ${ARTICLE}
IAM ロール画面に遷移するので、こちらの「ポリシーをアタッチします」ボタンをクリックしてください。IAM ロールには複数の IAM ポリシーをアタッチすることができるので、Amazon Comprehend の機能を利用するためのポリシーをアタッチしていきます。(なお、IAM に関するハンズオン も用意して おりますので、あわせてご覧いただければと思います。)
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ aws comprehend detect-sentiment --language-code "ja" --text "${ARTICLE}"
{
    "Sentiment": "NEUTRAL",
    "SentimentScore": {
        "Positive": 0.007161383982747793,
        "Negative": 0.0002051049959845841,
        "Neutral": 0.9926292896270752,
        "Mixed": 4.2791070882231e-06
    }
}

S3バケット作成

S3バケット作成

コマンド
# バケット名
date_var=$(date +%Y%m%d) \
&& echo ${date_var}
S3_BUCKET_NAME="h4b-comprehend-${date_var}" \
&& echo ${S3_BUCKET_NAME}

# S3バケット作成
aws s3 mb s3://${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # バケット名
[cloudshell-user@ip-10-130-32-74 ~]$ date_var=$(date +%Y%m%d) \
> && echo ${date_var}
20241020
[cloudshell-user@ip-10-130-32-74 ~]$ S3_BUCKET_NAME="h4b-comprehend-${date_var}" \
> && echo ${S3_BUCKET_NAME}
h4b-comprehend-20241020
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 mb s3://${S3_BUCKET_NAME}
make_bucket: h4b-comprehend-20241020

アップロード

コマンド
# アップロードファイル名
UPLOAD_FILENAME="07_sample_text.txt" \
&& echo ${UPLOAD_FILENAME}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-130-32-74 ~]$ UPLOAD_FILENAME="07_sample_text.txt" \
> && echo ${UPLOAD_FILENAME}
07_sample_text.txt
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # アップロード
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 cp resources/${UPLOAD_FILENAME} s3://${S3_BUCKET_NAME}/
upload: resources/07_sample_text.txt to s3://h4b-comprehend-20241020/07_sample_text.txt

S3バケット内オブジェクト確認

コマンド
# S3バケット内オブジェクト確認 (最新のオブジェクト)
aws s3api list-object-versions \
    --bucket ${S3_BUCKET_NAME} \
    --query 'Versions | sort_by(@, &LastModified)[-1]' \
    --output json

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット内オブジェクト確認 (最新のオブジェクト)
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api list-object-versions \
>     --bucket ${S3_BUCKET_NAME} \
>     --query 'Versions | sort_by(@, &LastModified)[-1]' \
>     --output json
{
    "ETag": "\"891869bb9fb3746da8a2a954435c96c0\"",
    "Size": 991,
    "StorageClass": "STANDARD",
    "Key": "07_sample_text.txt",
    "VersionId": "null",
    "IsLatest": true,
    "LastModified": "2024-10-20T13:57:26+00:00",
    "Owner": {
        "DisplayName": "user01",
        "ID": "974cd83317461904fcbad632a42045ad8cd85cb24065c65f2ca62b7e35d84078"
    }
}

IAM

IAMポリシー

コマンド
# IAMポリシー名
IAM_POLICY_NAME="AmazonComprehendServicePolicy-h4b-comprehend" \
&& echo ${IAM_POLICY_NAME}

# ポリシードキュメントの作成
POLICY_DOCUMENT_JSON=$(cat << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::${S3_BUCKET_NAME}/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": "s3:ListBucket",
            "Resource": [
                "arn:aws:s3:::${S3_BUCKET_NAME}"
            ],
            "Effect": "Allow"
        },
        {
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::${S3_BUCKET_NAME}/*",
            "Effect": "Allow"
        }
    ]
}
EOF
) \
&& echo ${POLICY_DOCUMENT_JSON}

# JSONフォーマットの確認
echo ${POLICY_DOCUMENT_JSON} | python -m json.tool

# ポリシーの作成
aws iam create-policy \
    --policy-name ${IAM_POLICY_NAME} \
    --policy-document "${POLICY_DOCUMENT_JSON}" \
    --path /service-role/

# ARN取得
IAM_POLICY_ARN=$(
    aws iam list-policies \
        --query "Policies[?PolicyName=='${IAM_POLICY_NAME}'].Arn" \
        --output text
) \
&& echo ${IAM_POLICY_ARN}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # IAMポリシー名
[cloudshell-user@ip-10-130-32-74 ~]$ IAM_POLICY_NAME="AmazonComprehendServicePolicy-h4b-comprehend" \
> && echo ${IAM_POLICY_NAME}
AmazonComprehendServicePolicy-h4b-comprehend
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ポリシードキュメントの作成
[cloudshell-user@ip-10-130-32-74 ~]$ POLICY_DOCUMENT_JSON=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Action": "s3:GetObject",
>             "Resource": [
>                 "arn:aws:s3:::${S3_BUCKET_NAME}/*"
>             ],
>             "Effect": "Allow"
>         },
>         {
>             "Action": "s3:ListBucket",
>             "Resource": [
>                 "arn:aws:s3:::${S3_BUCKET_NAME}"
>             ],
>             "Effect": "Allow"
>         },
>         {
>             "Action": "s3:PutObject",
>             "Resource": "arn:aws:s3:::${S3_BUCKET_NAME}/*",
>             "Effect": "Allow"
>         }
>     ]
> }
> EOF
> ) \
> && echo ${POLICY_DOCUMENT_JSON}
{ "Version": "2012-10-17", "Statement": [ { "Action": "s3:GetObject", "Resource": [ "arn:aws:s3:::h4b-comprehend-20241020/*" ], "Effect": "Allow" }, { "Action": "s3:ListBucket", "Resource": [ "arn:aws:s3:::h4b-comprehend-20241020" ], "Effect": "Allow" }, { "Action": "s3:PutObject", "Resource": "arn:aws:s3:::h4b-comprehend-20241020/*", "Effect": "Allow" } ] }
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-32-74 ~]$ echo ${POLICY_DOCUMENT_JSON} | python -m json.tool
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::h4b-comprehend-20241020/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": "s3:ListBucket",
            "Resource": [
                "arn:aws:s3:::h4b-comprehend-20241020"
            ],
            "Effect": "Allow"
        },
        {
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::h4b-comprehend-20241020/*",
            "Effect": "Allow"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ポリシーの作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws iam create-policy \
>     --policy-name ${IAM_POLICY_NAME} \
>     --policy-document "${POLICY_DOCUMENT_JSON}" \
>     --path /service-role/
{
    "Policy": {
        "PolicyName": "AmazonComprehendServicePolicy-h4b-comprehend",
        "PolicyId": "ANPAWFKRCMKOYJ23SHEW7",
        "Arn": "arn:aws:iam::999999999999:policy/service-role/AmazonComprehendServicePolicy-h4b-comprehend",
        "Path": "/service-role/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2024-10-20T14:33:43+00:00",
        "UpdateDate": "2024-10-20T14:33:43+00:00"
    }
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ARN取得
[cloudshell-user@ip-10-130-32-74 ~]$ IAM_POLICY_ARN=$(
>     aws iam list-policies \
>         --query "Policies[?PolicyName=='${IAM_POLICY_NAME}'].Arn" \
>         --output text
> ) \
> && echo ${IAM_POLICY_ARN}
arn:aws:iam::999999999999:policy/service-role/AmazonComprehendServicePolicy-h4b-comprehend

IAMロール

コマンド
# 変数
IAM_ROLE_NAME="AmazonComprehendServiceRole-h4b-comprehend" \
&& echo ${IAM_ROLE_NAME}

# 信頼関係ポリシードキュメントの作成
ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "comprehend.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
EOF
) \
&& echo ${ASSUME_ROLE_POLICY_DOCUMENT}

# JSONフォーマットの確認
echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool

# IAMロールの作成
aws iam create-role \
    --role-name ${IAM_ROLE_NAME} \
    --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}" \
    --path /service-role/

# ARN取得
IAM_ROLE_ARN=$(
    aws iam get-role \
        --role-name ${IAM_ROLE_NAME} \
        --query 'Role.Arn' --output text
) \
&& echo ${IAM_ROLE_ARN}

# IAMロールにポリシーをアタッチ
aws iam attach-role-policy \
    --role-name ${IAM_ROLE_NAME} \
    --policy-arn ${IAM_POLICY_ARN}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # 変数
[cloudshell-user@ip-10-130-32-74 ~]$ IAM_ROLE_NAME="AmazonComprehendServiceRole-h4b-comprehend" \
> && echo ${IAM_ROLE_NAME}
AmazonComprehendServiceRole-h4b-comprehend
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # 信頼関係ポリシードキュメントの作成
[cloudshell-user@ip-10-130-32-74 ~]$ ASSUME_ROLE_POLICY_DOCUMENT=$(cat << EOF
> {
>     "Version": "2012-10-17",
>     "Statement": [
>         {
>             "Effect": "Allow",
>             "Principal": {
>                 "Service": "comprehend.amazonaws.com"
>             },
>             "Action": "sts:AssumeRole"
>         }
>     ]
> }
> EOF
> ) \
> && echo ${ASSUME_ROLE_POLICY_DOCUMENT}
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "comprehend.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-32-74 ~]$ echo ${ASSUME_ROLE_POLICY_DOCUMENT} | python -m json.tool
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "comprehend.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # IAMロールの作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws iam create-role \
>     --role-name ${IAM_ROLE_NAME} \
>     --assume-role-policy-document "${ASSUME_ROLE_POLICY_DOCUMENT}" \
>     --path /service-role/
{
    "Role": {
        "Path": "/service-role/",
        "RoleName": "AmazonComprehendServiceRole-h4b-comprehend",
        "RoleId": "AROAWFKRCMKOZ67FLJ5QM",
        "Arn": "arn:aws:iam::999999999999:role/service-role/AmazonComprehendServiceRole-h4b-comprehend",
        "CreateDate": "2024-10-20T14:34:12+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "comprehend.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ARN取得
[cloudshell-user@ip-10-130-32-74 ~]$ IAM_ROLE_ARN=$(
>     aws iam get-role \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'Role.Arn' --output text
> ) \
> && echo ${IAM_ROLE_ARN}
arn:aws:iam::999999999999:role/service-role/AmazonComprehendServiceRole-h4b-comprehend
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # IAMロールにポリシーをアタッチ
[cloudshell-user@ip-10-130-32-74 ~]$ aws iam attach-role-policy \
>     --role-name ${IAM_ROLE_NAME} \
>     --policy-arn ${IAM_POLICY_ARN}

Analysis jobs

ジョブ作成

コマンド
# ジョブ名
JOB_NAME="h4b-comprehend-job" \
&& echo ${JOB_NAME}

# 入力フォーマット
INPUTFORMAT="ONE_DOC_PER_LINE" \
&& echo ${INPUTFORMAT}

# 言語
LANGUAGE_CODE="ja" \
&& echo ${LANGUAGE_CODE}

ACCOUNT_ID="999999999999" \
&& echo ${ACCOUNT_ID}

# ジョブ作成
aws comprehend start-sentiment-detection-job \
    --job-name ${JOB_NAME} \
    --input-data-config S3Uri=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME},InputFormat=${INPUTFORMAT} \
    --output-data-config S3Uri=s3://${S3_BUCKET_NAME}/ \
    --data-access-role-arn ${IAM_ROLE_ARN} \
    --language-code ${LANGUAGE_CODE}
    
# ID取得
JOB_ID=$(
aws comprehend list-sentiment-detection-jobs \
    --query "SentimentDetectionJobPropertiesList[?JobName=='${JOB_NAME}'].JobId" \
    --output text
) \
&& echo ${JOB_ID}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # ジョブ名
[cloudshell-user@ip-10-130-32-74 ~]$ JOB_NAME="h4b-comprehend-job" \
> && echo ${JOB_NAME}
h4b-comprehend-job
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # 入力フォーマット
[cloudshell-user@ip-10-130-32-74 ~]$ INPUTFORMAT="ONE_DOC_PER_LINE" \
> && echo ${INPUTFORMAT}
ONE_DOC_PER_LINE
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # 言語
[cloudshell-user@ip-10-130-32-74 ~]$ LANGUAGE_CODE="ja" \
> && echo ${LANGUAGE_CODE}
ja
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ジョブ作成
[cloudshell-user@ip-10-130-32-74 ~]$ aws comprehend start-sentiment-detection-job \
>     --job-name ${JOB_NAME} \
>     --input-data-config S3Uri=s3://${S3_BUCKET_NAME}/${UPLOAD_FILENAME},InputFormat=${INPUTFORMAT} \
>     --output-data-config S3Uri=s3://${S3_BUCKET_NAME}/ \
>     --data-access-role-arn ${IAM_ROLE_ARN} \
>     --language-code ${LANGUAGE_CODE}
{
    "JobId": "b9bae54473760e251d22689aa3614f69",
    "JobArn": "arn:aws:comprehend:ap-northeast-1:999999999999:sentiment-detection-job/b9bae54473760e251d22689aa3614f69",
    "JobStatus": "SUBMITTED"
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # ID取得
[cloudshell-user@ip-10-130-32-74 ~]$ JOB_ID=$(
> aws comprehend list-sentiment-detection-jobs \
>     --query "SentimentDetectionJobPropertiesList[?JobName=='${JOB_NAME}'].JobId" \
>     --output text
> ) \
> && echo ${JOB_ID}
b9bae54473760e251d22689aa3614f69

確認

コマンド
# 確認
aws comprehend describe-sentiment-detection-job --job-id ${JOB_ID}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # 確認
[cloudshell-user@ip-10-130-32-74 ~]$ aws comprehend describe-sentiment-detection-job --job-id ${JOB_ID}
{
    "SentimentDetectionJobProperties": {
        "JobId": "b9bae54473760e251d22689aa3614f69",
        "JobArn": "arn:aws:comprehend:ap-northeast-1:999999999999:sentiment-detection-job/b9bae54473760e251d22689aa3614f69",
        "JobName": "h4b-comprehend-job",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2024-10-20T23:43:06.354000+09:00",
        "EndTime": "2024-10-20T23:49:14.875000+09:00",
        "InputDataConfig": {
            "S3Uri": "s3://h4b-comprehend-20241020/07_sample_text.txt",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://h4b-comprehend-20241020/999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz"
        },
        "LanguageCode": "ja",
        "DataAccessRoleArn": "arn:aws:iam::999999999999:role/service-role/AmazonComprehendServiceRole-h4b-comprehend"
    }
}

出力確認

S3バケット内のオブジェクトを確認

コマンド
# S3バケット内オブジェクト確認 (最新のオブジェクト)
S3_OBJECT_NAME=$(
aws s3api list-objects-v2 \
    --bucket ${S3_BUCKET_NAME} \
    --query "Contents|sort_by(@, &LastModified)[-1].Key" \
    --output text
) \
&& echo ${S3_OBJECT_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケット内オブジェクト確認 (最新のオブジェクト)
[cloudshell-user@ip-10-130-32-74 ~]$ S3_OBJECT_NAME=$(
> aws s3api list-objects-v2 \
>     --bucket ${S3_BUCKET_NAME} \
>     --query "Contents|sort_by(@, &LastModified)[-1].Key" \
>     --output text
> ) \
> && echo ${S3_OBJECT_NAME}
999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz

S3からファイルをダウンロード

コマンド
# ダウンロード
aws s3 cp s3://${S3_BUCKET_NAME}/${S3_OBJECT_NAME} ./

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # ダウンロード
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3 cp s3://${S3_BUCKET_NAME}/${S3_OBJECT_NAME} ./
download: s3://h4b-comprehend-20241020/999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz to ./output.tar.gz

ダウンロードしたファイルを確認

コマンド
tar -xzf output.tar.gz -O

出力
[cloudshell-user@ip-10-130-32-74 ~]$ tar -xzf output.tar.gz -O
tar: Ignoring unknown extended header keyword 'LIBARCHIVE.creationtime'
{"File": "07_sample_text.txt", "Line": 1, "Sentiment": "NEUTRAL", "SentimentScore": {"Mixed": 8.50432479637675e-05, "Negative": 0.00017361136269755661, "Neutral": 0.730780303478241, "Positive": 0.2689610719680786}}
{"File": "07_sample_text.txt", "Line": 0, "Sentiment": "NEUTRAL", "SentimentScore": {"Mixed": 4.279090717318468e-06, "Negative": 0.00020510460308287293, "Neutral": 0.9926292896270752, "Positive": 0.0071613602340221405}}

削除

S3

コマンド
# オブジェクト一覧取得
OBJECT_LIST=$(
    aws s3api list-object-versions \
        --bucket ${S3_BUCKET_NAME} \
        --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
) \
&& echo ${OBJECT_LIST}

# JSONフォーマットの確認
echo ${OBJECT_LIST} | python -m json.tool

# バケットを空にする
aws s3api delete-objects \
    --bucket ${S3_BUCKET_NAME} \
    --delete "${OBJECT_LIST}"

# S3バケットを削除
aws s3api delete-bucket \
    --bucket ${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # オブジェクト一覧取得
[cloudshell-user@ip-10-130-32-74 ~]$ OBJECT_LIST=$(
>     aws s3api list-object-versions \
>         --bucket ${S3_BUCKET_NAME} \
>         --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
> ) \
> && echo ${OBJECT_LIST}
{ "Objects": [ { "Key": ".write_access_check_file.temp", "VersionId": "null" }, { "Key": "07_sample_text.txt", "VersionId": "null" }, { "Key": "999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz", "VersionId": "null" } ] }
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-130-32-74 ~]$ echo ${OBJECT_LIST} | python -m json.tool
{
    "Objects": [
        {
            "Key": ".write_access_check_file.temp",
            "VersionId": "null"
        },
        {
            "Key": "07_sample_text.txt",
            "VersionId": "null"
        },
        {
            "Key": "999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # バケットを空にする
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api delete-objects \
>     --bucket ${S3_BUCKET_NAME} \
>     --delete "${OBJECT_LIST}"
{
    "Deleted": [
        {
            "Key": "999999999999-SENTIMENT-b9bae54473760e251d22689aa3614f69/output/output.tar.gz",
            "VersionId": "null"
        },
        {
            "Key": "07_sample_text.txt",
            "VersionId": "null"
        },
        {
            "Key": ".write_access_check_file.temp",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # S3バケットを削除
[cloudshell-user@ip-10-130-32-74 ~]$ aws s3api delete-bucket \
>     --bucket ${S3_BUCKET_NAME}

IAM

コマンド
# ロールにアタッチされているポリシーをリスト
POLICIES=$(
    aws iam list-attached-role-policies \
        --role-name ${IAM_ROLE_NAME} \
        --query 'AttachedPolicies[*].PolicyArn' \
        --output text
) \
&& echo ${POLICIES}

# リスト内のポリシーをデタッチする
for POLICY in ${POLICIES}; do
    aws iam detach-role-policy \
        --role-name ${IAM_ROLE_NAME} \
        --policy-arn ${POLICY}
done

# IAMロールの削除
aws iam delete-role \
    --role-name ${IAM_ROLE_NAME}

# IAMポリシーの削除
aws iam delete-policy \
    --policy-arn ${IAM_POLICY_ARN}

出力
[cloudshell-user@ip-10-130-32-74 ~]$ # ロールにアタッチされているポリシーをリスト
[cloudshell-user@ip-10-130-32-74 ~]$ POLICIES=$(
>     aws iam list-attached-role-policies \
>         --role-name ${IAM_ROLE_NAME} \
>         --query 'AttachedPolicies[*].PolicyArn' \
>         --output text
> ) \
> && echo ${POLICIES}
arn:aws:iam::999999999999:policy/service-role/AmazonComprehendServicePolicy-h4b-comprehend
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # リスト内のポリシーをデタッチする
[cloudshell-user@ip-10-130-32-74 ~]$ for POLICY in ${POLICIES}; do
>     aws iam detach-role-policy \
>         --role-name ${IAM_ROLE_NAME} \
>         --policy-arn ${POLICY}
> done
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # IAMロールの削除
[cloudshell-user@ip-10-130-32-74 ~]$ aws iam delete-role \
>     --role-name ${IAM_ROLE_NAME}
[cloudshell-user@ip-10-130-32-74 ~]$ 
[cloudshell-user@ip-10-130-32-74 ~]$ # IAMポリシーの削除
[cloudshell-user@ip-10-130-32-74 ~]$ aws iam delete-policy \
>     --policy-arn ${IAM_POLICY_ARN}

08 Amazon Rekognition を用いて画像・動画分析を行う

S3バケット作成

S3バケット作成

コマンド
# バケット名
date_var=$(date +%Y%m%d) \
&& echo ${date_var}
S3_BUCKET_NAME="h4b-rekognition-${date_var}" \
&& echo ${S3_BUCKET_NAME}

# S3バケット作成
aws s3 mb s3://${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # バケット名
[cloudshell-user@ip-10-132-68-209 ~]$ date_var=$(date +%Y%m%d) \
> && echo ${date_var}
20241021
[cloudshell-user@ip-10-132-68-209 ~]$ S3_BUCKET_NAME="h4b-rekognition-${date_var}" \
> && echo ${S3_BUCKET_NAME}
h4b-rekognition-20241021
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # S3バケット作成
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3 mb s3://${S3_BUCKET_NAME}
make_bucket: h4b-rekognition-20241021

アップロード

コマンド
# アップロードファイル名
UPLOAD_FILENAME_1="08_kanazawa32.png" \
&& echo ${UPLOAD_FILENAME_1}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME_1} s3://${S3_BUCKET_NAME}/

# アップロードファイル名
UPLOAD_FILENAME_2="08_kanazawa10.JPG" \
&& echo ${UPLOAD_FILENAME_2}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME_2} s3://${S3_BUCKET_NAME}/

# アップロードファイル名
UPLOAD_FILENAME_3="08_sample_movie.mp4" \
&& echo ${UPLOAD_FILENAME_3}

# アップロード
aws s3 cp resources/${UPLOAD_FILENAME_3} s3://${S3_BUCKET_NAME}/

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-132-68-209 ~]$ UPLOAD_FILENAME_1="08_kanazawa32.png" \
> && echo ${UPLOAD_FILENAME_1}
08_kanazawa32.png
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロード
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3 cp resources/${UPLOAD_FILENAME_1} s3://${S3_BUCKET_NAME}/
upload: resources/08_kanazawa32.png to s3://h4b-rekognition-20241021/08_kanazawa32.png
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-132-68-209 ~]$ UPLOAD_FILENAME_2="08_kanazawa10.JPG" \
> && echo ${UPLOAD_FILENAME_2}
08_kanazawa10.JPG
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロード
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3 cp resources/${UPLOAD_FILENAME_2} s3://${S3_BUCKET_NAME}/
upload: resources/08_kanazawa10.JPG to s3://h4b-rekognition-20241021/08_kanazawa10.JPG
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロードファイル名
[cloudshell-user@ip-10-132-68-209 ~]$ UPLOAD_FILENAME_3="08_sample_movie.mp4" \
> && echo ${UPLOAD_FILENAME_3}
08_sample_movie.mp4
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # アップロード
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3 cp resources/${UPLOAD_FILENAME_3} s3://${S3_BUCKET_NAME}/
upload: resources/08_sample_movie.mp4 to s3://h4b-rekognition-20241021/08_sample_movie.mp4

S3バケット内オブジェクト確認

コマンド
# S3バケット内オブジェクト確認 (最新3つのオブジェクト)
aws s3api list-objects-v2 \
    --bucket ${S3_BUCKET_NAME} \
    --query 'reverse(sort_by(Contents, &LastModified))[:3].{Key: Key, LastModified: LastModified}'

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # S3バケット内オブジェクト確認 (最新3つのオブジェクト)
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3api list-objects-v2 \
>     --bucket ${S3_BUCKET_NAME} \
>     --query 'reverse(sort_by(Contents, &LastModified))[:3].{Key: Key, LastModified: LastModified}'
[
    {
        "Key": "08_sample_movie.mp4",
        "LastModified": "2024-10-21T14:57:30+00:00"
    },
    {
        "Key": "08_kanazawa10.JPG",
        "LastModified": "2024-10-21T14:41:31+00:00"
    },
    {
        "Key": "08_kanazawa32.png",
        "LastModified": "2024-10-21T14:41:30+00:00"
    }
]

Amazon Rekognition

ラベル検出

コマンド
# ラベル検出
aws rekognition detect-labels \
    --image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_1}}" \
    --no-cli-pager \
    > detect-lables_result.log

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # ラベル検出
[cloudshell-user@ip-10-132-68-209 ~]$ aws rekognition detect-labels \
>     --image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_1}}" \
>     --no-cli-pager \
>     > detect-lables_result.log

顔の比較

コマンド
# 顔の比較
aws rekognition compare-faces \
    --source-image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_1}}" \
    --target-image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_2}}" \
    --no-cli-pager \
    > compare-faces_result.log

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # 顔の比較
[cloudshell-user@ip-10-132-68-209 ~]$ aws rekognition compare-faces \
>     --source-image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_1}}" \
>     --target-image "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_2}}" \
>     --no-cli-pager \
>     > compare-faces_result.log

保存済み動画分析

コマンド
# 保存済み動画分析
aws rekognition start-label-detection \
    --video "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_3}}" \
    --no-cli-pager

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # 保存済み動画分析
[cloudshell-user@ip-10-132-68-209 ~]$ aws rekognition start-label-detection \
>     --video "S3Object={Bucket=${S3_BUCKET_NAME},Name=${UPLOAD_FILENAME_3}}" \
>     --no-cli-pager
{
    "JobId": "8f8870949ff3fe112974f66696a7d96635f205cafd2dee032afb98722738ec52"
}

分析結果取得

コマンド
aws rekognition get-label-detection \
    --job-id "8f8870949ff3fe112974f66696a7d96635f205cafd2dee032afb98722738ec52" \
    > vide_analysis_result.log

出力
[cloudshell-user@ip-10-132-68-209 ~]$ aws rekognition get-label-detection \
>     --job-id "8f8870949ff3fe112974f66696a7d96635f205cafd2dee032afb98722738ec52" \
>     > vide_analysis_result.log

削除

S3

コマンド
# オブジェクト一覧取得
OBJECT_LIST=$(
    aws s3api list-object-versions \
        --bucket ${S3_BUCKET_NAME} \
        --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
) \
&& echo ${OBJECT_LIST}

# JSONフォーマットの確認
echo ${OBJECT_LIST} | python -m json.tool

# バケットを空にする
aws s3api delete-objects \
    --bucket ${S3_BUCKET_NAME} \
    --delete "${OBJECT_LIST}"

# S3バケットを削除
aws s3api delete-bucket \
    --bucket ${S3_BUCKET_NAME}

出力
[cloudshell-user@ip-10-132-68-209 ~]$ # オブジェクト一覧取得
[cloudshell-user@ip-10-132-68-209 ~]$ OBJECT_LIST=$(
>     aws s3api list-object-versions \
>         --bucket ${S3_BUCKET_NAME} \
>         --query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}'
> ) \
> && echo ${OBJECT_LIST}
{ "Objects": [ { "Key": "08_kanazawa10.JPG", "VersionId": "null" }, { "Key": "08_kanazawa32.png", "VersionId": "null" }, { "Key": "08_sample_movie.mp4", "VersionId": "null" } ] }
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # JSONフォーマットの確認
[cloudshell-user@ip-10-132-68-209 ~]$ echo ${OBJECT_LIST} | python -m json.tool
{
    "Objects": [
        {
            "Key": "08_kanazawa10.JPG",
            "VersionId": "null"
        },
        {
            "Key": "08_kanazawa32.png",
            "VersionId": "null"
        },
        {
            "Key": "08_sample_movie.mp4",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # バケットを空にする
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3api delete-objects \
>     --bucket ${S3_BUCKET_NAME} \
>     --delete "${OBJECT_LIST}"
{
    "Deleted": [
        {
            "Key": "08_kanazawa32.png",
            "VersionId": "null"
        },
        {
            "Key": "08_sample_movie.mp4",
            "VersionId": "null"
        },
        {
            "Key": "08_kanazawa10.JPG",
            "VersionId": "null"
        }
    ]
}
[cloudshell-user@ip-10-132-68-209 ~]$ 
[cloudshell-user@ip-10-132-68-209 ~]$ # S3バケットを削除
[cloudshell-user@ip-10-132-68-209 ~]$ aws s3api delete-bucket \
>     --bucket ${S3_BUCKET_NAME}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?