Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions apigw-lambda-translate-polly-s3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Amazon API Gateway REST API to AWS Lambda which calls AWS Translate and Polly services

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.

Learn more about this pattern at: https://serverlessland.com/patterns/apigw-lambda-translate-polly-s3.

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.

## Requirements

* [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.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
* [AWS Translate](https://aws.amazon.com/translate/)
* [AWS Translate Languages](https://docs.aws.amazon.com/translate/latest/dg/pairs.html)
* [AWS Polly](https://aws.amazon.com/polly/)
* [AWS S3](https://aws.amazon.com/s3/)

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```
cd apigw-lambda-translate-polly-s3
```
3. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam deploy --guided
```
4. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Enter the S3 bucket to store the audio file

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.

5. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs that were created.

## How it works

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.

## Testing

Once the application is deployed, either use a curl or call the endpoint from Postman.

Example POST Request to translate text to Spanish:
```
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"es"}'
```

Response:
```
"{"TranslatedText": "Hola, esto es sin servidor", "AudioFile": "s3://{yourS3bucketname}/1692129677356.mp3"}"
```

Example POST Request to translate text to Afrikaans:
```
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"af"}'
```

Response:
```
"{"TranslatedText": "Hallo dit is bedienerloos", "AudioFile": "s3://{yourS3bucketname}/1692129833975.mp3"}"
```

Example POST Request with unsupported language:
```
curl -X POST "https://{api-gateway-endpoint}/prod" -H 'Content-Type: application/json' -d '{"OriginalText":"Hello this is serverless","TranslateToLanguage":"ef"}'
```

Response:
```
"An error occurred (UnsupportedLanguagePairException) when calling the TranslateText operation: Unsupported language pair: en to ef. Target language 'ef' is not supported"
```

## Documentation
- [Working with REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html)
- [Working with AWS Lambda proxy integrations for REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html)
- [AWS Lambda - the Basics](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/aws-lambdathe-basics.html)
- [Lambda Function Handler](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-handler.html)
- [Function Environment Variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)

## Cleanup

Please empty the S3 bucket to delete the audio files before running "sam delete".

1. Delete the stack
```bash
sam delete
```

This pattern was contributed by Sudheer Yalamanchili.

----
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
65 changes: 65 additions & 0 deletions apigw-lambda-translate-polly-s3/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"title": "Amazon API Gateway REST API to AWS Lambda which calls AWS Translate and Polly services",
"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.",
"language": "Python",
"level": "200",
"framework": "SAM",
"introBox": {
"headline": "How it works",
"text": [
"API Gateway REST API is integrated to AWS Lambda function which calls AWS Translate and Polly services"
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-translate-polly-s3",
"templateURL": "serverless-patterns/apigw-lambda-translate-polly-s3",
"projectFolder": "apigw-lambda-translate-polly-s3",
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "AWS Serverless Application Model",
"link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html"
},
{
"text": "AWS Translate",
"link": "https://aws.amazon.com/translate/"
},
{
"text": "AWS Translate Languages",
"link": "https://docs.aws.amazon.com/translate/latest/dg/pairs.html"
},
{
"text": "AWS Polly",
"link": "https://aws.amazon.com/polly/"
},
{
"text": "AWS S3",
"link": "https://aws.amazon.com/s3/"
}
]
},
"deploy": {
"text": [
"sam deploy --guided" ]
},
"testing": {
"text": ["See the GitHub repo for detailed testing instructions."]
},
"cleanup": {
"text": [
"Delete the stack: <code>sam delete</code>."
]
},
"authors": [
{
"name": "Sudheer Yalamanchili",
"image": "./sudheer.jpg",
"bio": "Sudheer is a Cloud Application Architect at AWS ProServ.",
"linkedin": "sudheeryalamanchili"
}
]
}
62 changes: 62 additions & 0 deletions apigw-lambda-translate-polly-s3/src/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import json
import boto3
import os
from contextlib import closing

# Get the aws translate client
translate_client = boto3.client('translate')
# Get the aws s3 client
s3_client = boto3.client("s3")
# Get the aws polly client
polly_client = boto3.client("polly")

def lambda_handler(event, context):
# Fetch the message body and request timestamp from the request event
req_body = json.loads(event['body'])
timestamp = event['requestContext']['requestTimeEpoch']
bucket_name = os.environ['S3_BUCKET_NAME']

try:
# Call translate_text API with the text and language given in the request body
translate_response = translate_client.translate_text(
Text=req_body["OriginalText"],
SourceLanguageCode='auto',
TargetLanguageCode=req_body["TranslateToLanguage"]
)
print(req_body)

# Get the translated text from the response
response_text = translate_response['TranslatedText']

# Call the Polly API to convert translated text to speech
response = polly_client.synthesize_speech(Text=response_text, OutputFormat="mp3", VoiceId="Lucia")

# Get the audio file from the response
audio_file = response["AudioStream"]

# Create s3 filename using request timestamp
audio_file_name = str(timestamp) + ".mp3"
print(audio_file_name)

# Save the audio file to the s3 bucket that was created during stack creation
with closing(audio_file) as stream:
s3_client.put_object(Key=audio_file_name, Body=stream.read(), Bucket=bucket_name)

# create response object
response_json = {
"TranslatedText": response_text,
"AudioFile": "s3://" + bucket_name + "/" + audio_file_name
}

except Exception as errormessage:
# Get the error messages if translation fails
response_json = str(errormessage)

# return translated text or error response if translation fails
return {
'statusCode': 200,
'body': json.dumps(response_json)
}
Binary file added apigw-lambda-translate-polly-s3/sudheer.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
58 changes: 58 additions & 0 deletions apigw-lambda-translate-polly-s3/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
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.

Parameters:
s3BucketName:
Type: String
Description: s3 bucket to save audio files generated by polly

Resources:
# S3 bucket to store audio file created by polly service
AudioFileBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref s3BucketName
# API Gateway REST API
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
Name: apigw-translate-polly-s3
StageName: prod
EndpointConfiguration:
Type: REGIONAL
# Lambda Function to call AWS Translate and Polly services
ApiFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: lambda-translate-polly-s3
Environment:
Variables:
S3_BUCKET_NAME: !Ref s3BucketName
Runtime: python3.9
Handler: index.lambda_handler
CodeUri: src/
MemorySize: 128
Policies:
- TranslateReadOnly
- AmazonPollyReadOnlyAccess
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- "s3:GetObject"
- "s3:PutObject"
Resource: "*"
Events:
ApiEvent:
Type: Api
Properties:
Path: /
Method: post
RestApiId:
Ref: ApiGatewayApi

Outputs:
RestApiEndpoint:
Description: "The endpoint for the REST API Gateway"
Value: !Sub "https://${ApiGatewayApi}.execute-api.${AWS::Region}.amazonaws.com/prod/"