Amazon Translate Developer Guide
Amazon Translate Developer Guide
Amazon Translate Developer Guide
Developer Guide
Amazon Translate Developer Guide
Table of Contents
What Is Amazon Translate? ................................................................................................................. 1
Are You a First-time User of Amazon Translate ? ............................................................................ 1
How It Works .................................................................................................................................... 3
Automatic Language Detection .................................................................................................... 4
Exception Handling .................................................................................................................... 4
Next Steps ................................................................................................................................ 4
Getting Started .................................................................................................................................. 6
Step 1: Set Up an Account .......................................................................................................... 6
Sign Up for AWS ................................................................................................................ 6
Create an IAM User ............................................................................................................ 7
Next Step .......................................................................................................................... 7
Step 2: Set Up the AWS CLI ........................................................................................................ 7
Next Step .......................................................................................................................... 8
Step 3: Getting Started (Console) ................................................................................................. 8
Next Step .......................................................................................................................... 9
Step 4: Getting Started (AWS CLI) ................................................................................................ 9
Translate Text Using the Command Line ............................................................................. 10
Translate Text Using a JSON File ........................................................................................ 10
Next Step ........................................................................................................................ 11
Step 5: Getting Started (SDK) .................................................................................................... 11
Using the SDK for Java ..................................................................................................... 11
Using the AWS SDK for Python .......................................................................................... 12
Using the Mobile SDK for Android ...................................................................................... 12
Using the Mobile SDK for iOS ............................................................................................ 14
Examples ......................................................................................................................................... 16
Using Amazon Polly with Amazon Translate ................................................................................ 16
Code ............................................................................................................................... 16
Using Amazon Translate to Translate a Chat Channel .................................................................... 20
Using Amazon Translate with DynamoDB .................................................................................... 28
Example Code .................................................................................................................. 29
Using Amazon Translate to Translate a Web Page ......................................................................... 31
Using Amazon Translate to Translate Large Documents ................................................................. 34
Using Signature Version 4 with Amazon Translate ........................................................................ 36
Setting Up ....................................................................................................................... 36
Code ............................................................................................................................... 36
Authentication and Access Control ..................................................................................................... 40
Authentication ......................................................................................................................... 40
Access Control ......................................................................................................................... 41
Overview of Managing Access .................................................................................................... 41
Managing Access to Actions ............................................................................................... 41
Specifying Policy Elements: Resources, Actions, Effects, and Principals ..................................... 42
Specifying Conditions in a Policy ........................................................................................ 43
Using Identity-Based Policies (IAM Policies) for Amazon Translate ................................................... 43
Amazon Translate API Permissions Reference ............................................................................... 44
Monitoring ....................................................................................................................................... 45
Monitoring with CloudWatch ..................................................................................................... 47
Understanding CloudWatch Metrics for Amazon Translate ..................................................... 47
Viewing Amazon Translate Metrics ..................................................................................... 48
CloudWatch Metrics and Dimensions for Amazon Translate ............................................................ 48
CloudWatch Metrics for Amazon Translate ........................................................................... 48
CloudWatch Dimensions for Amazon Translate ..................................................................... 49
Guidelines and Limits ........................................................................................................................ 50
Supported Regions ................................................................................................................... 50
Throttling ................................................................................................................................ 50
iii
Amazon Translate Developer Guide
Guidelines ............................................................................................................................... 50
Limits ..................................................................................................................................... 50
Document History ............................................................................................................................ 51
API Reference .................................................................................................................................. 52
HTTP Headers .......................................................................................................................... 52
Actions .................................................................................................................................... 52
TranslateText ................................................................................................................... 53
Data Types .............................................................................................................................. 56
Common Errors ........................................................................................................................ 56
Common Parameters ................................................................................................................ 57
AWS Glossary .................................................................................................................................. 60
iv
Amazon Translate Developer Guide
Are You a First-time User of Amazon Translate ?
• Arabic
• Chinese (Simplified)
• Chinese (Traditional)
• Czech
• French
• German
• Italian
• Japanese
• Portuguese
• Russian
• Spanish
• Turkish
Amazon Translate uses advanced machine learning technologies to provide high-quality translation on
demand. Use it to translate unstructured text documents or to build applications that work in multiple
languages.
• Integrate Amazon Translate into your applications to enable multilingual user experiences.
• Translate company-authored content, such as meeting minutes, technician reports, knowledge-base
articles, posts, and more.
• Translate interpersonal communications, such as email, in-game chat, customer service chat, and
more, enabling customers and employees to connect in their preferred language.
• Use Amazon Translate as part of your company's workflow for incoming data.
• Analyze text, such as social media and news feeds, in many languages.
• Search information, such as for eDiscovery cases, in many languages.
• Integrate Amazon Translate with other AWS services to enable language-independent processing.
• Use it with Amazon Comprehend to extract named entities, sentiment, and key phrases from
unstructured text, such as social media streams.
• Use it with Amazon Transcribe to make subtitles and live captioning available in many languages.
• Use it with Amazon Polly to speak translated content.
• Use it with Amazon S3 to translate document repositories.
• Use it with Amazon DynamoDB, Amazon Aurora, and Amazon Redshift to translate text stored in
databases.
• Use it with AWS Lambda or AWS Glue for seamless workflow integration.
1
Amazon Translate Developer Guide
Are You a First-time User of Amazon Translate ?
2
Amazon Translate Developer Guide
• Arabic
• Chinese (Simplified)
• Chinese (Traditional)
• Czech
• French
• German
• Italian
• Japanese
• Portuguese
• Russian
• Spanish
• Turkish
You can also translate text in any of these languages into another one of these languages by first
translating the source text to English and then translating the English text to the target language.
When working with Amazon Translate, you will provide source text and get output text:
• Source text—The text that you want to translate. You provide the source text in UTF-8 format.
• Output text—The text that Amazon Translate has translated into the target language Output text is
also in UTF-8 format. Depending on the source and target languages, there might be more characters
in the output text than in the input text.
The translation model has two components, the encoder and the decoder. The encoder reads a source
sentence one word at a time and constructs a semantic representation that captures its meaning. The
decoder uses the semantic representation to generate a translation one word at a time in the target
language.
Amazon Translate uses attention mechanisms to understand context. This helps it decide which words in
the source text are most relevant for generating the next target word. Attention mechanisms enable the
decoder to focus on the most relevant parts of a source sentence. This ensures that the decoder correctly
translates ambiguous words or phrases.
The target word that the model generates becomes input to the decoder. The network continues
generating words until it reaches the end of the sentence.
To translate text, you call the TranslateText (p. 53) method and provide the source text and the target
language, using the language code listed in the following table.
Language Code
Arabic ar
Chinese (Simplified) zh
3
Amazon Translate Developer Guide
Automatic Language Detection
Language Code
Czech cs
English en
French fr
German de
Italian it
Japanese ja
Portuguese pt
Russian ru
Spanish es
Turkish tr
To translate text from any non-English language in the table to any other non-English language in the
table, translate it into English, and then translate the English output text into the target language.
Amazon Translate can automatically detect the source language. For automatic language detection,
specify auto as the source language. when you provide source text. Amazon Translate calls Amazon
Comprehend to detect the source language.
Exception Handling
If you specify a source or target language that isn't supported, Amazon Translate returns the following
exceptions:
Next Steps
Now that you've learned about Amazon Translate you can explore the following sections to learn about
creating a solution.
4
Amazon Translate Developer Guide
Next Steps
5
Amazon Translate Developer Guide
Step 1: Set Up an Account
Topics
• Step 1: Set Up an AWS Account and Create an Administrator User (p. 6)
• Step 2: Set Up the AWS Command Line Interface (AWS CLI) (p. 7)
• Step 3: Getting Started (Console) (p. 8)
• Step 4: Getting Started (AWS CLI) (p. 9)
• Step 5: Getting Started (SDK) (p. 11)
With Amazon Translate, you pay only for the resources that you use. If you are a new AWS customer, you
can get started with Amazon Translate for free. For more information, see AWS Free Usage Tier.
Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phone
keypad.
Record your AWS account ID because you'll need it for the next task.
6
Amazon Translate Developer Guide
Create an IAM User
We strongly recommend that you access AWS using AWS Identity and Access Management (IAM), not the
credentials for your AWS account. To use IAM to access AWS, create an IAM user, add the user to an IAM
group with administrative permissions, and then grant administrative permissions to the IAM user. You
can then access AWS using a special URL and the IAM user's credentials.
Exercises in this guide assume that you have an IAM user with administrator privileges called
adminuser.
• In your AWS account, create an administrator user called adminuser. For instructions, see Creating
Your First IAM User and Administrators Group in the IAM User Guide.
Next Step
Step 2: Set Up the AWS Command Line Interface (AWS CLI) (p. 7)
1. Download and configure the AWS CLI. For instructions, see the following topics in the AWS
Command Line Interface User Guide:
[profile adminuser]
aws_access_key_id = adminuser access key ID
aws_secret_access_key = adminuser secret access key
region = aws-region
You use this profile when executing AWS CLI commands. For more information about named
profiles, see Named Profiles in the AWS Command Line Interface User Guide. For a list of AWS
Regions, see Regions and Endpoints in the Amazon Web Services General Reference.
7
Amazon Translate Developer Guide
Next Step
3. Verify the setup by typing the following help command at the command prompt:
You should see a brief description of Amazon Translate and a list of the available commands.
Next Step
Step 3: Getting Started (Console) (p. 8)
To start translating text, go to the AWS Management Console and open the Amazon Translate console.
If this is the first time that you've used Amazon Translate, choose Try Amazon Translate.
In Translate text, choose the source and target languages. Enter the text that you want to translate in
the left-hand text box. The translated text appears in the right-hand text box.
In the JSON samples section you can see the JSON input and output to the TranslateText (p. 53)
operation.
8
Amazon Translate Developer Guide
Next Step
Next Step
Step 4: Getting Started (AWS CLI) (p. 9)
There are two ways to use the CLI to translate text with Amazon Translate. For short text, you can
provide the text that you want to translate as a parameter of the translate-text command. For
longer text, you can provide the source language, target language, and text in a JSON file.
To use Amazon Translate from the command line, you need to know the endpoint and region for the
service. For a list of available endpoints and regions, see Guidelines and Limits (p. 50).
9
Amazon Translate Developer Guide
Translate Text Using the Command Line
{
"TargetLanguageCode": "es",
"Text": "Hola, mundo",
"SourceLanguageCode": "en"
}
{
"Text": "Amazon Translate translates documents into English from
six languages and vice versa in real time. It uses
advanced machine learning technologies to provide
high-quality real-time translation. Use it to translate
documents or to build applications that work in multiple
languages.",
"SourceLanguageCode": "en",
"TargetLanguageCode": "fr"
}
The command outputs a JSON file that contains the following JSON text:
{
"TargetLanguageCode": "fr",
"Text": "Amazon Translate traduit les documents en anglais à partir
10
Amazon Translate Developer Guide
Next Step
Next Step
To see other ways to use Amazon Translate see Examples (p. 16).
To run the Java examples, you need to install the AWS SDK for Java. For instructions for installing the
SDK for Java, see Set up the AWS SDK for Java.
Topics
• Translating Text Using the AWS SDK for Java (p. 11)
• Translating Text Using the AWS SDK for Python (Boto) (p. 12)
• Translating Text Using the AWS Mobile SDK for Android (p. 12)
• Translating Text Using the AWS Mobile SDK for iOS (p. 14)
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.translate.AmazonTranslateClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;
11
Amazon Translate Developer Guide
Using the AWS SDK for Python
You can change the source and target languages subject to the following constraints:
• If the source language is English, you can translate the source text to any of the other supported
languages. For a list of supported languages, see How Amazon Translate Works (p. 3).
• If the source language is not English, the target language must be English.
import boto3
You can change the source and target languages subject to the following constraints:
• If the source language is English, you can translate the source text to any of the other supported
languages. For a list of supported languages, see How It Works (p. 3).
• If the source language is not English, the target language must be English.
1. Set up the AWS Mobile SDK for Android. For instructions, see Android: Setup Options for the SDK in
the AWS Mobile Developer Guide
2. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43). After you create the user, download the
credentials or record the access key and secret access key.
3. Create a new project with Android Studio.
12
Amazon Translate Developer Guide
Using the Mobile SDK for Android
dependencies {
implementation 'com.amazonaws:aws-android-sdk-translate:2.6.20'
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Code
Use the following code to create the example.
package com.amazonaws.amazontranslatetester;
import android.app.Activity;
import android.util.Log;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.handlers.AsyncHandler;
import com.amazonaws.services.translate.AmazonTranslateAsyncClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
AWSCredentials awsCredentials = new AWSCredentials() {
@Override
public String getAWSAccessKeyId() {
return "access key";
}
@Override
public String getAWSSecretKey() {
return "secret key";
}
};
13
Amazon Translate Developer Guide
Using the Mobile SDK for iOS
@Override
public void onSuccess(TranslateTextRequest request, TranslateTextResult
translateTextResult) {
Log.d(LOG_TAG, "Original Text: " + request.getText());
Log.d(LOG_TAG, "Translated Text: " +
translateTextResult.getTranslatedText());
}
});
}
}
1. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43). After you create the user, download the
credentials or record the access key and secret access key.
2. Install Xcode version 8.0 or later. You can download the latest version of Xcode from the Apple
website, https://developer.apple.com/xcode/.
3. Install Cocoapods. In a terminal window, run the following command:
4. Create a project using Xcode. Then, in a terminal window, navigate to the directory that contains
your project's .xcodeproj file and run the following command:
pod init
5. Add the core Mobile SDK for iOS components to your pod file:
7. Running 'pod install' creates a new workspace file. Close your Xcode project and then open it
using the ./project_name.xcworkspace file. From now on you should only use this file to open your
Xcode project
Rebuild your app after you open it to resolve APIs from the new libraries called in your code.
8. Add the following import statement to your view controller:
14
Amazon Translate Developer Guide
Using the Mobile SDK for iOS
import AWSTranslate
9. Copy the following code into your XCode project. Update the access key and secret key to the values
that you recorded in step 1.
Code
Use the following code to create the example.
AWSServiceManager.default().defaultServiceConfiguration = configuration
15
Amazon Translate Developer Guide
Using Amazon Polly with Amazon Translate
Examples
The following examples show ways that you can use Amazon Translate.
Topics
• Using Amazon Polly with Amazon Translate (p. 16)
• Using Amazon Translate to Translate a Chat Channel (p. 20)
• Using Amazon Translate with Amazon DynamoDB (p. 28)
• Using Amazon Translate to Translate a Web Page (p. 31)
• Using Amazon Translate to Translate Large Documents (p. 34)
• Using Signature Version 4 with Amazon Translate (p. 36)
1. Install and Configure the AWS SDK for JavaScript. For instructions for installing the SDK for
JavaScript, see Installing the SDK for JavaScript.
2. Copy the code for the example to an HTML file on your Web server.
3. Update the <script> tag to the location where you installed the SDK for JavaScript.
4. Change the region and endpoint to the region where you want to run the Amazon Translate and
Amazon Polly operations. For a list of supported regions for Amazon Translate, see Guidelines and
Limits (p. 50). For a list of supported regions for Amazon Polly, see AWS Regions and Endpoints in
the Amazon Web Services General Reference.
5. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43) and Using Identity-Based Policies (IAM
Policies) for Amazon Polly in the Amazon Polly Developer Guide.
6. Provide the access ID and secret key of the IAM user created in the previous step.
Code
The following is the complete code of the example Web page. You can copy this code into an HTML file
to run the example on your own Web server.
<!DOCTYPE html>
<html>
16
Amazon Translate Developer Guide
Code
<head>
<title>Amazon Translate</title>
<script src="aws-sdk/dist/aws-sdk.js"></script>
</head>
<body>
<h1 style="text-align: left">Amazon Translate Demo</h1>
<br/>
<table class="tg">
<tr>
<th align="left">
Source Language Code:
<select id="sourceLanguageCodeDropdown">
<option value="en">en</option>
<option value="ar">ar</option>
<option value="cs">cs</option>
<option value="de">de</option>
<option value="es">es</option>
<option value="fr">fr</option>
<option value="it">it</option>
<option value="ja">ja</option>
<option value="pt">pt</option>
<option value="ru">ru</option>
<option value="tr">tr</option>
<option value="zh">zh</option>
<option value="zh-TW">zh-TW</option>
</select>
</th>
<th align="left">
Target Language Code:
<select id="targetLanguageCodeDropdown">
<option value="en">en</option>
<option value="ar">ar</option>
<option value="cs">cs</option>
<option value="de">de</option>
<option value="es">es</option>
<option value="fr">fr</option>
<option value="it">it</option>
<option value="ja">ja</option>
<option value="pt">pt</option>
<option value="ru">ru</option>
<option value="tr">tr</option>
<option value="zh">zh</option>
<option value="zh-TW">zh-TW</option>
</select>
</th>
</tr>
<tr>
<th>
<textarea id="inputText" name="inputText" rows="10" cols="50"
placeholder="Text to translate..."></textarea>
</th>
<th>
<textarea id="outputText" name="outputText" rows="10" cols="50"
placeholder="Translated text..."></textarea>
</th>
</tr>
<tr>
<th align="left">
<button type="button" name="translateButton"
onclick="doTranslate()">Translate</button>
<button type="button" name="synthesizeButton"
onclick="doSynthesizeInput()">Synthesize Input Speech</button>
<button type="button" name="clearButton" onclick="clearInputs()">Clear</
button>
17
Amazon Translate Developer Guide
Code
</th>
<th align="left">
<button type="button" name="synthesizeButton"
onclick="doSynthesizeOutput()">Synthesize Output Speech</button>
</th>
</tr>
</table>
<script type="text/javascript">
// set the focus to the input box
document.getElementById("inputText").focus();
/**
* Change the region and endpoint.
*/
AWS.config.region = 'region'; // Region
/**
* In a production application you should use a secure method of authenticating
uses, such as the ones
* described here:
* https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-
credentials-browser.html
*
* Note that Amazon Translate does not work with Amazon Cognito Identity.
*
* For this example you place the credentials of an IAM user in the HTML page. The
IAM user associated
* with these credentials must have permissions to call Amazon Translate. We
recommend using the following
* permissions policy and nothing more, as anyone that has access to this HTML page
will also have access to
* these hard-coded credentials.
* {
* "Version": "2012-10-17",
* "Statement": [
* {
* "Action": [
* "translate:TranslateText",
* "polly:SynthesizeSpeech"
* ],
* "Resource": "*",
* "Effect": "Allow"
* }
* ]
* }
*
* For more information about the AWS Credentials object, see:
* http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html
*/
AWS.config.credentials = new AWS.Credentials("access key", "secret key);
function doTranslate() {
var inputText = document.getElementById('inputText').value;
if (!inputText) {
alert("Input text cannot be empty.");
exit();
}
18
Amazon Translate Developer Guide
Code
var params = {
Text: inputText,
SourceLanguageCode: sourceLanguageCode,
TargetLanguageCode: targetLanguageCode
};
function doSynthesizeInput() {
var text = document.getElementById('inputText').value.trim();
if (!text) {
return;
}
var sourceLanguageCode =
document.getElementById("sourceLanguageCodeDropdown").value;
doSynthesize(text, sourceLanguageCode);
}
function doSynthesizeOutput() {
var text = document.getElementById('outputText').value.trim();
if (!text) {
return;
}
var targetLanguageCode =
document.getElementById("targetLanguageCodeDropdown").value;
doSynthesize(text, targetLanguageCode);
}
19
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
function clearInputs() {
document.getElementById('inputText').value = "";
document.getElementById('outputText').value = "";
document.getElementById("sourceLanguageCodeDropdown").value = "en";
document.getElementById("targetLanguageCodeDropdown").value = "en";
}
</script>
</body>
</html>
This example uses a web page that shows real-time messages in English and their real-time translations
side-by-side. You can send the messages to Amazon Polly to speak the text. To follow a person in the
chat, type their user name. The app will speak only messages from that user.
20
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
1. Install and Configure the AWS SDK for JavaScript. For instructions for installing the SDK for
JavaScript, see Installing the SDK for JavaScript.
2. Copy the code for the example to an HTML file on your Web server.
3. Update the <script> tag to the location where you installed the SDK for JavaScript.
4. Change the region and endpoint to the region where you want to run the Amazon Translate and
Amazon Polly operations. For a list of supported regions for Amazon Translate, see Guidelines and
Limits (p. 50). For a list of supported regions for Amazon Polly, see AWS Regions and Endpoints in
the Amazon Web Services General Reference.
5. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43) and Using Identity-Based Policies (IAM
Policies) for Amazon Polly in the Amazon Polly Developer Guide.
6. Provide the access ID and secret key of the IAM user created in the previous step.
7. Provide a Twitch user name and OAuth token for your account. You can create a Twitch account at
https://www.twitch.tv. You can create a Twitch OAuth token at https://twitchapps.com/tmi.
<!doctype html>
<html lang="en">
<head>
<title>Amazon Translate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
.panelHeading
{
background-color: #6441a4 !important;
}
.panelBody
{
min-height: 450px; max-height: 450px;overflow-y: scroll;
}
body{
margin-left: 0px;
margin-right: 0px;
height: 100%;
}
</style>
21
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
</head>
<body>
<div class="container-fluid">
<!--Top Header-->
<div class="row topHeader">
<div class="col-md-12">
<h4>Amazon Translate - Artificial Intelligence on AWS - Powerful machine learning
for all Developers and Data Scientists</h4>
</div>
</div>
<!--Status Label-->
<div class="row">
<div class="col-md-12">
<p class="bg-info">
<div id="connecting-div"></div>
</p>
</div>
</div>
22
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
</div>
</div>
<!--Chat Boxes-->
<div class="row">
<!--Live Chat-->
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading panelHeading">Live Chat</div>
<div id="livechatc" class="panel-body panelBody">
<div class="subscribe" id="livechat"></div>
</div>
</div>
</div>
<!--Live Chat-->
<!--Translated Chat-->
<div class="col-md-6">
<div class="panel panel-primary">
<div class="panel-heading panelHeading">Live Translation</div>
<div id="livetranslationc" class="panel-body panelBody">
<div class="imageDetected" id="livetranslation"></div>
</div>
</div>
</div>
<!--Translated Chat-->
</div>
<!--Send Message-->
<div class="row">
<div class="col-md-11">
<input type="text" id="message" class="form-control"/>
</div>
<div class=" col-md-1">
<button type="button" class="form-control btn btn-default" id="btn-send"
onclick="sendMessage()">Send</button>
</div>
</div>
</div>
<script src="aws-js-sdk/dist/aws-sdk-all.js"></script>
<script src="http://cdn.tmijs.org/js/1.2.1/tmi.min.js" integrity="sha384-
eE0n7sm1W7DOUI2Xh5I4qSpZTe6hupAO0ovLfqEy0yVJtGRBNfssdmjbJhEYm6Bw"
crossorigin="anonymous"></script>
<script>
cred = {
twitchUsername: "Twitch user name",
twitchOAuthToken: "Twitch OAuth token",
awsAccessKeyId: "access key",
awsSecretAccessKey: "secret key"
};
AWS.config.region = 'region';
ep = new AWS.Endpoint('endpoint');
23
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
//Twitch Client
var options = {
options: {
debug: false
},
connection: {
cluster: "aws",
reconnect: true
},
identity: {
username: cred.twitchUsername,
password: cred.twitchOAuthToken
},
channels: [con.channel]
};
window.client = tmi.client(options);
window.client.connect();
//Attached Handlers
window.client.on("chat", onChat);
window.client.on("connecting", onConnecting);
window.client.on("connected", onConnected);
//Disable UI Elements
document.getElementById("sourceLanguage").disabled = true;
document.getElementById("targetLanguage").disabled = true;
document.getElementById("channel").disabled = true;
document.getElementById("btn-go").disabled = true;
}
function init(){
//Get UI Controls
var lc = document.getElementById("livechat");
var lt = document.getElementById("livetranslation")
var lcc = document.getElementById("livechatc");
var ltc = document.getElementById("livetranslationc")
var cbspeak = document.getElementById("cbSpeak")
var follow = document.getElementById("follow");
var sendMessage = document.getElementById("message");
//Cache values
con = {
channel: document.getElementById("channel").value,
sourceLanguage: document.getElementById("sourceLanguage").value,
targetLanguage: document.getElementById("targetLanguage").value,
liveChatUI: lc,
liveTranslationUI: lt,
liveChatUIContainer: lcc,
liveTranslationUIContainer: ltc,
cbSpeak: cbspeak,
follow: follow,
sendMessage: sendMessage
}
lc.innerHTML = '';
lt.innerHTML = '';
//Speaker
var voiceId = "Joanna";
24
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
if(con.targetLanguage == "en")
voiceId = "Joanna";
else if(con.targetLanguage == "de")
voiceId = "Marlene";
else if(con.targetLanguage == "es")
voiceId = "Conchita";
else if(con.targetLanguage == "fr")
voiceId = "Celine";
else if(con.targetLanguage == "pt")
voiceId = "Ines";
else
voiceId = "Joanna";
window.audioPlayer = AudioPlayer(voiceId);
}
/**************************Init and Connect to Chat****************************/
//Translate
if (message) {
var username = userstate['username'];
var params = {
Text: message,
SourceLanguageCode: con.sourceLanguage,
TargetLanguageCode: con.targetLanguage
};
/**************************Client Connecting****************************/
25
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
/**************************Send Message****************************/
function sendMessage(){
if(con.sendMessage.value){
message = con.sendMessage.value;
var params = {
Text: con.sendMessage.value,
SourceLanguageCode: con.targetLanguage,
TargetLanguageCode: con.sourceLanguage
};
/**************************Audio player****************************/
function AudioPlayer(voiceId) {
var audioPlayer = document.createElement('audio');
audioPlayer.setAttribute("id", "audioPlayer");
document.body.appendChild(audioPlayer);
var speaker = {
self: this,
26
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Chat Channel
playlist:[],
return speaker;
27
Amazon Translate Developer Guide
Using Amazon Translate with DynamoDB
}
/**************************Audio player****************************/
</script>
</body>
</html>
• Use AWS CloudFormation to create DynamoDB tables to store the translation and a Lambda function
that calls the TranslateText (p. 53) operation.
• Test the function using the AWS Lambda console.
1. Copy the contents of example.py, which you can find in Python Lambda Function (p. 29), to a
file named example.py. example.py is a Lambda function that calls the TranslateText (p. 53)
operation. Compress the file to a zip archive named example.zip. Store it in an S3 bucket in the
same AWS Region where you want to run the function.
2. Create a new file named template.yaml. Copy the AWS CloudFormation template code, which you
can find in AWS CloudFormation Template (p. 30), into the file. AWS CloudFormation uses the
template to create resources for the sample application. Change BUCKET_NAME to the name of the
S3 bucket that contains example.zip. Save the file in a local directory.
3. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://
console.aws.amazon.com/cloudformation.
4. Choose Create new stack.
5. Choose Upload a template to Amazon S3, and then choose Choose file. Choose template.yaml,
that you created in Step 2, then Next.
6. Type a name for the stack, then choose Next.
7. On the Options page, choose Next.
8. Choose I acknowledge that AWS CloudFormation might create IAM resources and I acknowledge
that AWS CloudFormation might create IAM resources with custom names. For more information,
see Controlling Access with AWS Identity and Access Management in the AWS CloudFormation User
Guide.
9. Choose Create Change Set.
10. After AWS CloudFormation creates the change set, choose Execute. Wait until AWS CloudFormation
creates the stack.
11. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
12. Choose the new function. Its name starts with TestTranslate-ReviewTranslate.
13. On the function detail page, choose Test.
14. For Event name, type TestTranslate. For Configure test event, replace the JSON with the
following:
28
Amazon Translate Developer Guide
Example Code
Choose Create.
15. Make sure that TestTranslate is selected, then choose Test. When the test finishes, you receive the
following message:
Example Code
Use the following code to create the example.
import logging
import json
import boto3
import os
translate = boto3.client('translate')
dynamodb = boto3.client('dynamodb')
firehose = boto3.client('firehose')
TABLE_NAME = os.getenv('TABLE_NAME')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info(event)
29
Amazon Translate Developer Guide
Example Code
try:
# The Lambda function queries the Amazon DynamoDB table to check whether
# the review has already been translated. If the translated review
# is already stored in Amazon DynamoDB, the function returns it.
response = dynamodb.get_item(
TableName=TABLE_NAME,
Key={
'review_id': {
'N': review_id,
},
'language': {
'S': target_language,
},
}
)
logger.info(response)
if 'Item' in response:
return response['Item']['review']['S']
except Exception as e:
logger.error(response)
raise Exception("[ErrorMessage]: " + str(e))
try:
# The Lambda function calls the TranslateText operation and passes the
# review, the source language, and the target language to get the
# translated review.
result = translate.translate_text(Text=review,
SourceLanguageCode=source_language, TargetLanguageCode=target_language)
logging.info("Translation output: " + str(result))
except Exception as e:
logger.error(response)
raise Exception("[ErrorMessage]: " + str(e))
try:
# After the review is translated, the function stores it using
# the Amazon DynamoDB putItem operation. Subsequent requests
# for this translated review are returned from Amazon DynamoDB.
response = dynamodb.put_item(
TableName=TABLE_NAME,
Item={
'review_id': {
'N': review_id,
},
'language': {
'S': target_language,
},
'review': {
'S': result.get('TranslatedText')
}
}
)
logger.info(response)
except Exception as e:
logger.error(e)
raise Exception("[ErrorMessage]: " + str(e))
return result.get('TranslatedText')
else:
logger.error(e)
raise Exception("[ErrorMessage]: Invalid input ")
30
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Web Page
stack for the example. Update BUCKET_NAME to the name of the S3 bucket that contains the
example.zip file and then save it to a local directory as template.yaml.
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Resources: ReviewTranslate:
Type: 'AWS::Serverless::Function'
Properties:
Handler: example.lambda_handler
Runtime: python2.7
CodeUri:
Bucket: BUCKET_NAME
Key: example.zip
Policies:
- AWSLambdaFullAccess
- TranslateReadOnly
Environment:
Variables:
TABLE_NAME: !Ref ReviewTable
Tracing: "Active"
ReviewTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
- AttributeName: "review_id"
AttributeType: "N"
- AttributeName: "language"
AttributeType: "S"
KeySchema:
- AttributeName: "review_id"
KeyType: "HASH"
- AttributeName: "language"
KeyType: "RANGE"
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
• A function that reads data from the source Web page, separates it into HTML elements, and then calls
the second function to translate the element. At the end of the document, it writes the results to an
HTML file.
• A function that calls the Amazon Translate service to translate the contents of an HTML element.
1. Install and configure the AWS SDK for Java. For instructions for installing the SDK for Java, see Set
up the AWS SDK for Java.
2. Install the jsoup Java HTML parser. For instructions, see jsoup.
3. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
31
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Web Page
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43).
4. Set up the credentials needed to run the sample. For instructions, see Set up AWS Credentials and
Region for Development in the AWS SDK for Java Developer Guide.
5. Create a new project in your Java IDE and copy the source code.
6. Change the region and endpoint to the region where you want to run the Amazon Translate
operation. For a list of supported regions for Amazon Translate, see Guidelines and Limits (p. 50).
package com.amazonaws.translateweb;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.SystemPropertiesCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.translate.AmazonTranslateClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;
import com.amazonaws.AmazonServiceException;
import java.io.IOException;
import java.io.PrintWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
32
Amazon Translate Developer Guide
Using Amazon Translate to Translate a Web Page
try {
// Retrieve the HTML located at the URL
doc = Jsoup.connect(url).get();
33
Amazon Translate Developer Guide
Using Amazon Translate to Translate Large Documents
• The SentenceSegmenter class that is responsible for breaking the source string into individual
sentences. The sample uses the Java BreakIterator class.
• The main function that calls the Translate operation for each sentence in the source string. The
main function also handles authentication with Amazon Translate.
1. Install and configure the AWS SDK for Java. For instructions for installing the SDK for Java, see Set
up the AWS SDK for Java.
2. Create an IAM user with the minimum required permissions to run this example. For information
about creating an IAM user, see Creating an IAM User in Your AWS Account in the AWS Identity
and Access Management User Guide. For the required permissions policies, see Using Identity-Based
Policies (IAM Policies) for Amazon Translate (p. 43).
3. Set up the credentials needed to run the sample. For instructions, see Set up AWS Credentials and
Region for Development in the AWS SDK for Java Developer Guide.
4. Create a new project in your Java IDE and copy the source code.
5. Change the region to the region where you want to run the Amazon Translate operation. For a list of
supported regions for Amazon Translate, see Guidelines and Limits (p. 50).
6. Change the source and target languages to the languages to translate between.
7. Run the sample to see the translated text on standard output.
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.SystemPropertiesCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
34
Amazon Translate Developer Guide
Using Amazon Translate to Translate Large Documents
import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.translate.AmazonTranslateClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
class SentenceSegmenter {
public List<String> segment(final String text, final String lang) throws Exception {
List<String> res = new ArrayList<>();
BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(new
Locale(lang));
sentenceIterator.setText(text);
35
Amazon Translate Developer Guide
Using Signature Version 4 with Amazon Translate
Setting Up
To run the example, perform the following steps:
1. Install the AWS Command Line Interface (AWS CLI). The AWS SDK for Python (Boto) is included
when you install the AWS CLI. For instructions, see Step 2: Set Up the AWS Command Line Interface
(AWS CLI) (p. 7).
2. Create an AWS Identity and Access Management (IAM) user with the minimum required permission
policy to run this example. For information about creating an IAM user, see Creating an IAM User
in Your AWS Account in the AWS Identity and Access Management User Guide. For the required
permissions policies, see Using Identity-Based Policies (IAM Policies) for Amazon Translate (p. 43).
Record the user access key ID and the secret access key.
3. Place the access key ID and secret access key in environment variables named AWS_ACCESS_KEY
and AWS_SECRET_ACCESS_KEY, respectively. As a best practice, we recommend that you don't
embed credentials in code.
4. Create a new file on your computer, copy the code for the example (which you can find in the next
section), paste it into the file, and save the file with the extension .py.
5. In the code, replace region with the name of the AWS Region where you want to run the Amazon
Translate TranslateText operation. For a list of supported Regions, see AWS Regions and
Endpoints in the Amazon Web Services General Reference..
Code
The following is the complete code of the example Python program.
After creating request values such as the endpoint URL and the body of the request, the code does the
following:
36
Amazon Translate Developer Guide
Code
To run the example on your computer, copy the code to a Python file.
# The following functions derive keys for the request. For more information, see
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-
examples-python.
def sign(key, msg):
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
# Python can read the AWS access key from environment variables or the configuration file.
# In this example, keys are stored in environment variables. As a best practice, do not
# embed credentials in code.
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key is None or secret_key is None:
print 'No access key is available.'
sys.exit()
37
Amazon Translate Developer Guide
Code
date_stamp = t.strftime('%Y%m%d') # The date without time is used in the credential scope.
# Step 1: Define the verb (GET, POST, etc.), which you have already done.
# Step 2: Create a canonical URI. A canonical URI is the part of the URI from domain to
query.
# string (use '/' if no path)
canonical_uri = '/'
38
Amazon Translate Developer Guide
Code
# For Amazon Translate, the request can include any headers, but it must include "host,"
"x-amz-date,"
# "x-amz-target," "content-type," and "Authorization" headers. Except for the authorization
# header, the headers must be included in the canonical_headers and signed_headers values,
as
# noted earlier. Header order is not significant.
# Note: The Python 'requests' library automatically adds the 'host' header.
headers = {'Content-Type':content_type,
'X-Amz-Date':amz_date,
'X-Amz-Target':amz_target,
'Authorization':authorization_header}
39
Amazon Translate Developer Guide
Authentication
Authentication
You can access AWS as any of the following types of identities:
• AWS account root user – When you first create an AWS account, you begin with a single sign-in
identity that has complete access to all AWS services and resources in the account. This identity is
called the AWS account root user and is accessed by signing in with the email address and password
that you used to create the account. We strongly recommend that you do not use the root user for
your everyday tasks, even the administrative ones. Instead, adhere to the best practice of using the
root user only to create your first IAM user. Then securely lock away the root user credentials and use
them to perform only a few account and service management tasks.
• IAM user – An IAM user is an identity within your AWS account that has specific custom permissions
(for example, permissions to create a custom glossary in Amazon Translate). You can use an IAM user
name and password to sign in to secure AWS webpages like the AWS Management Console, AWS
Discussion Forums, or the AWS Support Center.
In addition to a user name and password, you can also generate access keys for each user. You can
use these keys when you access AWS services programmatically, either through one of the several
SDKs or by using the AWS Command Line Interface (CLI). The SDK and CLI tools use the access keys
to cryptographically sign your request. If you don’t use AWS tools, you must sign the request yourself.
Amazon Translate supports Signature Version 4, a protocol for authenticating inbound API requests.
For more information about authenticating requests, see Signature Version 4 Signing Process in the
AWS General Reference.
• IAM role – An IAM role is an IAM identity that you can create in your account that has specific
permissions. It is similar to an IAM user, but it is not associated with a specific person. An IAM role
enables you to obtain temporary access keys that can be used to access AWS services and resources.
IAM roles with temporary credentials are useful in the following situations:
• Federated user access – Instead of creating an IAM user, you can use existing user identities from
AWS Directory Service, your enterprise user directory, or a web identity provider. These are known as
federated users. AWS assigns a role to a federated user when access is requested through an identity
provider. For more information about federated users, see Federated Users and Roles in the IAM User
Guide.
40
Amazon Translate Developer Guide
Access Control
• AWS service access – You can use an IAM role in your account to grant an AWS service permissions
to access your account’s resources. For example, you can create a role that allows Amazon Redshift
to access an Amazon S3 bucket on your behalf and then load data from that bucket into an Amazon
Redshift cluster. For more information, see Creating a Role to Delegate Permissions to an AWS
Service in the IAM User Guide.
• Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials
for applications that are running on an EC2 instance and making AWS API requests. This is preferable
to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make
it available to all of its applications, you create an instance profile that is attached to the instance.
An instance profile contains the role and enables programs that are running on the EC2 instance
to get temporary credentials. For more information, see Using an IAM Role to Grant Permissions to
Applications Running on Amazon EC2 Instances in the IAM User Guide.
Access Control
You can have valid credentials to authenticate your requests. For example, you must have permissions to
call an Amazon Translate action.
The following sections describe how to manage permissions for Amazon Translate. We recommend that
you read the overview first.
• Overview of Managing Access Permissions to Your Amazon Translate Resources (p. 41)
• Using Identity-Based Policies (IAM Policies) for Amazon Translate (p. 43)
When granting permissions, you decide who is getting the permissions and the actions they get
permissions for.
Topics
• Managing Access to Actions (p. 41)
• Specifying Policy Elements: Resources, Actions, Effects, and Principals (p. 42)
• Specifying Conditions in a Policy (p. 43)
41
Amazon Translate Developer Guide
Specifying Policy Elements: Resources,
Actions, Effects, and Principals
Note
This section discusses using IAM in the context of Amazon Translate. It doesn't provide detailed
information about the IAM service. For complete IAM documentation, see What Is IAM? in the
IAM User Guide. For information about IAM policy syntax and descriptions, see AWS IAM Policy
Reference in the IAM User Guide.
Policies attached to an IAM identity are referred to as identity-based policies (IAM policies). Policies
attached to a resource are referred to as resource-based policies. Amazon Translate supports only
identity-based policies.
• Attach a permissions policy to a user or a group in your account – To grant a user or a group of users
permissions to call an Amazon Translate action, you can attach a permissions policy to a user or group
that the user belongs to.
• Attach a permissions policy to a role (grant cross-account permissions) – To grant cross-account
permissions, you can attach an identity-based permissions policy to an IAM role. For example, the
administrator in Account A can create a role to grant cross-account permissions to another AWS
account (for example, Account B) or an AWS service as follows:
1. Account A administrator creates an IAM role and attaches a permissions policy to the role that
grants permissions on resources in Account A.
2. Account A administrator attaches a trust policy to the role identifying Account B as the principal
who can assume the role.
3. Account B administrator can then delegate permissions to assume the role to any users in Account
B. Doing this allows users in Account B to create or access resources in Account A. If you want to
grant an AWS service permissions to assume the role, the principal in the trust policy can also be an
AWS service principal.
For more information about using IAM to delegate permissions, see Access Management in the IAM
User Guide.
For more information about using identity-based policies with Amazon Translate, see Using Identity-
Based Policies (IAM Policies) for Amazon Translate (p. 43). For more information about users, groups,
roles, and permissions, see Identities (Users, Groups, and Roles) in the IAM User Guide.
Resource-Based Policies
Other services, such as Lambda, support resource-based permissions policies. For example, you can
attach a policy to an S3 bucket to manage access permissions to that bucket. Amazon Translate doesn't
support resource-based policies.
• Resource – In a policy, you use an Amazon Resource Name (ARN) to identify the resource to which the
policy applies. For Amazon Translate, the resource is always *.
42
Amazon Translate Developer Guide
Specifying Conditions in a Policy
• Action – You use action keywords to identify operations that you want to allow or deny. For example,
depending on the specified Effect, translate:TranslateText either allows or denies the user
permissions to perform the Amazon Translate TranslateText operation.
• Effect – You specify the effect of the action that occurs when the user requests the specific action
—this can be either allow or deny. If you don't explicitly grant access to (allow) a resource, access is
implicitly denied. You can also explicitly deny access to a resource. You might do this to make sure that
a user cannot access the resource, even if a different policy grants access.
• Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the
implicit principal.
To learn more about IAM policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User
Guide.
For a table showing all of the Amazon Translate API actions, see Amazon Translate API Permissions:
Actions, Resources, and Conditions Reference (p. 44).
AWS provides a set of predefined condition keys for all AWS services that support IAM for access control.
For example, you can use the aws:userid condition key to require a specific AWS ID when requesting an
action. For more information and a complete list of AWS-wide keys, see Available Keys for Conditions in
the IAM User Guide.
Note
Condition keys are case-sensitive.
The following is the permissions policy required to use Amazon Translate and the Amazon Translate
console:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"translate:TranslateText",
"comprehend:DetectDominantLanguage"
43
Amazon Translate Developer Guide
Amazon Translate API Permissions Reference
],
"Resource": "*"
}
]
}
The policy has two statements. The first grants permissions to use the TranslateText action. The
second grants permissions to the Amazon Comprehend DetectDominantLanguage operation to
enable automatic language detection.
The policy doesn't specify the Principal element because you don't specify the principal who gets
the permissions in an identity-based policy. When you attach a policy to a user, the user is the implicit
principal. When you attach a permissions policy to an IAM role, the principal identified in the role's trust
policy gets the permissions.
For a table of the Amazon Translate API actions and the resources that they apply to, see Amazon
Translate API Permissions: Actions, Resources, and Conditions Reference (p. 44).
To express conditions, you can use AWS-wide condition keys in your Amazon Translate policies. For a
complete list of AWS-wide keys, see Available Keys in the IAM User Guide.
Note
To specify an action, use the translate: prefix followed by the API operation name, for
example, translate:TranslateText.
44
Amazon Translate Developer Guide
Amazon Translate provides preconfigured graphs that show you the most important metrics for your
solution. Each graph offers a window into your solution's performance. You can change the time range
that the graphs show to get different views of how your solution is performing over time.
You can also use Amazon CloudWatch to monitor Amazon Translate. With CloudWatch, you can
automate monitoring specific metrics for your solutions. You receive a notice whenever a metric
is outside of the thresholds that you set. You can also use the CloudWatch API to create a custom
monitoring application that is suitable for your needs. For more information, see What is Amazon
CloudWatch in the Amazon CloudWatch User Guide.
The following table describes each of the preconfigured graphs provided by Amazon Translate.
Graph Description
45
Amazon Translate Developer Guide
Graph Description
Character count
46
Amazon Translate Developer Guide
Monitoring with CloudWatch
• The metric dimension. A dimension is a set of name-value pairs that you use to identify a metric.
Amazon Translate has two dimensions:
• Operation
• Language pair
• The metric name, such as SuccessfulRequestCount or RequestCharacters. For a complete list
of metrics, see CloudWatch Metrics for Amazon Translate (p. 48).
You can get metrics for Amazon Translate with the AWS Management Console, the AWS CLI, or
the CloudWatch API. You can use the CloudWatch API through one of the Amazon AWS Software
Development Kits (SDKs) or the CloudWatch API tools.
The following table lists some common uses for CloudWatch metrics. These are suggestions to get you
started, not a comprehensive list.
Track the number of successful requests Monitor the sum statistic of the
SuccessfulRequestCount metric.
Know if my application has reached its maximum Monitor the sum statistic of the ThrottledCount
throughput metric.
Find the response time for my application Monitor the average statistic of the
ResponseTime metric.
Find the number of errors for my application Monitor the sum statistic of the
ServerErrorCount and UserErrorCount
metrics.
Find the number of billable characters Monitor the sum statistic of the CharacterCount
metric.
You must have the appropriate CloudWatch permissions to monitor Amazon Translate with CloudWatch
For more information, see Authentication and Access Control for Amazon CloudWatch in the Amazon
CloudWatch User Guide.
47
Amazon Translate Developer Guide
Viewing Amazon Translate Metrics
1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose Metrics, choose All Metrics, and then choose AWS/Translate.
3. Choose the dimension, choose a metric name, and choose Add to graph.
4. Choose a value for the date range. The metric count for the specified date range is displayed in the
graph.
Unit: Count
ServerErrorCount The number of server errors. The HTTP response code range for a server
error is 500 to 599.
Unit: Count
SuccessfulRequestCount The number of successful translation requests. The response code for a
successful request is 200 to 299.
48
Amazon Translate Developer Guide
CloudWatch Dimensions for Amazon Translate
Metric Description
Unit: Count
Unit: Count
UserErrorCount The number of user errors that occurred. The HTTP response code range
for a user error is 400 to 499.
Unit: Count
Dimension Description
LanguagePair Restricts the metrics to only those that contain the specified languages.
Operation Restricts the metrics to only those with the specified operation.
49
Amazon Translate Developer Guide
Supported Regions
Throttling
For information about throttling for Amazon Translate and to request a limit increase, see Amazon
Translate Limits in the Amazon Web Services General Reference.
Guidelines
Amazon Translate may store your content to continuously improve the quality of its analysis models. See
the Amazon Translate FAQ to learn more. To request that we delete content that may have been stored
by Amazon Translate, open a case with AWS Support.
Limits
Amazon Translate has the following limitations:
• The maximum document size is 5,000 bytes of UTF-8 characters per request.
50
Amazon Translate Developer Guide
New guide (p. 51) This is the first release of the November 29, 2017
Amazon Translate Developer
Guide.
51
Amazon Translate Developer Guide
HTTP Headers
API Reference
This section contains the API Reference documentation.
HTTP Headers
In addition to the usual HTTP headers, Amazon Translate operations have the required headers:
X-Amz-Target: AWSShineFrontendService_20170701.<operation>
The target Amazon Translate
operation. For example, use
AWSShineFrontendService_20170701.Tra
to call the TranslateText
operation.
Actions
The following actions are supported:
52
Amazon Translate Developer Guide
TranslateText
TranslateText
Translates input text from the source language to the target language. You can translate between
English (en) and one of the following languages, or between one of the following languages and English.
• Arabic (ar)
• Chinese (Simplified) (zh)
• Chinese (Traditional) (zh-TW)
• Czech (cs)
• French (fr)
• German (de)
• Italian (it)
• Japanese (ja)
• Portuguese (pt)
• Russian (ru)
• Spanish (es)
• Turkish (tr)
To have Amazon Translate determine the source language of your text, you can specify auto in the
SourceLanguageCode field. If you specify auto, Amazon Translate will call Amazon Comprehend to
determine the source language.
Request Syntax
{
"SourceLanguageCode": "string",
"TargetLanguageCode": "string",
"Text": "string"
}
Request Parameters
For information about the parameters that are common to all actions, see Common
Parameters (p. 57).
One of the supported language codes for the source text. If the TargetLanguageCode is not "en",
the SourceLanguageCode must be "en".
To have Amazon Translate determine the source language of your text, you can specify auto in the
SourceLanguageCode field. If you specify auto, Amazon Translate will call Amazon Comprehend
to determine the source language.
Type: String
Required: Yes
53
Amazon Translate Developer Guide
TranslateText
One of the supported language codes for the target text. If the SourceLanguageCode is not "en",
the TargetLanguageCode must be "en".
Type: String
Required: Yes
Text (p. 53)
The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your
character set, this may be fewer than 5,000 characters.
Type: String
Required: Yes
Response Syntax
{
"SourceLanguageCode": "string",
"TargetLanguageCode": "string",
"TranslatedText": "string"
}
Response Elements
If the action is successful, the service sends back an HTTP 200 response.
Type: String
Type: String
Type: String
54
Amazon Translate Developer Guide
TranslateText
Errors
For information about the errors that are common to all actions, see Common Errors (p. 56).
DetectedLanguageLowConfidenceException
The confidence that Amazon Comprehend accurately detected the source language is low. If a low
confidence level is acceptable for your application, you can use the language in the exception to call
Amazon Translate again. For more information, see the DetectDominantLanguage operation in the
Amazon Comprehend Developer Guide.
The size of the input text exceeds the length constraint for the Text field. Try again with a shorter
text.
The number of requests exceeds the limit. Resubmit your request later.
Amazon Translate cannot translate input text in the source language into this target language. For
more information, see Exception Handling (p. 4).
See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:
55
Amazon Translate Developer Guide
Data Types
Data Types
There are no separate data types in this API.
Common Errors
This section lists the errors common to the API actions of all AWS services. For errors specific to an API
action for this service, see the topic for that API action.
AccessDeniedException
The request processing has failed because of an unknown error, exception or failure.
The action or operation requested is invalid. Verify that the action is typed correctly.
The X.509 certificate or AWS access key ID provided does not exist in our records.
The AWS query string is malformed or does not adhere to AWS standards.
56
Amazon Translate Developer Guide
Common Parameters
The request must contain either a valid (registered) AWS access key ID or X.509 certificate.
The request reached the service more than 15 minutes after the date stamp on the request or more
than 15 minutes after the request expiration date (such as for pre-signed URLs), or the date stamp
on the request is more than 15 minutes in the future.
Common Parameters
The following list contains the parameters that all actions use for signing Signature Version 4 requests
with a query string. Any action-specific parameters are listed in the topic for that action. For more
information about Signature Version 4, see Signature Version 4 Signing Process in the Amazon Web
Services General Reference.
Action
Type: string
57
Amazon Translate Developer Guide
Common Parameters
Required: Yes
Version
The API version that the request is written for, expressed in the format YYYY-MM-DD.
Type: string
Required: Yes
X-Amz-Algorithm
The hash algorithm that you used to create the request signature.
Condition: Specify this parameter when you include authentication information in a query string
instead of in the HTTP authorization header.
Type: string
Required: Conditional
X-Amz-Credential
The credential scope value, which is a string that includes your access key, the date, the region you
are targeting, the service you are requesting, and a termination string ("aws4_request"). The value is
expressed in the following format: access_key/YYYYMMDD/region/service/aws4_request.
For more information, see Task 2: Create a String to Sign for Signature Version 4 in the Amazon Web
Services General Reference.
Condition: Specify this parameter when you include authentication information in a query string
instead of in the HTTP authorization header.
Type: string
Required: Conditional
X-Amz-Date
The date that is used to create the signature. The format must be ISO 8601 basic format
(YYYYMMDD'T'HHMMSS'Z'). For example, the following date time is a valid X-Amz-Date value:
20120325T120000Z.
Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for
signing requests. If the Date header is specified in the ISO 8601 basic format, X-Amz-Date is
not required. When X-Amz-Date is used, it always overrides the value of the Date header. For
more information, see Handling Dates in Signature Version 4 in the Amazon Web Services General
Reference.
Type: string
Required: Conditional
X-Amz-Security-Token
The temporary security token that was obtained through a call to AWS Security Token Service (AWS
STS). For a list of services that support temporary security credentials from AWS Security Token
Service, go to AWS Services That Work with IAM in the IAM User Guide.
Condition: If you're using temporary security credentials from the AWS Security Token Service, you
must include the security token.
Type: string
58
Amazon Translate Developer Guide
Common Parameters
Required: Conditional
X-Amz-Signature
Specifies the hex-encoded signature that was calculated from the string to sign and the derived
signing key.
Condition: Specify this parameter when you include authentication information in a query string
instead of in the HTTP authorization header.
Type: string
Required: Conditional
X-Amz-SignedHeaders
Specifies all the HTTP headers that were included as part of the canonical request. For more
information about specifying signed headers, see Task 1: Create a Canonical Request For Signature
Version 4 in the Amazon Web Services General Reference.
Condition: Specify this parameter when you include authentication information in a query string
instead of in the HTTP authorization header.
Type: string
Required: Conditional
59
Amazon Translate Developer Guide
AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.
60