Translate text between the languages using Amazon Translate

What is the Use case?

This blog will explain a simple use case of Amazon Translate, where you can POST an HTTP request with your input data for the Amazon Translate and upload the translated text to an S3 bucket.

We will be creating a serverless project using the Sigma IDE. Apart from the Amazon Translate, it will use API Gateway, AWS Lambda, and Amazon S3 resources.

Don't have a Sigma IDE account? You can sign-up here for a free account.

Implementation

1. Create a Sigma Project

Once your Sigma Account sign-up is completed, login and create a new project. Make sure to select AWS as the Base Platform and NodeJS as the Primary Language. Select the preferred AWS region as the Project Region and Click on the Create Project button. Make sure the Amazon Translate is available in the region you have selected.

create project

2. API Gateway Trigger

monaco editor

Once you’ve created the project, the Editor view will be opened with the Lambda file and default code snippet. Now we have to edit the code as required.

First, let's add an API Gateway as a trigger. On the left-hand side Resource Panel, all the resource types which Sigma supports are listed. Click on the API Gateway from the list and drag and drop it onto the event variable on the lambda handler. API Gateway Configuration panel will open on the right side.

api gateway

You can fill the API name (SampleTransalatorAPI) and the Resource path (/translate/add) with something suitable and select the Method POST. Then configure a suitable deployment stage name, I have used the name test.
Once you have filled in the details, click on the Inject button to set the API Gateway as the trigger. After a successful update, the trigger icon in front of the lambda handler will turn to green and if you want to make any changes to the added API Gateway Trigger, you can open the API Configuration panel by clicking on that.

3. Sample Payload

Before we move on to the next resource let's take a look at what we are going to translate. I will be passing the following JSON payload to the API Gateway endpoint.

{
    "data": "كيف حالكم",
    "filename": "test010.txt",
    "language": "ar"
}

This includes the text we are going to translate for this project, the file name we use to save the translated text in the S3, and the source language (the input language). There are more than 70 languages supported by Amazon Translate and you can find the complete list here.

I have assigned the JSON payload to variables on the Sigma project before I add the Amazon Translate resource.

    let sourceData = event.data;
    let sourceLanguage = event.language;
    let fileName = event.filename;

4. Add Amazon Translate

Now from the left-hand resource panel drag and drop the Translate resource onto the editor panel (on to any line between the fileName variable and the return statement). Just like the API Gateway, the Translate configuration panel will open on the right-hand side.

image translate

Keep the Operation as Translate Text. For the Text field, we have to give the sourceData variable. On the configuration panel, you can specify variables using @{variablename} syntax. If you have already defined the variables, once you type @{ the list of available variables will be suggested.

Source Language field you have to give the sourceLanguage variable. First, toggle the Preset button to custom and add the variable. For now, we keep Target Language as it is. So your text will be translated into English. If you need, that can also be changed to any other supported language by selecting one from the drop-down list or adding a custom value.

Then click on the Inject button.

I updated the initially injected code, so now if the translation was successful it will return the translated text, assign it to s3Content, and in an error scenario, it will log the error message and throw the error. Here is the updated sample.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const translate = new AWS.Translate();
 
exports.handler = async (event) => {
 
    let sourceData = event.data;
    let sourceLanguage = event.language;
    let fileName = event.filename;
 
    try {
        let data = await translate.translateText({
            SourceLanguageCode: sourceLanguage,
            TargetLanguageCode: "en",
            Text: sourceData
        }).promise();
 
        let s3Content = data.TranslatedText;
        console.log("This is the translation :", s3Content);
        return s3Content;
 
    } catch (err) {
        msg = `Unable to translate input data due to an error: ${err}`;
        console.log(msg);
        throw (err);
 
    };
 
};

5. Testing the Implementation up to now.

Even though we have not added the S3 Upload part yet, and have not deployed the project to AWS, we can test the code we edited so far by using the inbuilt testing capability of the Sigma IDE. Click on the Create event on the top toolbar and + sign next to Test Events. Copy and paste the JSON payload to the Test Event input box and click on the Execute Test Icon next to Event Name.

If everything up to now works fine, you will be able to see a log with the translated value on the Sigma Trail.

sigma trail

6. Add S3 Resource

The next step is to add the S3 resource from the resource panel. Just like the other resources drag and drop the S3 resource inside the try block after the log line.

Here you can select one of your existing S3 buckets from the drop-down to upload the text file. If you do not have an S3 Bucket you can create one by clicking on the New Bucket tab and giving a bucket name.

s3 bucket

Select Put Object as the S3 Operation and The content of the Object should be s3Content and the Name of the object should be fileName. Add both of them as variables. Then click on the Inject button.

Now we’ve almost completed the project. I’ve updated the default injected S3 code to add log lines and return a success message after a successful Put operation. Below is the full code after all the changes.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const translate = new AWS.Translate();
 
exports.handler = async (event) => {
 
    let sourceData = event.data;
    let sourceLanguage = event.language;
    let fileName = event.filename;
 
    try {
        let data = await translate.translateText({
            SourceLanguageCode: sourceLanguage,
            TargetLanguageCode: "en",
            Text: sourceData
        }).promise();
 
        let s3Content = data.TranslatedText;
        console.log("This is the translation :", s3Content);
 
        try {
            let data = await s3.putObject({
                Bucket: "cloud9-ktest",
                Key: fileName,
                Body: s3Content,
                Metadata: {}
            }).promise();
 
            console.log(`The object ${fileName} is successfully saved to the S3 bucket translate-data`);
            return { "message": "Translated Text : " + s3Content };
 
        } catch (err) {
            msg = `Unable to save the object in to the S3 bucket: ${err}`;
            console.log(msg);
            throw (err);
 
        };
 
    } catch (err) {
        msg = `Unable to translate input data due to an error: ${err}`;
        console.log(msg);
        throw (err);
 
    };
 
};

Now if you run the Test event we have created earlier, the following logs will be printed on the Sigma Trail.

{"message":"Translated Text : How are you doing?"}
[5/19/2021] [8:29:30 AM] INFO    This is the translation : How are you doing?
[5/19/2021] [8:29:30 AM] INFO    The object test010.txt is successfully saved to the S3 bucket cloud9-ktest

log

Note:
If you have added an already existing S3 bucket to the code a new file will be added to the bucket with the translated text. But if it is a new S3 bucket you have to first deploy the project before running a test, since then only the new bucket will be created.

Deploying the Project

Once everything is completed now, all that is left is to deploy the Lambda in the AWS. Click on the Deploy Project Icon on the top toolbar and you will be prompted with a Change Summary pop-up like follow. This summarizes the complete deployment, with all the changes this deployment will perform. Click on the Execute icon to start the deployment.

deploy project

Once the deployment is completed, the summary view will be updated with the status of the deployment and the URL of the API Gateway endpoint. You can copy that URL and POST an HTTP request using an HTTP client with the JSON Payload we had above, to trigger the Lambda we just deployed.

deployment completed

Once you make an API call to the given endpoint you can login to the AWS console and check the given S3 bucket for the translated text files.