Detecting languages (Basic)

This document describes how to use the Cloud Translation - Basic (v2) to detect the language of a string.

Before you begin

Before you can start using the Cloud Translation API, you must have a project that has the Cloud Translation API enabled, and you must have the appropriate credentials. You can also install client libraries for common programming languages to help you make calls to the API. For more information, see the Setup page.

Detecting the language of a text string

You can detect the language of a text string by sending an HTTP request using a URL of the following format:

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

Detecting the language of a single string

REST

To detect the language of some text, make a POST request and provide the appropriate request body. The following shows an example of a POST request using curl or PowerShell. The example uses the access token for a service account set up for the project using the Google Cloud CLI. For instructions on installing the Google Cloud CLI, setting up a project with a service account, and obtaining an access token, see the Setup page.

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

  • PROJECT_NUMBER_OR_ID: the numeric or alphanumeric ID of your Google Cloud project

HTTP method and URL:

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

Request JSON body:

{
  "q": "Mi comida favorita es una enchilada."
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "data": {
    "detections": [
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "es"
        }
      ]
    ]
  }
}

In the response, language is the detected language code. The other two fields, isReliable and confidence, are deprecated fields included for backward compatibility; we recommend not basing any decisions or thresholds on their values.

Go

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

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"

	"cloud.google.com/go/translate"
)

func detectLanguage(text string) (*translate.Detection, error) {
	// text := "こんにちは世界"
	ctx := context.Background()
	client, err := translate.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("translate.NewClient: %w", err)
	}
	defer client.Close()
	lang, err := client.DetectLanguage(ctx, []string{text})
	if err != nil {
		return nil, fmt.Errorf("DetectLanguage: %w", err)
	}
	if len(lang) == 0 || len(lang[0]) == 0 {
		return nil, fmt.Errorf("DetectLanguage return value empty")
	}
	return &lang[0][0], nil
}

Java

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

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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 Cloud Translation quickstart using client libraries. For more information, see the Cloud Translation Node.js API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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 Cloud Translation quickstart using client libraries. For more information, see the Cloud Translation Python API reference documentation.

To authenticate to Cloud Translation, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def detect_language(text: str) -> dict:
    """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(f"Text: {text}")
    print("Confidence: {}".format(result["confidence"]))
    print("Language: {}".format(result["language"]))

    return result

Additional languages

C#: Please follow the C# setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for .NET.

PHP: Please follow the PHP setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for PHP.

Ruby: Please follow the Ruby setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for Ruby.

Detecting the language of more than one string

REST

To detect language for more than one string, use the q parameter to specify each string. This example passes two separate strings for detection:

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

  • PROJECT_NUMBER_OR_ID: the numeric or alphanumeric ID of your Google Cloud project

HTTP method and URL:

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

Request JSON body:

{
  "q": ["Hello world", "我的名字叫傑夫"]
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "data": {
    "detections": [
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "en"
        }
      ],
      [
        {
          "confidence": 1,
          "isReliable": false,
          "language": "zh-TW"
        }
      ]
    ]
  }
}

Here, the response contains two detections, in the same order as the corresponding source strings were provided in the request.

Go

To detect the language of multiple texts, include multiple strings in the slice passed to the Client#DetectLanguage method shown in the preceding example.

Java

To detect the language of multiple texts, simply pass a list of strings to the Translate#detect method shown in the preceding example.

Node.js

To detect the language of multiple texts, simply pass an array of strings to the Translate#detect method shown in the preceding example.

Python

To detect the language of multiple texts, simply pass a list of strings to the Client#detect_language method shown in the preceding example.

Additional languages

C#: Please follow the C# setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for .NET.

PHP: Please follow the PHP setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for PHP.

Ruby: Please follow the Ruby setup instructions on the client libraries page and then visit the Cloud Translation reference documentation for Ruby.

Ruby

To detect the language of multiple texts, simply pass multiple strings to the Translate#detect method shown in the preceding example.

Additional resources

  • For help on resolving common issues or errors, see the Troubleshooting page.