Skip to content

Commit b2b9dde

Browse files
authored
Merge pull request #1577 from sudheery80/sudheery80-apigw-lambda-translate-polly-s3
new pattern changes - apigw-lambda-translate-polly-s3
2 parents c1c585c + 6fd498f commit b2b9dde

File tree

5 files changed

+287
-0
lines changed

5 files changed

+287
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Amazon API Gateway REST API to AWS Lambda which calls AWS Translate and Polly services
2+
3+
This pattern creates an Amazon API Gateway REST API and an AWS Lambda function that calls AWS Translate and Polly services and saves the audio file to S3.
4+
5+
Learn more about this pattern at: https://serverlessland.com/patterns/apigw-lambda-translate-polly-s3.
6+
7+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
8+
9+
## Requirements
10+
11+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
12+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
13+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
14+
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
15+
* [AWS Translate](https://aws.amazon.com/translate/)
16+
* [AWS Translate Languages](https://docs.aws.amazon.com/translate/latest/dg/pairs.html)
17+
* [AWS Polly](https://aws.amazon.com/polly/)
18+
* [AWS S3](https://aws.amazon.com/s3/)
19+
20+
## Deployment Instructions
21+
22+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
23+
```
24+
git clone https://github.com/aws-samples/serverless-patterns
25+
```
26+
2. Change directory to the pattern directory:
27+
```
28+
cd apigw-lambda-translate-polly-s3
29+
```
30+
3. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
31+
```
32+
sam deploy --guided
33+
```
34+
4. During the prompts:
35+
* Enter a stack name
36+
* Enter the desired AWS Region
37+
* Enter the S3 bucket to store the audio file
38+
39+
Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.
40+
41+
5. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs that were created.
42+
43+
## How it works
44+
45+
This pattern deploys an Amazon API Gateway REST API and a default route integrated with an AWS LAMBDA function written in Python. The lambda function calls AWS Translate service using the text and language given in the request and then calls AWS Polly service to convert the translated text into speech which is saved as a audio file in S3. The API response will have the translated text and audio file location or error response if the language code is not supported.
46+
47+
## Testing
48+
49+
Once the application is deployed, either use a curl or call the endpoint from Postman.
50+
51+
Example POST Request to translate text to Spanish:
52+
```
53+
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"es"}'
54+
```
55+
56+
Response:
57+
```
58+
"{"TranslatedText": "Hola, esto es sin servidor", "AudioFile": "s3://{yourS3bucketname}/1692129677356.mp3"}"
59+
```
60+
61+
Example POST Request to translate text to Afrikaans:
62+
```
63+
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"af"}'
64+
```
65+
66+
Response:
67+
```
68+
"{"TranslatedText": "Hallo dit is bedienerloos", "AudioFile": "s3://{yourS3bucketname}/1692129833975.mp3"}"
69+
```
70+
71+
Example POST Request with unsupported language:
72+
```
73+
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"ef"}'
74+
```
75+
76+
Response:
77+
```
78+
"An error occurred (UnsupportedLanguagePairException) when calling the TranslateText operation: Unsupported language pair: en to ef. Target language 'ef' is not supported"
79+
```
80+
81+
## Documentation
82+
- [Working with REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html)
83+
- [Working with AWS Lambda proxy integrations for REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html)
84+
- [AWS Lambda - the Basics](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/aws-lambdathe-basics.html)
85+
- [Lambda Function Handler](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-handler.html)
86+
- [Function Environment Variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)
87+
88+
## Cleanup
89+
90+
Please empty the S3 bucket to delete the audio files before running "sam delete".
91+
92+
1. Delete the stack
93+
```bash
94+
sam delete
95+
```
96+
97+
This pattern was contributed by Sudheer Yalamanchili.
98+
99+
----
100+
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
101+
102+
SPDX-License-Identifier: MIT-0
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
{
2+
"title": "Amazon API Gateway REST API to AWS Lambda which calls AWS Translate and Polly services",
3+
"description": "This pattern creates an Amazon API Gateway REST API and an AWS Lambda function that calls AWS Translate and Polly services and saves the audio file to S3.",
4+
"language": "Python",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"API Gateway REST API is integrated to AWS Lambda function which calls AWS Translate and Polly services"
11+
]
12+
},
13+
"gitHub": {
14+
"template": {
15+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-translate-polly-s3",
16+
"templateURL": "serverless-patterns/apigw-lambda-translate-polly-s3",
17+
"projectFolder": "apigw-lambda-translate-polly-s3",
18+
"templateFile": "template.yaml"
19+
}
20+
},
21+
"resources": {
22+
"bullets": [
23+
{
24+
"text": "AWS Serverless Application Model",
25+
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html"
26+
},
27+
{
28+
"text": "AWS Translate",
29+
"link": "https://aws.amazon.com/translate/"
30+
},
31+
{
32+
"text": "AWS Translate Languages",
33+
"link": "https://docs.aws.amazon.com/translate/latest/dg/pairs.html"
34+
},
35+
{
36+
"text": "AWS Polly",
37+
"link": "https://aws.amazon.com/polly/"
38+
},
39+
{
40+
"text": "AWS S3",
41+
"link": "https://aws.amazon.com/s3/"
42+
}
43+
]
44+
},
45+
"deploy": {
46+
"text": [
47+
"sam deploy --guided" ]
48+
},
49+
"testing": {
50+
"text": ["See the GitHub repo for detailed testing instructions."]
51+
},
52+
"cleanup": {
53+
"text": [
54+
"Delete the stack: <code>sam delete</code>."
55+
]
56+
},
57+
"authors": [
58+
{
59+
"name": "Sudheer Yalamanchili",
60+
"image": "./sudheer.jpg",
61+
"bio": "Sudheer is a Cloud Application Architect at AWS ProServ.",
62+
"linkedin": "sudheeryalamanchili"
63+
}
64+
]
65+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: MIT-0
3+
4+
import json
5+
import boto3
6+
import os
7+
from contextlib import closing
8+
9+
# Get the aws translate client
10+
translate_client = boto3.client('translate')
11+
# Get the aws s3 client
12+
s3_client = boto3.client("s3")
13+
# Get the aws polly client
14+
polly_client = boto3.client("polly")
15+
16+
def lambda_handler(event, context):
17+
# Fetch the message body and request timestamp from the request event
18+
req_body = json.loads(event['body'])
19+
timestamp = event['requestContext']['requestTimeEpoch']
20+
bucket_name = os.environ['S3_BUCKET_NAME']
21+
22+
try:
23+
# Call translate_text API with the text and language given in the request body
24+
translate_response = translate_client.translate_text(
25+
Text=req_body["OriginalText"],
26+
SourceLanguageCode='auto',
27+
TargetLanguageCode=req_body["TranslateToLanguage"]
28+
)
29+
print(req_body)
30+
31+
# Get the translated text from the response
32+
response_text = translate_response['TranslatedText']
33+
34+
# Call the Polly API to convert translated text to speech
35+
response = polly_client.synthesize_speech(Text=response_text, OutputFormat="mp3", VoiceId="Lucia")
36+
37+
# Get the audio file from the response
38+
audio_file = response["AudioStream"]
39+
40+
# Create s3 filename using request timestamp
41+
audio_file_name = str(timestamp) + ".mp3"
42+
print(audio_file_name)
43+
44+
# Save the audio file to the s3 bucket that was created during stack creation
45+
with closing(audio_file) as stream:
46+
s3_client.put_object(Key=audio_file_name, Body=stream.read(), Bucket=bucket_name)
47+
48+
# create response object
49+
response_json = {
50+
"TranslatedText": response_text,
51+
"AudioFile": "s3://" + bucket_name + "/" + audio_file_name
52+
}
53+
54+
except Exception as errormessage:
55+
# Get the error messages if translation fails
56+
response_json = str(errormessage)
57+
58+
# return translated text or error response if translation fails
59+
return {
60+
'statusCode': 200,
61+
'body': json.dumps(response_json)
62+
}
349 KB
Loading
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: An Amazon REST API gateway integrated with a AWS Lambda function that calls AWS Translate service to translate given text, then call AWS Polly service to convert the text into speech and save audio file to s3.
4+
5+
Parameters:
6+
s3BucketName:
7+
Type: String
8+
Description: s3 bucket to save audio files generated by polly
9+
10+
Resources:
11+
# S3 bucket to store audio file created by polly service
12+
AudioFileBucket:
13+
Type: AWS::S3::Bucket
14+
Properties:
15+
BucketName: !Ref s3BucketName
16+
# API Gateway REST API
17+
ApiGatewayApi:
18+
Type: AWS::Serverless::Api
19+
Properties:
20+
Name: apigw-translate-polly-s3
21+
StageName: prod
22+
EndpointConfiguration:
23+
Type: REGIONAL
24+
# Lambda Function to call AWS Translate and Polly services
25+
ApiFunction:
26+
Type: AWS::Serverless::Function
27+
Properties:
28+
FunctionName: lambda-translate-polly-s3
29+
Environment:
30+
Variables:
31+
S3_BUCKET_NAME: !Ref s3BucketName
32+
Runtime: python3.9
33+
Handler: index.lambda_handler
34+
CodeUri: src/
35+
MemorySize: 128
36+
Policies:
37+
- TranslateReadOnly
38+
- AmazonPollyReadOnlyAccess
39+
- Version: '2012-10-17'
40+
Statement:
41+
- Effect: Allow
42+
Action:
43+
- "s3:GetObject"
44+
- "s3:PutObject"
45+
Resource: "*"
46+
Events:
47+
ApiEvent:
48+
Type: Api
49+
Properties:
50+
Path: /
51+
Method: post
52+
RestApiId:
53+
Ref: ApiGatewayApi
54+
55+
Outputs:
56+
RestApiEndpoint:
57+
Description: "The endpoint for the REST API Gateway"
58+
Value: !Sub "https://${ApiGatewayApi}.execute-api.${AWS::Region}.amazonaws.com/prod/"

0 commit comments

Comments
 (0)