Using the Translation API with Python

The Translation API provides a simple, programmatic interface for dynamically translating an arbitrary string into any supported language using state-of-the-art Neural Machine Translation. It can also be used to detect a language in cases where the source language is unknown.

In this tutorial, you'll use the Translation API with Python. Concepts covered include how to list available languages, translate text, and detect the language of a given text.

What you'll learn

  • How to use Cloud Shell
  • How to enable the Translation API
  • How to authenticate API requests
  • How to install the Python client library
  • How to list available languages
  • How to translate text
  • How to detect language

What you'll need

  • A Google Cloud Project
  • A Browser, such as Chrome or Firefox
  • Familiarity using Python 3

Survey

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would you rate your experience with Python?

Novice Intermediate Proficient

How would you rate your experience with using Google Cloud services?

Novice Intermediate Proficient

Self-paced environment setup

  1. Sign in to Cloud Console and create a new project or reuse an existing one. (If you don't already have a Gmail or G Suite account, you must create one.)

WvZ4Lcm6k-4AOA_v1j9HE6MO5-TJvI3TlGp4PNpqf_gbPLt9pq3c0ZiMOtT4bZZ1urP6tVOzAsTdpQ9OLYDcvvhpbdHcqqLRoQ7JFy-tCyKyE8gn9BtOwo8T3CLjOoTVL17Czok8-A

RQVrJ6Mj_SCQFipYRkdxqlWmokfg9D05dd5oq8qWaF_ci584t_xHW6M5-8fGR5i5JIUkx2r1G_5Ue630biVrQmSLKf_s2OiU9dnc4PZD1VnWSJf2AzZwzZP8UYiI__zqurLdj_7Qvw

ARsF00OMeFtN4MASqu6GKhjNAf8ANuL29fBrkJ6qnh3DrxdXFAftS-klvH5WNZ8XculywaNSnNZk3WoUP0d5UBQstpHXKgiWGJ3Wox3MVsL5TVhhSWt66U8yBfZBmNRksXds-_6wdA

Remember the project ID, a unique name across all Google Cloud projects (the name above has already been taken and will not work for you, sorry!). It will be referred to later in this codelab as PROJECT_ID.

  1. Next, you'll need to enable billing in Cloud Console in order to use Google Cloud resources.

Running through this codelab shouldn't cost much, if anything at all. Be sure to to follow any instructions in the "Cleaning up" section which advises you how to shut down resources so you don't incur billing beyond this tutorial. New users of Google Cloud are eligible for the $300USD Free Trial program.

Start Cloud Shell

While Google Cloud can be operated remotely from your laptop, in this tutorial you will be using Cloud Shell, a command line environment running in the Cloud.

While Google Cloud can be operated remotely from your laptop, in this codelab you will be using Google Cloud Shell, a command line environment running in the Cloud.

From the GCP Console click the Cloud Shell icon on the top right toolbar:

GhOXO4NcPKadwbYghSkf8Na2PFnFM5jcK6xFgfiVlYWPfyBl-WJt2M9tnMCMMLwp-kRqOP0C-mpKDhajdW_zJ0CoTT-gfwAR2FlGlFx-3EV7atSx5N-z2uiexzc9F0UX2q3SmNumiA

It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:

J7h_nML9i5ESVEhywWx0jlpMjCvgD5tu7IAqishPFyj36lZrhvMIYUnssC-KvRXc5nKH9JO_N60xxE6Fxm-WleTK4ShBjcEGdAz_CFn2V8EQmJ5h3Zs_1xydj8MoOjX3skAQrCCiJA

This virtual machine is loaded with all the development tools you'll need. It offers a persistent 5GB home directory, and runs on Google Cloud, greatly enhancing network performance and authentication. All of your work in this lab can be done with simply a browser.

Before using the Translation API you must enable it. Enter the following command in the Cloud Shell:

gcloud services enable translate.googleapis.com

In order to make requests to the Translation API you need to use a Service Account. A service account belongs to your project. Service accounts allow the Google Client Python library to make Translation API requests. Like any other user account, a service account is represented by an email address. In this section you'll use the Cloud SDK to create and authenticate a service account.

First, set an environment variable with your PROJECT_ID which you'll use throughout this tutorial:

export PROJECT_ID=$(gcloud config get-value core/project)

Test that it was set correctly:

echo $PROJECT_ID

yourproject-XXXX

Create a new service account to access the Translation API:

gcloud iam service-accounts create my-translation-sa \
  --display-name "my translation service account"

Grant your service account the Cloud Translation API User role.

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:my-translation-sa@${PROJECT_ID}.iam.gserviceaccount.com \
  --role roles/cloudtranslate.user

Create credentials that your Python code will use to log in as your new service account. The credentials are saved as a JSON file ~/key.json:

gcloud iam service-accounts keys create ~/key.json \
  --iam-account my-translation-sa@${PROJECT_ID}.iam.gserviceaccount.com

Finally, set the GOOGLE_APPLICATION_CREDENTIALS environment variable. This variable will let the Translation API Python library find your credentials. The environment variable should be set to the full path of the credentials JSON file you` created:

export GOOGLE_APPLICATION_CREDENTIALS=~/key.json

For more information, see the Authentication overview page.

Install the client library:

pip3 install --user --upgrade google-cloud-translate

You should see something like this:

...
Installing collected packages: google-cloud-translate
Successfully installed google-cloud-translate-3.0.1

Now, you're ready to use the Translation API!

In this tutorial, you'll use an interactive Python interpreter called IPython. Start a session by running ipython in Cloud Shell. This command runs the Python interpreter in an interactive session.

ipython

You should see something like this:

Python 3.7.3 (default, Jul 25 2020, 13:03:44)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

In this section, you'll list all available languages in the Translation API.

To list available languages, copy the following code into your IPython session:

from os import environ

from google.cloud import translate

project_id = environ.get("PROJECT_ID", "")
assert project_id
parent = f"projects/{project_id}"
client = translate.TranslationServiceClient()

response = client.get_supported_languages(parent=parent, display_language_code="en")
languages = response.languages

print(f" Languages: {len(languages)} ".center(60, "-"))
for language in languages:
    print(f"{language.language_code}\t{language.display_name}")

Take a minute or two to study the code*.* Note that you're listing the language names in English but it can be listed in any language by swapping out "en" with another language code.

You should see the following output:

---------------------- Languages: 111 ----------------------
af      Afrikaans
sq      Albanian
am      Amharic
ar      Arabic
hy      Armenian
...
cy      Welsh
xh      Xhosa
yi      Yiddish
yo      Yoruba
zu      Zulu

Summary

In this step, you were able to list all available languages in the Translation API. You can find the complete list of supported languages on the Language Support page.

You can use the Translate API to translate text from one language to another. Text is translated using the Neural Machine Translation (NMT) model. If the NMT model is not supported for the requested language translation pair, the Phrase-Based Machine Translation (PBMT) model is used. For more info on Google Translate and its translation models, see the NMT announcement post.

To translate text, copy the following code into your IPython session:

from os import environ

from google.cloud import translate

project_id = environ.get("PROJECT_ID", "")
assert project_id
parent = f"projects/{project_id}"
client = translate.TranslationServiceClient()

sample_text = "Hello world!"
target_language_code = "tr"

response = client.translate_text(
    contents=[sample_text],
    target_language_code=target_language_code,
    parent=parent,
)

for translation in response.translations:
    print(translation.translated_text)

Take a minute or two to study the code. It translates the text "Hello World" from English to Turkish*.*

You should see the following output:

Selam Dünya!

Summary

In this step, you were able to use the Translation API to translate text from English to Turkish. Read more about Translating text.

You can use the Translate API to also detect the language of a text string.

To detect language, copy the following code into your IPython session:

from os import environ

from google.cloud import translate

project_id = environ.get("PROJECT_ID", "")
assert project_id
parent = f"projects/{project_id}"
client = translate.TranslationServiceClient()


def detect_language(text):
    response = client.detect_language(parent=parent, content=text)

    for languages in response.languages:
        confidence = languages.confidence
        language_code = languages.language_code
        print(
            f"Confidence: {confidence:5.1%}",
            f"Language: {language_code}",
            text,
            sep=" | ",
        )


sentences = (
    "Hola Mundo!",
    "Hallo Welt!",
    "Bonjour le Monde !",
)
for sentence in sentences:
    detect_language(sentence)

Take a minute or two to study the code. It detects the language of the text Hola Mundo!" which happens to be a Spanish phrase*.*

You should see the following output:

Confidence: 100.0% | Language: es | Hola Mundo!
Confidence: 100.0% | Language: de | Hallo Welt!
Confidence: 100.0% | Language: fr | Bonjour le Monde !

Summary

In this step, you were able to detect the language of a piece of text using the Translation API. Read more about Detecting language.

You learned how to use the Translation API using Python!

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial:

  • In the Cloud Console, go to the Manage resources page.
  • In the project list, select your project then click Delete.
  • In the dialog, type the project ID and then click Shut down to delete the project.

Learn more

License

This work is licensed under a Creative Commons Attribution 2.0 Generic License.