Traduzir textos com o Cloud Translation Basic

Nesta página, mostramos como traduzir um texto de amostra usando o Cloud Translation Basic.

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.

Exemplo de texto traduzido

Veja no exemplo a seguir como usar o Cloud Translation - Basic para traduzir textos para um determinado idioma de destino.

REST

Para fazer uma solicitação do Cloud Translation – Basic, realize uma chamada REST para o método translate da edição correspondente. Use os códigos ISO-639-1 para identificar os idiomas de origem e de destino.

Veja a seguir um exemplo de uma solicitação POST usando curl ou PowerShell.

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 seu Google Cloud projeto

Método HTTP e URL:

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

Corpo JSON da solicitação:

{
  "q": "The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.",
  "source": "en",
  "target": "es",
  "format": "text"
}

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

curl

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

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

PowerShell

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER_OR_ID" }

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

Você receberá uma resposta JSON semelhante a esta:

{
  "data": {
    "translations": [{
      "translatedText": "La Gran Pirámide de Giza (también conocida como la Pirámide de Khufu o la Pirámide de Keops) es la más antigua y más grande de las tres pirámides en el complejo de la pirámide de Giza."
    }]
  }
}

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"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

// translateText translates the given text into the specified targetLanguage. sourceLanguage
// is optional. If empty, the API will attempt to detect the source language automatically.
// targetLanguage and sourceLanguage should follow ISO 639 language code of the input text
// (e.g., 'fr' for French)
//
// Find a list of supported languages and codes here:
// https://cloud.google.com/translate/docs/languages#nmt
func translateText(w io.Writer, targetLanguage, sourceLanguage, text string) error {
	ctx := context.Background()

	// Create new Translate client.
	client, err := translate.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("translate.NewClient error: %w", err)
	}
	defer client.Close()

	// Get required tag by parsing the target language.
	targetLang, err := language.Parse(targetLanguage)
	if err != nil {
		return fmt.Errorf("language.Parse: %w", err)
	}

	options := &translate.Options{}

	if sourceLanguage != "" {
		sourceLang, err := language.Parse(sourceLanguage)
		if err != nil {
			return fmt.Errorf("language.Parse: %w", err)
		}
		options = &translate.Options{
			Source: sourceLang,
		}
	}

	// Find more information about translate function here:
	// https://pkg.go.dev/cloud.google.com/go/translate#Client.Translate
	resp, err := client.Translate(ctx, []string{text}, targetLang, options)
	if err != nil {
		return fmt.Errorf("client.Translate error: %w", err)
	}
	if len(resp) == 0 {
		return fmt.Errorf("client.Translate returned empty response to text: %s", text)
	}

	// Print results to buffer.
	fmt.Fprintf(w, "Input Text: %s\n", resp[0].Text)
	fmt.Fprintf(w, "Translated Test: %s\n", text)

	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.

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

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.

// 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();

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.

def translate_text(
    text: str | bytes | list[str] = "¡Hola amigos y amigas!",
    target_language: str = "en",
    source_language: str | None = None,
) -> dict:
    """Translates a given text into the specified target language.

    Find a list of supported languages and codes here:
    https://cloud.google.com/translate/docs/languages#nmt

    Args:
        text: The text to translate. Can be a string, bytes or a list of strings.
              If bytes, it will be decoded as UTF-8.
        target_language: The ISO 639 language code to translate the text into
                         (e.g., 'en' for English, 'es' for Spanish).
        source_language: Optional. The ISO 639 language code of the input text
                         (e.g., 'fr' for French). If None, the API will attempt
                         to detect the source language automatically.

    Returns:
        A dictionary containing the translation results.
    """

    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = [text.decode("utf-8")]

    if isinstance(text, str):
        text = [text]

    # If a string is supplied, a single dictionary will be returned.
    # In case a list of strings is supplied, this method
    # will return a list of dictionaries.

    # Find more information about translate function here:
    # https://cloud.google.com/python/docs/reference/translate/latest/google.cloud.translate_v2.client.Client#google_cloud_translate_v2_client_Client_translate
    results = translate_client.translate(
        values=text,
        target_language=target_language,
        source_language=source_language
    )

    for result in results:
        if "detectedSourceLanguage" in result:
            print(f"Detected source language: {result['detectedSourceLanguage']}")

        print(f"Input text: {result['input']}")
        print(f"Translated text: {result['translatedText']}")
        print()

    return results

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