This article explains the basic setup procedures for using AWS services with boto3, the AWS SDK for Python, along with simple usage examples of S3 (Simple Storage Service) and several AI services.
1. AWS Account Setup
To use AWS services, you first need an AWS account.
Create an AWS Account: Visit the AWS official site and create an account. Credit card registration is required, but a free tier is available.
Create an IAM User and Configure Permissions: As a security best practice, it is strongly recommended to create an IAM (Identity and Access Management) user rather than using the root user to operate AWS services.
- Log in to the AWS Management Console and navigate to the IAM dashboard.
- Create a “User Group” (e.g.,
administrators). Attach a policy with the necessary permissions (e.g.,AdministratorAccess) to this group. - Create a “User” and add them to the created user group.
- Note the Access Key ID and Secret Access Key generated when creating the user. The Secret Access Key is only displayed at this time, so be sure to store it in a safe location.
2. Python Environment Setup
Install the AWS CLI and boto3 to operate AWS services from Python.
Install the AWS CLI: The AWS CLI (Command Line Interface) is a tool for operating AWS services from the command line. It can also be used to configure
boto3settings.pip install awscliConfigure AWS Credentials: Run the
aws configurecommand and enter the Access Key ID and Secret Access Key noted when creating the IAM user.aws configureEnter the information as prompted.
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 region to use (e.g., Tokyo region) Default output format [None]: json # Output formatThe configured access keys can be verified with the following commands.
aws configure get aws_access_key_id aws configure get aws_secret_access_keyInstall Boto3:
boto3is the SDK (Software Development Kit) for operating AWS services from Python.pip install boto3
3. S3 (Simple Storage Service) Usage Example
S3 is a scalable and highly durable object storage service.
import boto3
import random
# Initialize S3 client
# Match region_name with the region set in aws configure
s3 = boto3.client("s3", region_name="ap-northeast-1")
# Generate bucket name (S3 bucket names must be globally unique)
bucket_name = "my-unique-test-bucket-" + str(random.randint(0, 10**5))
try:
# Create bucket
# LocationConstraint specifies the region. Not needed for us-east-1 (N. Virginia)
s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': 'ap-northeast-1'}
)
print(f"Bucket '{bucket_name}' created.")
# Verify created bucket
response = s3.list_buckets()
print("Existing buckets:")
for bucket in response['Buckets']:
print(f" - {bucket['Name']}")
finally:
# Delete bucket (must be empty before deletion; typically objects need to be deleted first)
# Example: s3.delete_object(Bucket=bucket_name, Key='your_object_key')
# s3.delete_bucket(Bucket=bucket_name)
# print(f"Bucket '{bucket_name}' deleted.")
pass # Deletion is commented out in this example
4. AWS AI Services Usage Examples
AWS provides various AI services that can be used without machine learning expertise.
1. Amazon Translate (Text Translation)
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"Before: {text_to_translate}")
print(f"After: {result['TranslatedText']}")
# Example output: After: Hello, how are you?
2. Amazon Polly (Text-to-Speech)
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" # Japanese female voice
)
# Save the audio stream to a file
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"Audio saved to '{output_file_path}'.")
# Play the saved audio file (command varies by OS)
# Windows: os.startfile(output_file_path)
# macOS: os.system(f"afplay {output_file_path}")
# Linux: os.system(f"mpg123 {output_file_path}") # Requires mpg123
else:
print("Could not retrieve audio stream.")
3. Amazon Comprehend (Natural Language Processing)
import boto3
import json
# Comprehend may only be available in certain regions; using 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!"
# Detect language
response_lang = comprehend.detect_dominant_language(Text=text_to_analyze)
print(f"Detected language: {response_lang['Languages'][0]['LanguageCode']}")
# Example output: Detected language: en
# Analyze sentiment
response_sentiment = comprehend.detect_sentiment(Text=text_to_analyze, LanguageCode="en")
print(f"Sentiment: {response_sentiment['Sentiment']}")
print(f"Sentiment scores: {json.dumps(response_sentiment['SentimentScore'], indent=2)}")
# Example output: Sentiment: POSITIVE
# Analyze syntax
response_syntax = comprehend.detect_syntax(Text=text_to_analyze, LanguageCode="en")
print("Syntax analysis (partial):")
for token in response_syntax['SyntaxTokens'][:5]:
print(f" Text: {token['Text']}, PartOfSpeech: {token['PartOfSpeech']['Tag']}")
References
- Kenichiro Matsuura & Yuki Tsukasa, “AI Programming Introduction with AWS”, Shoeisha (2020)
- Tomoyuki Mano, “Introduction to Cloud with AWS” (Online Book)