Como detectar idiomas (Advanced)

Neste documento, você vê como usar o Cloud Translation – Advanced para detectar o idioma de uma string.

Antes de começar

Antes de começar a usar a API Cloud Translation, é preciso ter um projeto com a API Cloud Translation ativada e as credenciais apropriadas. Também é possível instalar bibliotecas de cliente para linguagens de programação comuns para ajudar você a fazer chamadas para a API. Para ver mais informações, consulte a página Configuração.

Como detectar o idioma de uma string de texto

Detecte o idioma de uma string de texto enviando uma solicitação HTTP usando um URL no seguinte formato:

https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/global:detectLanguage

Como detectar o idioma de uma única string

REST

Para detectar o idioma de um texto, faça uma solicitação POST e forneça o corpo apropriado. Veja a seguir o exemplo de uma solicitação POST usando curl e PowerShell. O exemplo usa o token de acesso de uma conta de serviço configurada para o projeto por meio da CLI do Google Cloud. Consulte a página Configuração para ver instruções de como instalar a CLI do Google Cloud, configurar um projeto com uma conta de serviço e conseguir um token de acesso.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_NUMBER_OR_ID: o ID numérico ou alfanumérico do projeto do Google Cloud

Método HTTP e URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/global:detectLanguage

Corpo JSON da solicitação:

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

Para enviar a solicitação, expanda uma destas opções:

Você receberá uma resposta JSON semelhante a esta:

{
  "languages": [
    {
      "languageCode": "ru",
      "confidence": 1
    }
  ]
}
Na resposta, languageCode informa o código do idioma detectado. confidence é um intervalo de 0 a 1, sendo que 1 indica confiança total.

Go

Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido do Cloud Translation: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Cloud Translation em Go.

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", 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: %w", 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
}

Java

Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido do Cloud Translation: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Cloud Translation em Java.

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.cloud.translate.v3.DetectLanguageRequest;
import com.google.cloud.translate.v3.DetectLanguageResponse;
import com.google.cloud.translate.v3.DetectedLanguage;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class DetectLanguage {

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

    detectLanguage(projectId, text);
  }

  // Detecting the language of a text string
  public static void detectLanguage(String projectId, 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
      DetectLanguageRequest request =
          DetectLanguageRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setContent(text)
              .build();

      DetectLanguageResponse response = client.detectLanguage(request);

      // Display list of detected languages sorted by detection confidence.
      // The most probable language is first.
      for (DetectedLanguage language : response.getLanguagesList()) {
        // The language detected
        System.out.printf("Language code: %s\n", language.getLanguageCode());
        // Confidence of detection result for this language
        System.out.printf("Confidence: %s\n", language.getConfidence());
      }
    }
  }
}

Node.js

Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do Cloud Translation: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Cloud Translation em Node.js.

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * 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,
  };

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

Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido do Cloud Translation: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Cloud Translation em Python.

Para autenticar no Cloud Translation, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.cloud import translate

def detect_language(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.DetectLanguageResponse:
    """Detecting the language of a text string.

    Args:
        project_id: The GCP project ID.

    Returns:
        The detected language of the text.
    """
    client = translate.TranslationServiceClient()

    location = "global"

    parent = f"projects/{project_id}/locations/{location}"

    # 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(f"Language code: {language.language_code}")
        # Confidence of detection result for this language
        print(f"Confidence: {language.confidence}")

    return response

Outras linguagens

C#: Siga as Instruções de configuração do C# na página das bibliotecas de cliente e acesse Documentação de referência do Cloud Translation para o .NET.

PHP: Siga as Instruções de configuração do PHP na página das bibliotecas de cliente e acesse Documentação de referência do Cloud Translation para PHP.

Ruby: Siga as Instruções de configuração do Ruby na página das bibliotecas de cliente e acesse Documentação de referência do Cloud Translation para Ruby.

Outros recursos

  • Para receber ajuda sobre como resolver erros ou problemas comuns, consulte a página Solução de problemas.