Migrating to Translation Advanced

This page describes the major changes between the Cloud Translation - Basic and the Cloud Translation - Advanced. It also provides some code examples to help you migrate your application. If you want to see only the features in Cloud Translation - Advanced, like glossaries, see the Introducing Cloud Translation - Advanced.

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

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

Major changes between Basic and Advanced

Cloud Translation - Advanced has several differences from the Basic version.

Service accounts

Cloud Translation - Basic allows you to use API keys to authenticate to Translation.

Cloud Translation - Advanced 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 - Advanced 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 Cloud Translation - Advanced for details about the available IAM roles.

Resources, projects, and locations

When you make some requests to Cloud Translation - Advanced, 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 must 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/v3/projects/my-project/locations/us-central1/supportedLanguages

Translation models

When you request a translation from Cloud Translation - Advanced, you can 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, see Translating text.

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 - Advanced.

Review the following steps to update your existing application from Cloud Translation - Basic to Cloud Translation - Advanced.

  1. Take inventory of your Google Cloud projects, applications, and users that access the Basic 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 - Advanced for your project. If you use AutoML models with the Cloud Translation - Advanced, you must enable AutoML as well.
  4. Compare the changes between Cloud Translation - Basic and Cloud Translation - Advanced
  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 - Basic and Cloud Translation - Advanced.

Importing the Cloud Translation - Advanced client libraries

To import the client libraries for Cloud Translation - Advanced, use the following code.

C#

nuget install Google.Cloud.Translate.V3 -Pre

Go

go get -u cloud.google.com/go/translate/apiv3

Java

If you are using Maven, add the following to your pom.xml file:
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>4.1.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
  </dependency>
</dependencies>
If you are using Gradle, add the following to your dependencies:
compile 'com.google.cloud:google-cloud-translate:1.94.3'
If you are using sbt, add the following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "1.94.3"

If you're using IntelliJ or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more on setting up your Node.js development environment, refer to the Node.js Development Environment Setup Guide.

npm install --save @google-cloud/translate

PHP

composer install google/cloud-translate

Python

For more on setting up your Python development environment, refer to the Python Development Environment Setup Guide.

pip install --upgrade google-cloud-translate

Ruby

For more on setting up your Ruby development environment, refer to the Ruby Development Environment Setup Guide.

gem install google-cloud-translate

Translating text

With Cloud Translation - Basic, to send a translation request to the API use the following code:

REST & CMD LINE

HTTP method and URL:

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

Request JSON body:

{
  "q": ["Hello world", "My name is Jeff"],
  "target": "de"
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/language/translate/v2

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/language/translate/v2 " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

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

C#

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


using Google.Cloud.Translation.V2;
using System;

public partial class TranslateSample
{
    public string TranslateText()
    {
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        TranslationClient client = TranslationClient.Create();
        var response = client.TranslateText(
            text: "Hello World.",
            targetLanguage: "ru",  // Russian
            sourceLanguage: "en");  // English
        Console.WriteLine(response.TranslatedText);
        return response.TranslatedText;
    }
}

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 translateText(targetLanguage, text string) (string, error) {
	// text := "The Go Gopher is cute"
	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 "", err
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", fmt.Errorf("Translate: %v", err)
	}
	if len(resp) == 0 {
		return "", fmt.Errorf("Translate returned empty response to text: %s", text)
	}
	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.

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

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';

async function translateText() {
  // 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}`);
  });
}

translateText();

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

$translate = new TranslateClient();
$result = $translate->translate($text, [
    'target' => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\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.

"""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
"""
from google.cloud import translate_v2 as translate
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

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

# 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 version: :v2, project_id: 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}"

With Cloud Translation - Advanced, you must provide your project number (or 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).

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

Request JSON body:

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, come here!", "Bring me some coffee!"]
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id:translateText

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id:translateText " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "translations": [
    {
      "translatedText": "Доктор Ватсон, иди сюда!",
    },
    {
      "translatedText": "Принеси мне кофе!",
    }
  ]
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class TranslateText
    {
        /// <summary>
        /// Translates a given text to a target language.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextSample(string text = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);
            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
    }

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"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// translateText translates input text and returns translated text.
func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
	// projectID := "my-project-id"
	// sourceLang := "en-US"
	// targetLang := "fr"
	// text := "Text you wish to translate"

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

	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
	}

	resp, err := client.TranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("TranslateText: %v", err)
	}

	// Display the translation for each input text provided
	for _, translation := range resp.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return 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.

import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;

import java.io.IOException;

public class TranslateText {

  public static void translateText() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String targetLanguage = "your-target-language";
    String text = "your-text";
    translateText(projectId, targetLanguage, text);
  }

  // Translating Text
  public static void translateText(String projectId, String targetLanguage, String text)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");

      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        System.out.printf("Translated text: %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.

/**
 * 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');

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

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

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

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


def sample_translate_text(project_id="YOUR_PROJECT_ID"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        parent=parent,
        contents=["Hello, world!"],
        mime_type="text/plain",  # mime types: text/plain, text/html
        source_language_code="en-US",
        target_language_code="fr",
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))

Ruby

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

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project = "[Google Cloud Project ID]"

# The content to translate in string format
contents = ["Hello, world!"]
# Required. The BCP-47 language code to use for translation.
target_language = "fr"
parent = client.class.location_path project, "global"

response = client.translate_text contents, target_language, parent

# Display the translation for each input text provided
response.translations.each do |translation|
  puts "Translated text: #{translation.translated_text}"
end

Discovering supported languages

With Cloud Translation - Basic, to get a list of languages supported by the API use the following code:

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

To send your request, choose one of these options:

curl

Execute the following command:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

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

The list is sorted alphabetically by language code. This query returns iso-639-1 language codes for supported languages. Some language codes also include a country code, like zh-CN or zh-TW. For example:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

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

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

async function listLanguages() {
  // 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));
}

listLanguages();

Python

"""Lists all available languages."""
from google.cloud import translate_v2 as translate
translate_client = translate.Client()

results = translate_client.get_languages()

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

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

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

To send your request, choose one of these options:

curl

Execute the following command:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

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

The list is sorted alphabetically by language code. This query returns iso-639-1 language codes for supported languages. Some language codes also include a country code, like zh-CN or zh-TW. For example:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class GetSupportedLanguages
    {
        /// <summary>
        /// Getting a list of supported language codes
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void GetSupportedLanguagesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);
            // List language codes of supported languages
            foreach (SupportedLanguage language in response.Languages)
            {
                Console.WriteLine($"Language Code: {language.LanguageCode}");
            }
        }
    }

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"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// getSupportedLanguages gets a list of supported language codes.
func getSupportedLanguages(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %v", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
	}

	return 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.

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;

import java.io.IOException;

public class GetSupportedLanguages {

  public static void getSupportedLanguages() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    getSupportedLanguages(projectId);
  }

  // Getting a list of supported language codes
  public static void getSupportedLanguages(String projectId) throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
      }
    }
  }
}

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';

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

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

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  try {
    // Get supported languages
    const [response] = await translationClient.getSupportedLanguages(request);

    for (const language of response.languages) {
      // Supported language code, generally consisting of its ISO 639-1 identifier, for
      // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
      // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
      console.log(`Language - Language Code: ${language.languageCode}`);
      // Human readable name of the language localized in the display language specified
      // in the request.
      console.log(`Language - Display Name: ${language.displayName}`);
      // Can be used as source language.
      console.log(`Language - Support Source: ${language.supportSource}`);
      // Can be used as target language.
      console.log(`Language - Support Target: ${language.supportTarget}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

getSupportedLanguages();

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


def sample_get_supported_languages(project_id="YOUR_PROJECT_ID"):
    """Getting a list of supported language codes."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    response = client.get_supported_languages(parent=parent)

    # List language codes of supported languages.
    print("Supported Languages:")
    for language in response.languages:
        print(u"Language Code: {}".format(language.language_code))

Ruby

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

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"

parent = client.class.location_path project_id, location_id

response = client.get_supported_languages parent

# List language codes of supported languages
response.languages.each do |language|
  puts "Language Code: #{language.language_code}"
end

Detecting language

With Cloud Translation - Basic, to detect the source language present in text, 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').v2;

// 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.
async function detectLanguage() {
  let [detections] = await translate.detect(text);
  detections = Array.isArray(detections) ? detections : [detections];
  console.log('Detections:');
  detections.forEach(detection => {
    console.log(`${detection.input} => ${detection.language}`);
  });
}

detectLanguage();

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."""
from google.cloud import translate_v2 as translate
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 - Advanced, you must provide your project number (or project ID), and project location typically—either global or us-central1—when making a detectLanguage request.

Additionally, you can configure the request that you send to Cloud Translation - Advanced so that you can send different MIME types. For example, you can request text/html or text/plain (the default value is text/html).

REST & CMD LINE

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your GCP project number or ID

HTTP method and URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:detectLanguage

Request JSON body:

{
   "content":"Доктор Ватсон, иди сюда!"
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:detectLanguage

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global:detectLanguage " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "languages": [
    {
      "languageCode": "ru",
      "confidence": 1
    }
  ]
}
In the response, languageCode provides the language code of the language detected. confidence is a range from 0 to 1. 1 is 100% confident.

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class DetectLanguage
    {
        /// <summary>
        /// Detects the language of a given text.
        /// </summary>
        /// <param name="text">The text string for performing language detection</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void DetectLanguageSample(string text = "[TEXT_STRING_FOR_DETECTION]",
            string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            DetectLanguageRequest request = new DetectLanguageRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                Content = text,
                MimeType = "text/plain",
            };
            DetectLanguageResponse response = translationServiceClient.DetectLanguage(request);
            // Display list of detected languages sorted by detection confidence.
            // The most probable language is first.
            foreach (DetectedLanguage language in response.Languages)
            {
                // The language detected
                Console.WriteLine($"Language code: {language.LanguageCode}");
                // Confidence of detection result for this language
                Console.WriteLine($"Confidence: {language.Confidence}");
            }
        }
    }

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"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// detectLanguage detects the language of a text string.
func detectLanguage(w io.Writer, projectID string, text string) error {
	// projectID := "my-project-id"
	// text := "Hello, world!"

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

	req := &translatepb.DetectLanguageRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
		MimeType: "text/plain", // Mime types: "text/plain", "text/html"
		Source: &translatepb.DetectLanguageRequest_Content{
			Content: text,
		},
	}

	resp, err := client.DetectLanguage(ctx, req)
	if err != nil {
		return fmt.Errorf("DetectLanguage: %v", err)
	}

	// Display list of detected languages sorted by detection confidence.
	// The most probable language is first.
	for _, language := range resp.GetLanguages() {
		// The language detected.
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		// Confidence of detection result for this language.
		fmt.Fprintf(w, "Confidence: %v\n", language.GetConfidence())
	}

	return nil
}

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

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

async function detectLanguage() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    content: text,
  };

  try {
    // 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}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

detectLanguage();

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


def sample_detect_language(project_id="YOUR_PROJECT_ID"):
    """Detecting the language of a text string."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.detect_language(
        content="Hello, world!",
        parent=parent,
        mime_type="text/plain",  # mime types: text/plain, text/html
    )

    # Display list of detected languages sorted by detection confidence.
    # The most probable language is first.
    for language in response.languages:
        # The language detected
        print(u"Language code: {}".format(language.language_code))
        # Confidence of detection result for this language
        print(u"Confidence: {}".format(language.confidence))

Ruby

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

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
# The text string for performing language detection
content = "Hello, world!"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

parent = client.class.location_path project_id, location_id

response = client.detect_language parent, content: content, mime_type: mime_type

# Display list of detected languages sorted by detection confidence.
# The most probable language is first.
response.languages.each do |language|
  # The language detected
  puts "Language Code: #{language.language_code}"
  # Confidence of detection result for this language
  puts "Confidence: #{language.confidence}"
end

Ruby

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

require "google/cloud/translate"

client = Google::Cloud::Translate.new

project_id = "[Google Cloud Project ID]"
location_id = "[LOCATION ID]"
# The text string for performing language detection
content = "Hello, world!"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

parent = client.class.location_path project_id, location_id

response = client.detect_language parent, content: content, mime_type: mime_type

# Display list of detected languages sorted by detection confidence.
# The most probable language is first.
response.languages.each do |language|
  # The language detected
  puts "Language Code: #{language.language_code}"
  # Confidence of detection result for this language
  puts "Confidence: #{language.confidence}"
end