Migrating to Translation v3

This page describes the major changes between Cloud Translation v2 and Cloud Translation v3beta1. It also provides some code examples to help you migrate your application. If you want to see only the new features in Cloud Translation v3beta1, like glossaries, see the introduction to v3.

Cloud Translation v3beta1 supports all of the features and models available in v2. However, the client libraries do not support client integration backwards compatibility. In other words, you must plan to migrate your applications to benefit from the Cloud Translation v3beta1 features.

If you are planning a new project, you should build your application with Cloud Translation v3beta1, to take advantage of the new features and service improvements. Cloud Translation v2 remains available, but does not support new features like glossaries, batch prediction, or model selection.

Major changes between v2 and v3

Cloud Translation v3beta1 has several differences from the v2 version.

Service accounts

Cloud Translation API v2 allowed you to use API keys to authenticate to Translation.

Cloud Translation v3beta1 has features that require customer-managed resources; these resources require IAM role and permissions management. Because of this, you cannot use API keys to authenticate to the service. Instead, you must use service accounts when authenticating to Translation.

IAM roles

Service accounts for authenticating to Translation previously did not need to have specialized IAM roles applied to them.

Cloud Translation v3beta1 has several IAM roles that you can assign to your service account for access to specific resources in your project. For example, if you want to use your service account to translate text, you would assign the roles/cloudtranslate.user role to it. See Introducing v3 for details about the available IAM roles.

Resources, projects, and locations

When you make some requests to Cloud Translation v3beta1, you must provide the name of the resources that you want to use. A resource is typically a qualified name that includes the project name and its location. You need to provide a resource name when specifying a translation model, using an AutoML model, or when calling a REST method.

For example, if your Google Cloud project has the name my-project and the location for the resource is us-central1, then the full name of your resources might look like the following:

projects/my-project/locations/us-central1/...

You also use the location name in the URLs that you send REST requests. The location specifies where the request is executed. For example, the URL that you send a getSupportedLanguages request might look like the following:

https://translation.googleapis.com/v3beta1/projects/my-project/locations/us-central1/supportedLanguages

Translation models

When you request a translation from Cloud Translation v3beta1, you must specify which translation model to use. You can use a custom AutoML Translation custom model, a Neural Machine Translation (NMT) general model, or a Phrase-Based Machine Translation (PBMT) general model.

Integrating with AutoML models requires that the service accounts that are used for translation requests have appropriate IAM permissions to access AutoML and general models, whether defined in your project or another project.

For more information about selecting a translation model, see translating text with Cloud Translation v3beta1.

Review the following steps to update your existing application from Cloud Translation v2 to Cloud Translation v3beta1.

  1. Take inventory of your Google Cloud projects, applications, and users that access the v2 API.
  2. Set up service accounts and authentication for your application. Review the material on IAM roles, paying attention to the AutoML, Storage, and Cloud Translation roles in particular.
  3. Enable Cloud Translation v3beta1 for your project. If you use AutoML models with Cloud Translation v3beta1, you must enable AutoML as well.
  4. Compare the changes between Cloud Translation v2 and Cloud Translation v3beta1
  5. Update your application or translation workflow to take advantage of new features. To integrate your application with AutoML and Cloud Storage, you must apply the appropriate IAM roles and permissions to your service accounts so that they can access your resources.
  6. Plan your translation request quota monitoring. Both versions of the API share the same daily and monthly quotas.
  7. Review any potential changes in billing.

API and client libraries differences

The following sections describe specific differences between calling the Cloud Translation API v2 and Cloud Translation v3beta1.

Importing the beta client libraries

Use the following code snippets to import the client libraries for Cloud Translation v3beta1.

Java

Add the following to your pom.xml file:

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.68.0</version>
</dependency>

Node.js

Add the following to your package.json file:

  "dependencies": {
    "@google-cloud/translate": "^3.0.0",
    "@google-cloud/automl": "^0.1.2"
  },

The following code snippet demonstrates how to construct the Cloud Translation v3beta1 version of the TranslationServiceClient.

const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

Python

Use the following to your requirements.txt file:
google-cloud-translate==1.4.0

The following code snippet demonstrates how to construct the Cloud Translation v3beta1 version of the TranslationServiceClient.

from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()

Translating text

With the previous version of Cloud Translation, to send a translation request to the API you would use the following code:

curl command

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'Hello world',
  'q': 'My name is Jeff',
  'target': 'de'
}" "https://translation.googleapis.com/language/translate/v2"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "data": {
    "translations": [
      {
        "translatedText": "Hallo Welt",
        "detectedSourceLanguage": "en"
      },
      {
        "translatedText": "Mein Name ist Jeff",
        "detectedSourceLanguage": "en"
      }
    ]
  }
}

Java

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

Translation translation = translate.translate("¡Hola Mundo!");
System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());

Node.js

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
console.log('Translations:');
translations.forEach((translation, i) => {
  console.log(`${text[i]} => (${target}) ${translation}`);
});

Python

"""Translates text into the target language.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(
    text, target_language=target)

print(u'Text: {}'.format(result['input']))
print(u'Translation: {}'.format(result['translatedText']))
print(u'Detected source language: {}'.format(
    result['detectedSourceLanguage']))

With Cloud Translation v3beta1, you need to provide your project ID and project location—typically either global or us-central1—when making a translateText request.

You can also explicitly specify a translation model or a glossary to use when translating the text. You can even ask to receive the response translation as either text/plain or text/html (the default value is text/html).

curl command

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H 'Content-Type: application/json' --data "{
     target_language_code: 'ru',
     contents: ['Dr. Watson, come here!']
}" "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global:translateText"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "translations": [
    {
      "translatedText": "Доктор Ватсон, иди сюда!",
      "detectedLanguageCode": "en"
    }
  ]
}

Java


/**
 * Translates a given text to a target language.
 *
 * @param projectId - Id of the project.
 * @param location - location name.
 * @param text - Text for translation.
 * @param sourceLanguageCode - Language code of text. e.g. "en"
 * @param targetLanguageCode - Language code for translation. e.g. "sr"
 */
static TranslateTextResponse translateText(
    String projectId,
    String location,
    String text,
    String sourceLanguageCode,
    String targetLanguageCode) {
  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();

    TranslateTextRequest translateTextRequest =
        TranslateTextRequest.newBuilder()
            .setParent(locationName.toString())
            .setMimeType("text/plain")
            .setSourceLanguageCode(sourceLanguageCode)
            .setTargetLanguageCode(targetLanguageCode)
            .addContents(text)
            .build();

    // Call the API
    TranslateTextResponse response = translationServiceClient.translateText(translateTextRequest);
    System.out.format(
        "Translated Text: %s", response.getTranslationsList().get(0).getTranslatedText());
    return response;

  } catch (Exception e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';
// const text = 'text to translate';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateText() {
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en-US',
    targetLanguageCode: 'sr-Latn',
  };

  // Run request
  const [response] = await translationClient.translateText(request);

  for (const translation of response.translations) {
    console.log(`Translation: ${translation.translatedText}`);
  }
}

translateText();

Python

from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()

# project_id = YOUR_PROJECT_ID
# text = 'Text you wish to translate'
location = 'global'

parent = client.location_path(project_id, location)

response = client.translate_text(
    parent=parent,
    contents=[text],
    mime_type='text/plain',  # mime types: text/plain, text/html
    source_language_code='en-US',
    target_language_code='sr-Latn')

for translation in response.translations:
    print('Translated Text: {}'.format(translation))

Discovering supported languages

With the previous version of Cloud Translation, to get a list of languages supported by the API you would use the following code:

curl command

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    "https://translation.googleapis.com/language/translate/v2/languages"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "data": {
    "languages": [
      {
        "language": "af"
      },
      {
        "language": "am"
      },
      {
        "language": "ar"
      },
      {
        "language": "az"
      },
      ...
    ]
  }
}

Java

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<Language> languages = translate.listSupportedLanguages();

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

// Lists available translation language with their names in English (the default).
const [languages] = await translate.getLanguages();

console.log('Languages:');
languages.forEach(language => console.log(language));

Python

"""Lists all available languages."""
translate_client = translate.Client()

results = translate_client.get_languages()

for language in results:
    print(u'{name} ({language})'.format(**language))

With Cloud Translation v3beta1, you need to provide your project ID and project location—typically either global or us-central1—when making a getSupportedLanguages request.

curl command

curl -X GET \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global/supportedLanguages"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "languages": [
    {
      "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "az",
      "supportSource": true,
      "supportTarget": true
    },
    ...
}

Java

static SupportedLanguages listSupportedLanguages(String projectId, String location) {
  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();
    GetSupportedLanguagesRequest getSupportedLanguagesRequest =
        GetSupportedLanguagesRequest.newBuilder().setParent(locationName.toString()).build();

    // Call the API
    ApiFuture<SupportedLanguages> future =
        translationServiceClient
            .getSupportedLanguagesCallable()
            .futureCall(getSupportedLanguagesRequest);

    SupportedLanguages response = future.get();
    List<SupportedLanguage> languages = response.getLanguagesList();
    for (SupportedLanguage language : languages) {
      System.out.printf("Code: %s\n", language.getLanguageCode());
    }

    return response;

  } catch (Exception e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function listLanguages() {
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
  };

  // Run request
  const [response] = await translationClient.getSupportedLanguages(request);

  console.log(`Supported languages:`);
  for (const language of response.languages) {
    console.log(`Language Code: ${language.languageCode}`);
  }
}

listLanguages();

Python

from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()

# project_id = YOUR_PROJECT_ID
location = 'global'

parent = client.location_path(project_id, location)

response = client.get_supported_languages(parent)

print('Supported Languages:')
for language in response.languages:
    print('Language Code: {}'.format(language.language_code))

Detecting language

With the previous version of Cloud Translation, to detect the source language present in text, you would use the following code:

curl command

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'q': 'Omnia Gallia est divisa in tres partes',
}" "https://translation.googleapis.com/language/translate/v2/detect"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "data": {
    "detections": [
      [
        {
          "confidence": 0.93554825,
          "isReliable": false,
          "language": "la"
        }
      ]
    ]
  }

Java

Before trying this sample, follow the Java setup instructions in the Translation Quickstart Using Client Libraries . For more information, see the Translation Java API reference documentation .

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<String> texts = new LinkedList<>();
texts.add("Hello, World!");
texts.add("¡Hola Mundo!");
List<Detection> detections = translate.detect(texts);

System.out.println("Language(s) detected:");
for (Detection detection : detections) {
  System.out.printf("\t%s\n", detection);
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation Quickstart Using Client Libraries . For more information, see the Translation Node.js API reference documentation .

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate');

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const text = 'The text for which to detect language, e.g. Hello, world!';

// Detects the language. "text" can be a string for detecting the language of
// a single piece of text, or an array of strings for detecting the languages
// of multiple texts.
let [detections] = await translate.detect(text);
detections = Array.isArray(detections) ? detections : [detections];
console.log('Detections:');
detections.forEach(detection => {
  console.log(`${detection.input} => ${detection.language}`);
});

Python

Before trying this sample, follow the Python setup instructions in the Translation Quickstart Using Client Libraries . For more information, see the Translation Python API reference documentation .

"""Detects the text's language."""
translate_client = translate.Client()

# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.detect_language(text)

print('Text: {}'.format(text))
print('Confidence: {}'.format(result['confidence']))
print('Language: {}'.format(result['language']))

With Cloud Translation v3beta1, you need to provide your project ID and project location typically—either global or us-central1—when making a detectLanguage request.

You can also specify a model to use when sending a detectLanguage request, although it isn't required.

Additionally, you can configure the response that you get from Cloud Translation v3beta1 so that you can receive different MIME types. For example, you can request text/html as well as text/plain (the default value is text/html).

curl command

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H 'Content-Type: application/json' --data "{
     mimeType: 'text/plain',
     content: 'Omnia Gallia est divisa in tres partes'
}" "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global:detectLanguage"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

{
  "languages": [
    {
      "languageCode": "la",
      "confidence": 0.93554825
    }
  ]
}

Java

static DetectLanguageResponse detectLanguageOfText(
    String projectId, String location, String text) {

  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();
    DetectLanguageRequest detectLanguageRequest =
        DetectLanguageRequest.newBuilder()
            .setParent(locationName.toString())
            .setMimeType("text/plain")
            .setContent(text)
            .build();

    // Call the API
    DetectLanguageResponse response =
        translationServiceClient.detectLanguage(detectLanguageRequest);
    System.out.format("Detected Language Code: %s", response.getLanguages(0).getLanguageCode());
    return response;

  } catch (Exception e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1;

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function detectLanguage() {
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
    content: text,
  };

  // Run request
  const [response] = await translationClient.detectLanguage(request);

  console.log(`Detected Languages:`);
  for (const language of response.languages) {
    console.log(`Language Code: ${language.languageCode}`);
    console.log(`Confidence: ${language.confidence}`);
  }
}

detectLanguage();

Python

from google.cloud import translate_v3beta1 as translate
client = translate.TranslationServiceClient()

# project_id = YOUR_PROJECT_ID
# text = 'Text you wish to translate'
location = 'global'

parent = client.location_path(project_id, location)

response = client.detect_language(
    parent=parent,
    content=text,
    mime_type='text/plain')  # mime types: text/plain, text/html

for language in response.languages:
    print('Language Code: {} (Confidence: {})'.format(
        language.language_code,
        language.confidence))

Var denne siden nyttig? Si fra hva du synes:

Send tilbakemelding om ...

Cloud Translation
Trenger du hjelp? Gå til brukerstøttesiden vår.