This is the 8th project in my Twenty Projects in Twenty Days series! In this project, we’ll look at how to use Amazon Translate with Python using Boto3 and with Node.js using the AWS SDK for JavaScript. We’ll translate our first text in under 10 lines of code so let’s get started! You can copy the code from the GitHub repo here.
First, you’ll need to make sure you have a few things:
- The AWS CLI installed and configured with AWS credentials
- Python 3 and the Boto3 SDK installed if you plan to use Python
- Node.js and the AWS SDK for JavaScript installed if you want to use Node.js
From there, it’s super easy!
Python
Using Python, open up the Python interpreter and type in this code:
import boto3
translate = boto3.client('translate')
result = translate.translate_text(
Text='Hello! My name is Fernando.',
SourceLanguageCode='auto',
TargetLanguageCode='es'
)
print(result['TranslatedText'])
Here’s what’s happening above:
- We import
boto3
- We create an Amazon Translate client with Boto3
- We use the
translate_text()
method to translate text from english to Spanish (with thees
language code) - We print the result out to see what it says.
You should see something like this at the end of doing this:
>>> print(result['TranslatedText'])
¡Hola! ¡Hola! Mi nombre es Fernando.
And that’s it! It’s honestly that simple! Now let’s do Node.js!
Node.js
Open up the Node.js runtime and enter in the code below:
var AWS = require("aws-sdk");
AWS.config.update({region: "us-east-1"});
var translate = new AWS.Translate();
var params = {
SourceLanguageCode: 'auto',
TargetLanguageCode: 'es',
Text: 'Hello! My name is Fernando.'
};
translate.translateText(params, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data['TranslatedText']);
});
Here’s what’s happening:
- The first few lines import the AWS SDK for Node.js (the
aws-sdk
) and configure the AWS region to use - Then we setup an Amazon Translate client with
var translate = new AWS.Translate();
- From there, we set up some parameters to use the in the translation request including specifying the source language be autodetected, and that it be translated into Spanish (the
es
language code) - Finally, we run the
translateText()
method with the parameters from earlier and thenconsole.log()
theTranslatedText
property of the result which is where the translated string is stored.
It should output something like this:
> ¡Hola! ¡Hola! Mi nombre es Fernando.
And that’s it! You should be able to use this in Node.js or Python to translate text using Amazon Translate. If you want more details on how to use Amazon Translate, you can sign up for my mailing list and reply to the welcome email and I’ll give you free access to my Pluralsight.com courses including my course on Amazon Translate!