Python (boto3) を用いたAWS利用のためのセットアップとS3・AIサービスの活用

本記事では、PythonのAWS SDKである boto3 を用いてAWSサービスを利用するための基本的なセットアップ手順と、S3(Simple Storage Service)およびいくつかのAIサービスの簡単な利用例を解説します。

1. AWSアカウントのセットアップ

AWSサービスを利用するには、まずAWSアカウントが必要です。

  1. AWSアカウントの作成: AWS公式サイト にアクセスし、アカウントを作成します。クレジットカード情報の登録が必要ですが、無料利用枠があります。

  2. IAMユーザーの作成と権限設定: セキュリティのベストプラクティスとして、rootユーザーではなく、IAM(Identity and Access Management)ユーザーを作成し、そのユーザーでAWSサービスを操作することを強く推奨します。

    • AWSマネジメントコンソールにログインし、IAMダッシュボードに移動します。
    • 「ユーザーグループ」を作成します(例: administrators)。このグループに、必要な権限を持つポリシー(例: AdministratorAccess)をアタッチします。
    • 「ユーザー」を作成し、作成したユーザーグループに追加します。
    • ユーザー作成時に発行されるアクセスキーIDシークレットアクセスキーをメモしておきます。シークレットアクセスキーは、この時しか表示されないため、必ず安全な場所に保管してください。

2. Python環境のセットアップ

AWSサービスをPythonから操作するために、AWS CLIと boto3 をインストールします。

  1. AWS CLIのインストール: AWS CLI(Command Line Interface)は、コマンドラインからAWSサービスを操作するためのツールです。boto3 の設定にも利用できます。

    pip install awscli
    
  2. AWS認証情報の設定: aws configure コマンドを実行し、IAMユーザー作成時にメモしたアクセスキーIDとシークレットアクセスキーを設定します。

    aws configure
    

    プロンプトに従って情報を入力します。

    AWS Access Key ID [None]: YOUR_ACCESS_KEY_ID
    AWS Secret Access Key [None]: YOUR_SECRET_ACCESS_KEY
    Default region name [None]: ap-northeast-1 # 利用するAWSリージョン (例: 東京リージョン)
    Default output format [None]: json # 出力形式
    

    設定されたアクセスキーは、次のコマンドで確認できます。

    aws configure get aws_access_key_id
    aws configure get aws_secret_access_key
    
  3. Boto3のインストール: boto3 は、PythonからAWSサービスを操作するためのSDK(Software Development Kit)です。

    pip install boto3
    

3. S3 (Simple Storage Service) の利用例

S3は、スケーラブルで耐久性の高いオブジェクトストレージサービスです。

import boto3
import random

# S3クライアントの初期化
# region_nameはaws configureで設定したリージョンと合わせる
s3 = boto3.client("s3", region_name="ap-northeast-1")

# バケット名の生成 (S3のバケット名はグローバルで一意である必要がある)
bucket_name = "my-unique-test-bucket-" + str(random.randint(0, 10**5))

try:
    # バケットの作成
    # LocationConstraintはリージョンを指定。us-east-1 (バージニア北部) の場合は不要
    s3.create_bucket(
        Bucket=bucket_name,
        CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'}
    )
    print(f"バケット '{bucket_name}' を作成しました。")

    # 作成されたバケットの確認
    response = s3.list_buckets()
    print("既存のバケット:")
    for bucket in response['Buckets']:
        print(f"  - {bucket['Name']}")

finally:
    # バケットの削除 (空でないと削除できないため、通常はオブジェクトを先に削除する必要がある)
    # 例: s3.delete_object(Bucket=bucket_name, Key='your_object_key')
    # s3.delete_bucket(Bucket=bucket_name)
    # print(f"バケット '{bucket_name}' を削除しました。")
    pass # この例では削除処理をコメントアウト

4. AWS AIサービスの利用例

AWSは、機械学習の専門知識がなくても利用できる様々なAIサービスを提供しています。

1. Amazon Translate (テキスト翻訳)

import boto3

translate = boto3.client("translate", region_name="ap-northeast-1") # リージョンを指定

text_to_translate = "こんにちは、元気ですか?"
result = translate.translate_text(
    Text=text_to_translate,
    SourceLanguageCode="ja",
    TargetLanguageCode="en"
)
print(f"翻訳前: {text_to_translate}")
print(f"翻訳後: {result['TranslatedText']}")
# 出力例: 翻訳後: Hello, how are you?

2. Amazon Polly (テキスト読み上げ)

import boto3
import contextlib
import os

polly = boto3.client("polly", region_name="ap-northeast-1") # リージョンを指定

text_to_synthesize = "お元気ですか?"
output_file_path = "polly_synth.mp3"

response = polly.synthesize_speech(
    Text=text_to_synthesize,
    OutputFormat="mp3",
    VoiceId="Mizuki" # 日本語の女性の声
)

# 音声ストリームをファイルに保存
if "AudioStream" in response:
    with contextlib.closing(response["AudioStream"]) as stream:
        with open(output_file_path, "wb") as file:
            file.write(stream.read())
    print(f"音声を '{output_file_path}' に保存しました。")

    # 保存した音声ファイルを再生 (OSによってコマンドが異なる)
    # Windowsの場合: os.startfile(output_file_path)
    # macOSの場合: os.system(f"afplay {output_file_path}")
    # Linuxの場合: os.system(f"mpg123 {output_file_path}") # mpg123のインストールが必要
else:
    print("音声ストリームが取得できませんでした。")

3. Amazon Comprehend (自然言語処理)

import boto3
import json

# Comprehendは一部のリージョンでしか利用できない場合があるため、us-east-1を指定
comprehend = boto3.client("comprehend", region_name="us-east-1") 

text_to_analyze = "I'm looking forward to visiting Japan next summer. It will be a great trip!"

# 文字列の言語を検出
response_lang = comprehend.detect_dominant_language(Text=text_to_analyze)
print(f"検出された言語: {response_lang['Languages'][0]['LanguageCode']}")
# 出力例: 検出された言語: en

# 文字列の感情を分析
response_sentiment = comprehend.detect_sentiment(Text=text_to_analyze, LanguageCode="en")
print(f"感情分析結果: {response_sentiment['Sentiment']}")
print(f"感情スコア: {json.dumps(response_sentiment['SentimentScore'], indent=2)}")
# 出力例: 感情分析結果: POSITIVE

# 文字列の構文を解析
response_syntax = comprehend.detect_syntax(Text=text_to_analyze, LanguageCode="en")
print("構文解析結果 (一部):")
for token in response_syntax['SyntaxTokens'][:5]: # 最初の5トークンのみ表示
    print(f"  Text: {token['Text']}, PartOfSpeech: {token['PartOfSpeech']['Tag']}")
# 出力例:
#   Text: I'm, PartOfSpeech: PRON
#   Text: looking, PartOfSpeech: VERB
#   Text: forward, PartOfSpeech: ADV
#   Text: to, PartOfSpeech: PART
#   Text: visiting, PartOfSpeech: VERB

参考