Translate strings (Basic edition)

Demonstrates translating strings by using Cloud Translation - Basic (v2).

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Translation quickstart using client libraries. For more information, see the Translation Go API reference documentation.

import (
	"context"
	"fmt"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func translateTextWithModel(targetLanguage, text, model string) (string, error) {
	// targetLanguage := "ja"
	// text := "The Go Gopher is cute"
	// model := "nmt"

	ctx := context.Background()

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

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

	resp, err := client.Translate(ctx, []string{text}, lang, &translate.Options{
		Model: model, // Either "nmt" or "base".
	})
	if err != nil {
		return "", fmt.Errorf("Translate: %v", err)
	}
	if len(resp) == 0 {
		return "", nil
	}
	return resp[0].Text, nil
}

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.

Translation translation =
    translate.translate(
        "Hola Mundo!",
        Translate.TranslateOption.sourceLanguage("es"),
        Translate.TranslateOption.targetLanguage("de"),
        // Use "base" for standard edition, "nmt" for the premium model.
        Translate.TranslateOption.model("nmt"));

System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());

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').v2;

// 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';
// const model = 'The model to use, e.g. nmt';

async function translateTextWithModel() {
  const options = {
    // The target language, e.g. "ru"
    to: target,
    // Make sure your project is on the allow list.
    // 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.
  let [translations] = await translate.translate(text, options);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateTextWithModel();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation quickstart using client libraries. For more information, see the Translation PHP API reference documentation.

use Google\Cloud\Translate\TranslateClient;

/** Uncomment and populate these variables in your code */
// $text = 'The text to translate.'
// $targetLanguage = 'ja';  // 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");

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.

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

    Make sure your project is allowlisted.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        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"]))

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.