1. Overview
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 see
- 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 languages
What you'll need
Survey
How will you use this tutorial?
How would you rate your experience with Python?
How would you rate your experience with using Google Cloud services?
2. Setup and requirements
Self-paced environment setup
- Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Gmail or Google Workspace account, you must create one.
- The Project name is the display name for this project's participants. It is a character string not used by Google APIs. You can update it at any time.
- The Project ID must be unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference the Project ID (it is typically identified as
PROJECT_ID
). If you don't like the generated ID, you may generate another random one. Alternatively, you can try your own and see if it's available. It cannot be changed after this step and will remain for the duration of the project. - For your information, there is a third value, a Project Number which some APIs use. Learn more about all three of these values in the documentation.
- Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab shouldn't cost much, if anything at all. To shut down resources so you don't incur billing beyond this tutorial, you can delete the resources you created or delete the whole project. New users of Google Cloud are eligible for the $300 USD 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 Google Cloud Console, click the Cloud Shell icon on the top right toolbar:
It should only take a few moments to provision and connect to the environment. When it is finished, you should see something like this:
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 codelab can be done within a browser. You do not need to install anything.
3. Enable the API
Before using the Translation API you must enable it. Enter the following command in the Cloud Shell:
gcloud services enable translate.googleapis.com
4. Authenticate API requests
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 ~/my-translation-sa-key.json
:
gcloud iam service-accounts keys create ~/my-translation-sa-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=~/my-translation-sa-key.json
For more information, see the Authentication overview page.
5. Install the client library
Install the client library:
pip install --upgrade google-cloud-translate
You should see something like this:
... Installing collected packages: google-cloud-translate Successfully installed google-cloud-translate-3.8.2
Now, you're ready to use the Translation API!
6. Start Interactive Python
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.9.2 (default, Feb 28 2021, 17:03:44) Type 'copyright', 'credits' or 'license' for more information IPython 8.5.0 -- An enhanced Interactive Python. Type '?' for help. In [1]:
7. List available languages
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: 112 ---------------------- 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.
8. Translate text
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.
9. Detect languages
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:6.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 multiple phrases. One of these, "Hola Mundo!", happens to be a Spanish phrase.
You should see the following output:
Confidence: 100.0% | Language: es | Hola Mundo! Confidence: 80.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.
10. Congratulations!
You learned how to use the Translation API using Python!
Clean up
Delete the downloaded credentials:
rm ~/my-translation-sa-key.json
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
- Cloud Translation documentation: https://cloud.google.com/translate/docs
- Python on Google Cloud: https://cloud.google.com/python/
- Cloud Client Libraries for Python: https://github.com/googleapis/google-cloud-python
License
This work is licensed under a Creative Commons Attribution 2.0 Generic License.