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

REST & CMD LINE

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.

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

  • project-id: your GCP project ID

HTTP method and URL:

POST https://translation.googleapis.com/v3beta1/projects/project-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/v3beta1/projects/project-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/v3beta1/projects/project-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.

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 .

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 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').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 Quickstart Using Client Libraries . For more information, see the Translation 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))

หน้านี้มีประโยชน์ไหม โปรดแสดงความคิดเห็น

ส่งความคิดเห็นเกี่ยวกับ...

หากต้องการความช่วยเหลือ ให้ไปที่หน้าการสนับสนุน