Translating Text

This document describes how to use the Cloud Translation API to translate text.

Translating text

This section demonstrates a few ways to request translations. To run the HTTP examples, copy the URL and paste it into your browser. Don't forget to replace YOUR_API_KEY with your actual API key.

The URL for an HTTP request has the following format:

https://translation.googleapis.com/language/translate/v2

Three query parameters are required with each translation request:

  • Target language: Use the target parameter to specify the language you want to translate into.
  • Source text string: Use the q parameter to specify each text string to translate.
  • API key: Use the key parameter to identify your application. If you are using OAuth 2.0 service account credentials (recommended), do not supply this parameter.

All other query parameters are optional. The URL for GET requests, including parameters, must be less than 2K characters.

Translating input strings

Protocol

Use a separate q parameter for each string. This example HTTP POST request sends two strings for translation:

 POST https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY
{
  'q': 'Hello world',
  'q': 'My name is Jeff',
  'target': 'de'
}

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"
      }
    ]
  }
}

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

C#

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

static void Translate(string text, string targetLanguageCode,
    string sourceLanguageCode)
{
    TranslationClient client = TranslationClient.Create();
    var response = client.TranslateText(text, targetLanguageCode,
        sourceLanguageCode);
    Console.WriteLine(response.TranslatedText);
}

Go

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

func translateText(targetLanguage, text string) (string, error) {
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", err
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return "", err
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", err
	}
	return resp[0].Text, nil
}

Java

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

public static void translateText(String sourceText, PrintStream out) {
  Translate translate = createTranslateService();
  Translation translation = translate.translate(sourceText);
  out.printf("Source Text:\n\t%s\n", sourceText);
  out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());
}

Node.js

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

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

// Instantiates a client
const translate = Translate();

// The text to translate, e.g. "Hello, world!"
// const text = 'Hello, world!';

// The target language, e.g. "ru"
// const target = '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.
translate.translate(text, target)
  .then((results) => {
    let translations = results[0];
    translations = Array.isArray(translations) ? translations : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate."
// $targetLanguage = 'ja';  // Which language to translate to?

$translate = new TranslateClient();
$result = $translate->translate($text, [
    'target' => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");

Python

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

def translate_text(target, text):
    """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']))

Ruby

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

Specifying a model

By default, when you make a translation request to the Google Cloud Translation API, your text is translated using the Neural Machine Translation (NMT) model. If the NMT model is not supported for the requested language translation pair, then the Phrase-Based Machine Translation (PBMT) model is used.

Comparing models

The NMT model can provide improved translation for longer and more complex content. For example, consider the following request:

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
}

Because no model is specified in the request, and the translation language pair of English to German is supported by the NMT model, the request is translated using the nmt model. The following is returned in the response's translations field:

"translatedText": "Fangen wir also von neuem an - auf beiden Seiten erinnern wir
                   uns, daß die Höflichkeit kein Zeichen der Schwäche ist und
                   die Aufrichtigkeit immer unter Beweis gestellt wird. Lasst
                   uns nie aus Furcht verhandeln. Aber lassen Sie uns niemals
                   Angst haben, zu verhandeln.",
"detectedSourceLanguage": "en",
"model": "nmt"

Alternatively, you can specifically request that the text be translated using the base (PBMT) model.

{
  'q': 'So let us begin anew--remembering on both sides that civility is not a
        sign of weakness, and sincerity is always subject to proof. Let us never
        negotiate out of fear. But let us never fear to negotiate.',
  'target': 'de',
  'model': 'base',
}

Using the base model returns the following result in the response's translations field, which differs from the translation using the nmt model.

"translatedText": "Lassen Sie uns also neu beginnen - auf beiden Seiten nicht
                   vergessen, dass Zivilität ist kein Zeichen von Schwäche, und
                   Aufrichtigkeit ist immer unter Beweis. Lassen Sie uns nie aus
                   Angst verhandeln. Aber lassen Sie uns nie zu verhandeln
                   fürchten.",
"detectedSourceLanguage": "en",
"model": "base"

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 within client library code.

C#

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

static void TranslateWithModel(string text,
    string targetLanguageCode, string sourceLanguageCode,
    TranslationModel model)
{
    TranslationClient client = TranslationClient.Create();
    var response = client.TranslateText(text,
        targetLanguageCode, sourceLanguageCode, model);
    Console.WriteLine("Model: {0}", response.Model);
    Console.WriteLine(response.TranslatedText);
}

Node.js

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

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

// Instantiates a client
const translate = Translate();

// The text to translate, e.g. "Hello, world!"
// const text = 'Hello, world!';

// The target language, e.g. "ru"
// const target = 'ru';

// The model to use, e.g. "nmt"
// const model = 'nmt';

const options = {
  // The target language, e.g. "ru"
  to: target,
  // Make sure your project is whitelisted.
  // Possible values are "base" and "nmt"
  model: model
};

// 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.
translate.translate(text, options)
  .then((results) => {
    let translations = results[0];
    translations = Array.isArray(translations) ? translations : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

Python

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

def translate_text_with_model(target, text, model=translate.NMT):
    """Translates text into the target language.

    Make sure your project is whitelisted.

    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, model=model)

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

PHP

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

use Google\Cloud\Translate\TranslateClient;

// $text = 'The text to translate.';
// $targetLanguage = 'ja';  // Which language to translate to?
// $model = 'nmt';  // "base" for standard edition, "nmt" for premium

$translate = new TranslateClient();
$result = $translate->translate($text, [
    'target' => $targetLanguage,
    'model'  => $model,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
print("Model: $result[model]\n");

Java

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

public static void translateTextWithOptionsAndModel(
    String sourceText,
    String sourceLang,
    String targetLang,
    PrintStream out) {

  Translate translate = createTranslateService();
  TranslateOption srcLang = TranslateOption.sourceLanguage(sourceLang);
  TranslateOption tgtLang = TranslateOption.targetLanguage(targetLang);

  // Use translate `model` parameter with `base` and `nmt` options.
  TranslateOption model = TranslateOption.model("nmt");

  Translation translation = translate.translate(sourceText, srcLang, tgtLang, model);
  out.printf("Source Text:\n\tLang: %s, Text: %s\n", sourceLang, sourceText);
  out.printf("TranslatedText:\n\tLang: %s, Text: %s\n", targetLang,
      translation.getTranslatedText());
}

Ruby

For more on installing and creating a Cloud Translation API client, refer to Cloud Translation API Client Libraries.

# project_id    = "Your Google Cloud project ID"
# text          = "The text you would like to translate"
# language_code = "The ISO 639-1 code of language to translate to, eg. 'en'"

require "google/cloud/translate"

translate   = Google::Cloud::Translate.new project: project_id
translation = translate.translate text, to: language_code, model: "nmt"

puts "Translated '#{text}' to '#{translation.text.inspect}'"
puts "Original language: #{translation.from} translated to: #{translation.to}"

Feedback geben zu...

Google Cloud Translation API Documentation