Detecting languages (v3beta1)

This document describes how to use the Cloud Translation API to detect the language of a string.

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/v3beta1/projects/project-id/locations/global:detectLanguage

Detecting the language of a single string

curl command

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. 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 "{
     content: 'Доктор Ватсон, иди сюда!'
}" "https://translation.googleapis.com/v3beta1/projects/project-id/locations/global:detectLanguage"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "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.

Java

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

static DetectLanguageResponse detectLanguageOfText(
    String projectId, String location, String text) {

  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();
    DetectLanguageRequest detectLanguageRequest =
        DetectLanguageRequest.newBuilder()
            .setParent(locationName.toString())
            .setMimeType("text/plain")
            .setContent(text)
            .build();

    // Call the API
    DetectLanguageResponse response =
        translationServiceClient.detectLanguage(detectLanguageRequest);
    System.out.format("Detected Language Code: %s", response.getLanguages(0).getLanguageCode());
    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 API Quickstart Using Client Libraries . For more information, see the Translation API 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').v3beta1;

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

async function detectLanguage() {
  // Construct request
  const request = {
    parent: translationClient.locationPath(projectId, location),
    content: text,
  };

  // 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}`);
  }
}

detectLanguage();

Python

Before trying this sample, follow the Python setup instructions in the Translation API Quickstart Using Client Libraries . For more information, see the Translation API 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.detect_language(
    parent=parent,
    content=text,
    mime_type='text/plain')  # mime types: text/plain, text/html

for language in response.languages:
    print('Language Code: {} (Confidence: {})'.format(
        language.language_code,
        language.confidence))

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Translation
Need help? Visit our support page.