SnipHub.net

Your new source code snippet website!

Amazon Translate

In last two articles about Amazon I showed how to use Amazon Comprehend to make computer understand your text. Amazon can do even more: it can translate texts between languages. Amazon Translate API is very similar to Amazon Comprehend API, so let’s start!

Prerequisites

Translating

Let’s start with standard snippets that initialize Amazon APIs:

val region = "eu-central-1"

val credentials = DefaultAWSCredentialsProviderChain.getInstance()

val translate = AmazonTranslateClientBuilder.standard()
        .withCredentials(credentials)
        .withRegion(region)
        .build()

Now we can translate text from English to let’s say Polish:

val original = "SnipHub is an awesome website I read often!"
        val translatedPl = translate.translateText(TranslateTextRequest()
                .withText(original)
                .withSourceLanguageCode("en")
                .withTargetLanguageCode("pl")).translatedText

It gives SniPhuB to świetna strona często czytam! - there are 2 mistakes in this translation, but it’s not bad.

Often a good test for a translator is to translate back:

val translatedEn = translate.translateText(TranslateTextRequest()
                .withText(translatedPl)
                .withSourceLanguageCode("pl")
                .withTargetLanguageCode("en")).translatedText

We get SniPhuB is a great site I read often!, it has an error and differs from the original but still it’s not bad.

Further reading

Books and videos

Have a question or problem? Create a GitHub issue