Translating text (v3beta1)

Cloud Translation v3beta1 introduces support for translating text using custom AutoML Translation models, and for creating glossaries to ensure that the Cloud Translation API translates a customer's domain-specific terminology correctly.

Before you can use Cloud Translation v3, you enable the AutoML API (automl.googleapis.com) if you want to use AutoML custom models for your project. If you are an existing Cloud Translation API user, see to our migration guide. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Quickstart. If you plan to use a glossary or the batch features, you also need to create a Google Cloud Storage bucket and grant your service account access to it.

Comparing models

When you request translation from the Cloud Translation API v3, you can specify which translation model to use. If no model is specified the nmt model is used if the language pair is supported, otherwise the PBMT model is used.

Model Best fit Examples
Neural Machine Translation (NMT) model

General text use cases such as common website content that is not specific to a domain, for example. news articles.

News articles, Social media, Chat applications, Reviews

Phrase-Based Machine Translation (PBMT) model NMT generally results in better quality translations. PBMT might be used by default if the NMT model doesn't exist for a language pair. Languages (pull from delta between NMT and PBMT)
AutoML Translation model Domain specific text. Customers provide training data specific to their use cases, for given language pairs to customize Google's base model for the domain purpose. Financial News, technical documents, any text that uses terms and jargon unique to that field.

You specify the translation model using its model ID. For the general Google models, the model IDs are general/nmt for the NMT model and general/base for the PBMT model. See the next section for information about AutoML Translation model IDs.

Translating text

The input text can be plain text or HTML. Cloud Translation API does not translate any HTML tags in the input, only text that appears between the tags. The output retains the (untranslated) HTML tags, with the translated text between the tags to the extent possible due to differences between the source and target languages. The order of HTML tags in the output may differ from the order in the input text due to word order changes in the translation.

Translating input strings

This section demonstrates a few ways to request translations from the https://translation.googleapis.com/v3beta1/projects/project-id/locations/global:translateText URL.

curl command

To detect the language of some text, make a POST request and provide JSON in the request body that identifies the language to translate from (source_language_code), the language to translate to (target_language_code), and the text to translate (contents). You can provide multiple strings of text to translate by including them in your JSON (see example). You identify your source and target languages by using their iso-639-1 codes.

The following shows an example of a POST request using curl. The example uses the access token for a service account set up for the project using the Google Cloud Platform Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Quickstart.


curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H 'Content-Type: application/json' --data "{
     source_language_code: 'en',
     target_language_code: 'ru',
     contents: ['Dr. Watson, come here!', 'Bring me some coffee!']
}" "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": "Доктор Ватсон, иди сюда!",
    },
    {
      "translatedText": "Принеси мне кофе!",
    }
  ]
}

The translations array contains two translatedText fields with translations provided in the requested target language (ru: Russian). The translations are listed in the same order as the corresponding source array in the request.

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 .

/**
 * 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

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 .

/**
 * 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

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 .

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))

Translating text using an AutoML Translation custom model

curl command

This example translates text using an AutoML Translation model whose model ID is TRL1395675701985363739. You can get the model ID for an AutoML Translation model from the list of models in the AutoML Translation UI or from the API response when you train the model. The location location-id in the request must match the location-id of the AutoML model.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
         source_language_code: 'en',
         target_language_code: 'ru',
         model: 'projects/project-id/locations/us-central1/models/TRL1395675701985363739',
         contents: 'Dr. Watson, please discard your trash. You\'ve shared unsolicited email with me. \
                   Let\'s talk about spam and importance ranking in a confidential mode.',
     }" "https://translation.googleapis.com/v3beta1/projects/project-id/locations/us-central1:translateText"
If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:
{
  "translation": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора.
    Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о
    спаме и важности рейтинга в конфиденциальном режиме.",
    "model": "projects/project-id/locations/us-central1/models/TRL1395675701985363739"
  }
}

Using the model parameter

You can specify which model to use for translation by using the model query parameter. Specify base to use the PBMT model, and nmt to use the NMT model. If you specify the NMT model in your request and the requested language translation pair is not supported for the NMT model, then the PBMT model is used.

The following sample shows how to use the model parameter in a translate request, with the example showing the selection of base.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H 'Content-Type: application/json' --data "{
     model: 'projects/project-id/locations/global/models/general/base',
     source_language_code: 'en',
     target_language_code: 'de',
     contents: ['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": "Komm her!",
      "model": "projects/project-id/locations/global/models/general/base"
    }
  ]
}
Just change /models/general/base to /models/general/nmt to use the general NMT model.

Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице
Cloud Translation
Нужна помощь? Обратитесь в службу поддержки.