Solicitudes por lotes (avanzado)

La traducción por lotes te permite traducir grandes cantidades de texto (con un límite de 1,000 archivos por lote) y hasta 10 idiomas objetivo diferentes en un comando sin conexión. El tamaño total del contenido debe ser menor o igual que 100 millones de puntos de código Unicode y debe usar la codificación UTF-8.

Antes de comenzar

Antes de comenzar a usar la API de Cloud Translation, debes tener un proyecto que tenga habilitada la API de Cloud Translation y las credenciales adecuadas. También puedes instalar bibliotecas cliente para los lenguajes de programación comunes que te ayudarán a realizar llamadas a la API.

Para obtener más información, consulta la página Configuración.

Permisos

Para las traducciones por lotes, debes tener acceso a los depósitos de Cloud Storage además de los permisos de Cloud Translation. Los archivos de entrada de traducción por lotes se leen desde un depósito de Cloud Storage y los archivos de salida se escriben en un depósito de Cloud Storage. Por ejemplo, para leer archivos de entrada de un depósito, al menos debes tener permisos de objetos de lectura (proporcionados por la función roles/storage.objectViewer) en el depósito. Para obtener más información sobre las funciones de Cloud Storage, consulta su documentación.

Archivo de entrada

Solo se admiten dos tipos de MIME: text/html (HTML) y text/plain (.tsv y .txt).

Usa un archivo TSV

Si una extensión de archivo es TSV, puede contener una o dos columnas. La primera columna (opcional) es el ID de la solicitud de texto. Si falta la primera columna, Google usa el número de fila (basado en 0) del archivo de entrada como el ID en el archivo de salida. La segunda columna es el texto real que se quiere traducir. Para obtener mejores resultados, cada fila debe ser menor o igual que 10.000 puntos de código Unicode. De lo contrario, es posible que se muestre un error.

Usa texto o HTML

Las demás extensiones de archivo compatibles son archivos de texto (.txt) o HTML, que se tratan como una sola porción grande de texto.

Solicitud por lotes

Con una solicitud de traducción por lotes, debes proporcionar la ruta de acceso a un archivo de configuración de entrada (InputConfig) que contenga el contenido que deseas traducir y proporcionar una ruta de acceso a una ubicación de salida (OutputConfig) para la traducción final. Necesitas al menos dos depósitos distintos de Cloud Storage. El depósito de origen contiene el contenido que deseas traducir y el depósito de destino contendrá los archivos traducidos resultantes. El depósito de destino debe estar vacío antes de que comience el proceso de traducción.

A medida que se procesa la solicitud, escribimos los resultados en la ubicación de salida en tiempo real. Aunque canceles la solicitud a mitad de la operación, se producirá un resultado parcial a nivel de los archivos de entrada en la ubicación de salida de Cloud Storage. Por lo tanto, se cobrará la cantidad de caracteres traducidos.

LÍNEA DE REST Y CMD

En este ejemplo, se muestran dos archivos de entrada enviados para traducir.

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-number-or-id: el número o ID de tu proyecto de Google Cloud

Método HTTP y URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

Cuerpo JSON de la solicitud:

{
  "sourceLanguageCode": "en",
  "targetLanguageCodes": ["es", "fr"],
  "inputConfigs": [
   {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name1"
      }
    },
    {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name2"
      }
    }
  ],
  "outputConfig": {
      "gcsDestination": {
        "outputUriPrefix": "gs://bucket-name-destination/"
      }
   }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText " | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-number/locations/us-central1/operations/20191107-08251564068323-5d3895ce-0000-2067-864c-001a1136fb06",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.BatchTranslateMetadata",
    "state": "RUNNING"
  }
}
La respuesta contiene el ID de una operación de larga duración.

C#

Antes de probar este código de muestra, sigue las instrucciones de configuración para C# que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para C#.


using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;

namespace GoogleCloudSamples
{
    public static class BatchTranslateText
    {
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location">Region.</param>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        /// <param name="targetLanguage">Target language code.</param>
        public static void BatchTranslateTextSample(string inputUri = "gs://cloud-samples-data/text.txt",
            string outputUri = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1",
            string sourceLanguage = "en",
            string targetLanguage = "ja")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode = sourceLanguage,
                TargetLanguageCodes =
                {
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
            };
            // Poll until the returned long-running operation is completed.
            BatchTranslateResponse response = translationServiceClient.BatchTranslateText(request).PollUntilCompleted().Result;
            Console.WriteLine($"Total Characters: {response.TotalCharacters}");
            Console.WriteLine($"Translated Characters: {response.TranslatedCharacters}");
        }
    }

Go

Antes de probar este código de muestra, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Go.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// batchTranslateText translates a large volume of text in asynchronous batch mode.
func batchTranslateText(w io.Writer, projectID string, location string, inputURI string, outputURI string, sourceLang string, targetLang string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://cloud-samples-data/text.txt"
	// outputURI := "gs://YOUR_BUCKET_ID/path_to_store_results/"
	// sourceLang := "en"
	// targetLang := "ja"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.BatchTranslateTextRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode:  sourceLang,
		TargetLanguageCodes: []string{targetLang},
		InputConfigs: []*translatepb.InputConfig{
			{
				Source: &translatepb.InputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{InputUri: inputURI},
				},
				// Optional. Can be "text/plain" or "text/html".
				MimeType: "text/plain",
			},
		},
		OutputConfig: &translatepb.OutputConfig{
			Destination: &translatepb.OutputConfig_GcsDestination{
				GcsDestination: &translatepb.GcsDestination{
					OutputUriPrefix: outputURI,
				},
			},
		},
	}

	// The BatchTranslateText operation is async.
	op, err := client.BatchTranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("BatchTranslateText: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Total characters: %v\n", resp.GetTotalCharacters())
	fmt.Fprintf(w, "Translated characters: %v\n", resp.GetTranslatedCharacters())

	return nil
}

Java

Antes de probar este código de muestra, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Java.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.BatchTranslateMetadata;
import com.google.cloud.translate.v3.BatchTranslateResponse;
import com.google.cloud.translate.v3.BatchTranslateTextRequest;
import com.google.cloud.translate.v3.GcsDestination;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.InputConfig;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BatchTranslateText {

  public static void batchTranslateText()
      throws InterruptedException, ExecutionException, IOException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    String outputUri = "gs://your-gcs-bucket/path/to/results/";
    batchTranslateText(projectId, sourceLanguage, targetLanguage, inputUri, outputUri);
  }

  // Batch translate text
  public static void batchTranslateText(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String inputUri,
      String outputUri)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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: `us-central1`
      LocationName parent = LocationName.of(projectId, "us-central1");

      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      InputConfig inputConfig =
          InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();

      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      BatchTranslateTextRequest request =
          BatchTranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setSourceLanguageCode(sourceLanguage)
              .addTargetLanguageCodes(targetLanguage)
              .addInputConfigs(inputConfig)
              .setOutputConfig(outputConfig)
              .build();

      OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future =
          client.batchTranslateTextAsync(request);

      System.out.println("Waiting for operation to complete...");
      BatchTranslateResponse response = future.get(180, TimeUnit.SECONDS);
      System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
      System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
  }
}

Node.js

Antes de probar este código de muestra, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Node.js.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const inputUri = 'gs://cloud-samples-data/text.txt';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function batchTranslateText() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    sourceLanguageCode: 'en',
    targetLanguageCodes: ['ja'],
    inputConfigs: [
      {
        mimeType: 'text/plain', // mime types: text/plain, text/html
        gcsSource: {
          inputUri: inputUri,
        },
      },
    ],
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
  };

  try {
    // Batch translate text using a long-running operation
    const [operation] = await translationClient.batchTranslateText(request);

    // Wait for operation to complete.
    const [response] = await operation.promise();

    console.log(`Total Characters: ${response.totalCharacters}`);
    console.log(`Translated Characters: ${response.translatedCharacters}`);
  } catch (error) {
    console.error(error.details);
  }
}

batchTranslateText();

PHP

Antes de probar este código de muestra, sigue las instrucciones de configuración para PHP que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para PHP.

use Google\Cloud\Translate\V3\GcsDestination;
use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $inputUri = 'gs://cloud-samples-data/text.txt';
// $outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $sourceLang = 'en';
// $targetLang = 'ja';
$targetLanguageCodes = [$targetLang];
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';
$inputConfigsElement = (new InputConfig())
    ->setGcsSource($gcsSource)
    ->setMimeType($mimeType);
$inputConfigs = [$inputConfigsElement];
$gcsDestination = (new GcsDestination())
    ->setOutputUriPrefix($outputUri);
$outputConfig = (new OutputConfig())
    ->setGcsDestination($gcsDestination);
$formattedParent = $translationServiceClient->locationName($projectId, $location);

try {
    $operationResponse = $translationServiceClient->batchTranslateText(
        $formattedParent,
        $sourceLang,
        $targetLanguageCodes,
        $inputConfigs,
        $outputConfig
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        printf('Total Characters: %s' . PHP_EOL, $response->getTotalCharacters());
        printf('Translated Characters: %s' . PHP_EOL, $response->getTranslatedCharacters());
    } else {
        $error = $operationResponse->getError();
        print($error->getMessage());
    }
} finally {
    $translationServiceClient->close();
}

Python

Antes de probar este código de muestra, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Python.

from google.cloud import translate

def batch_translate_text(
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/file.txt",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
    project_id="YOUR_PROJECT_ID",
    timeout=180,
):
    """Translates a batch of texts on GCS and stores the result in a GCS location."""

    client = translate.TranslationServiceClient()

    location = "us-central1"
    # Supported file types: https://cloud.google.com/translate/docs/supported-formats
    gcs_source = {"input_uri": input_uri}

    input_configs_element = {
        "gcs_source": gcs_source,
        "mime_type": "text/plain",  # Can be "text/plain" or "text/html".
    }
    gcs_destination = {"output_uri_prefix": output_uri}
    output_config = {"gcs_destination": gcs_destination}
    parent = f"projects/{project_id}/locations/{location}"

    # Supported language codes: https://cloud.google.com/translate/docs/language
    operation = client.batch_translate_text(
        request={
            "parent": parent,
            "source_language_code": "en",
            "target_language_codes": ["ja"],  # Up to 10 language codes here.
            "input_configs": [input_configs_element],
            "output_config": output_config,
        }
    )

    print("Waiting for operation to complete...")
    response = operation.result(timeout)

    print("Total Characters: {}".format(response.total_characters))
    print("Translated Characters: {}".format(response.translated_characters))

Ruby

Antes de probar este código de muestra, sigue las instrucciones de configuración para Ruby que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Ruby.

require "google/cloud/translate"

# input_uri = "gs://cloud-samples-data/text.txt"
# output_uri = "gs://YOUR_BUCKET_ID/path_to_store_results/"
# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

source_lang = "en"
target_lang = "ja"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id
input_config = {
  mime_type:  mime_type,
  gcs_source: { input_uri: input_uri }
}
output_config = {
  gcs_destination: { output_uri_prefix: output_uri }
}

operation = client.batch_translate_text(
  parent:                parent,
  source_language_code:  source_lang,
  target_language_codes: [target_lang],
  input_configs:         [input_config],
  output_config:         output_config
)

# Wait until the long running operation is done
operation.wait_until_done!

response = operation.response

puts "Total Characters: #{response.total_characters}"
puts "Translated Characters: #{response.translated_characters}"

Realiza una solicitud por lotes con un modelo de AutoML

Puedes usar un modelo personalizado para realizar una solicitud por lotes. Existen muchos casos en los que se incluyen varios idiomas objetivo.

Especifica un modelo de AutoML para el idioma objetivo

LÍNEA DE CMD Y REST

En este ejemplo, se muestra cómo especificar un modelo personalizado para el idioma objetivo.

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-number-or-id: el número o ID de tu proyecto de Google Cloud

Método HTTP y URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

Cuerpo JSON de la solicitud:

{
  "models":{"es":"projects/project-number-or-id/locations/us-central1/models/model-id"},
  "sourceLanguageCode": "en",
  "targetLanguageCodes": ["es"],
  "inputConfigs": [
   {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name1"
      }
    },
    {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name2"
      }
    }
  ],
  "outputConfig": {
      "gcsDestination": {
        "outputUriPrefix": "gs://bucket-name-destination/"
      }
   }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText " | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-number/locations/us-central1/operations/20190725-08251564068323-5d3895ce-0000-2067-864c-001a1136fb06",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.BatchTranslateMetadata",
    "state": "RUNNING"
  }
}
La respuesta contiene el ID de una operación de larga duración.

C#

Antes de probar este código de muestra, sigue las instrucciones de configuración para C# que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para C#.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class BatchTranslateTextWithModel
    {
        /// <summary>
        /// Batch translate text using Translation model.
        /// Model can be AutoML or General[built-in] model.
        /// </summary>
        /// <param name="targetLanguage">Target language code.</param>
        /// <param name="sourceLanguage">Required. Source language code.</param>
        /// <param name="modelId">A model is used for Translation.
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        /// <param name="location"> Region.</param>
        public static void BatchTranslateTextWithModelSample(
            string inputUri = "gs://cloud-samples-data/translation/custom_model_text.txt'",
            string outputUri = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string modelId = "[YOUR-MODEL-ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            string modelPath = $"projects/{projectId}/locations/{location}/models/{modelId}";

            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode = sourceLanguage,
                TargetLanguageCodes =
                {
                    // Target language code.
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
                Models =
                {
                    // A model is used for Translation.
                    { targetLanguage,  modelPath},
                },
            };
            // Poll until the returned long-running operation is completed.
            BatchTranslateResponse response = translationServiceClient.BatchTranslateText(request).PollUntilCompleted().Result;
            Console.WriteLine($"Total Characters: {response.TotalCharacters}");
            Console.WriteLine($"Translated Characters: {response.TranslatedCharacters}");
        }
    }

Go

Antes de probar este código de muestra, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Go.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// batchTranslateTextWithModel translates a large volume of text in asynchronous batch mode.
func batchTranslateTextWithModel(w io.Writer, projectID string, location string, inputURI string, outputURI string, sourceLang string, targetLang string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://cloud-samples-data/text.txt"
	// outputURI := "gs://YOUR_BUCKET_ID/path_to_store_results/"
	// sourceLang := "en"
	// targetLang := "de"
	// modelID := "your-model-id"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.BatchTranslateTextRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode:  sourceLang,
		TargetLanguageCodes: []string{targetLang},
		InputConfigs: []*translatepb.InputConfig{
			{
				Source: &translatepb.InputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{InputUri: inputURI},
				},
				// Optional. Can be "text/plain" or "text/html".
				MimeType: "text/plain",
			},
		},
		OutputConfig: &translatepb.OutputConfig{
			Destination: &translatepb.OutputConfig_GcsDestination{
				GcsDestination: &translatepb.GcsDestination{
					OutputUriPrefix: outputURI,
				},
			},
		},
		Models: map[string]string{
			targetLang: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		},
	}

	// The BatchTranslateText operation is async.
	op, err := client.BatchTranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("BatchTranslateText: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Total characters: %v\n", resp.GetTotalCharacters())
	fmt.Fprintf(w, "Translated characters: %v\n", resp.GetTranslatedCharacters())

	return nil
}

Java

Antes de probar este código de muestra, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Java.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.BatchTranslateMetadata;
import com.google.cloud.translate.v3.BatchTranslateResponse;
import com.google.cloud.translate.v3.BatchTranslateTextRequest;
import com.google.cloud.translate.v3.GcsDestination;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.InputConfig;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BatchTranslateTextWithModel {

  public static void batchTranslateTextWithModel()
      throws InterruptedException, ExecutionException, IOException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    String outputUri = "gs://your-gcs-bucket/path/to/results/";
    String modelId = "YOUR-MODEL-ID";
    batchTranslateTextWithModel(
        projectId, sourceLanguage, targetLanguage, inputUri, outputUri, modelId);
  }

  // Batch translate text using AutoML Translation model
  public static void batchTranslateTextWithModel(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String inputUri,
      String outputUri,
      String modelId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      InputConfig inputConfig =
          InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();

      // Configure where to store the output in a GCS bucket
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      // Configure the model used in the request
      String modelPath =
          String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);

      // Build the request that will be sent to the API
      BatchTranslateTextRequest request =
          BatchTranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setSourceLanguageCode(sourceLanguage)
              .addTargetLanguageCodes(targetLanguage)
              .addInputConfigs(inputConfig)
              .setOutputConfig(outputConfig)
              .putModels(targetLanguage, modelPath)
              .build();

      // Start an asynchronous request
      OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future =
          client.batchTranslateTextAsync(request);

      System.out.println("Waiting for operation to complete...");
      BatchTranslateResponse response = future.get(180, TimeUnit.SECONDS);
      // Display the translation for each input text provided
      System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
      System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
  }
}

Node.js

Antes de probar este código de muestra, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Node.js.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const inputUri = 'gs://cloud-samples-data/text.txt';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const client = new TranslationServiceClient();
async function batchTranslateTextWithModel() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    sourceLanguageCode: 'en',
    targetLanguageCodes: ['ja'],
    inputConfigs: [
      {
        mimeType: 'text/plain', // mime types: text/plain, text/html
        gcsSource: {
          inputUri: inputUri,
        },
      },
    ],
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
    models: {
      ja: `projects/${projectId}/locations/${location}/models/${modelId}`,
    },
  };

  try {
    // Create a job using a long-running operation
    const [operation] = await client.batchTranslateText(request);

    // Wait for the operation to complete
    const [response] = await operation.promise();

    // Display the translation for each input text provided
    console.log(`Total Characters: ${response.totalCharacters}`);
    console.log(`Translated Characters: ${response.translatedCharacters}`);
  } catch (error) {
    console.error(error.details);
  }
}

batchTranslateTextWithModel();

PHP

Antes de probar este código de muestra, sigue las instrucciones de configuración para PHP que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para PHP.

use Google\Cloud\Translate\V3\GcsDestination;
use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $inputUri = 'gs://cloud-samples-data/text.txt';
// $outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $targetLanguage = 'en';
// $sourceLanguage = 'de';
// $modelId = '{your-model-id}';
$modelPath = sprintf(
    'projects/%s/locations/%s/models/%s',
    $projectId,
    $location,
    $modelId
);
$targetLanguageCodes = [$targetLanguage];
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';
$inputConfigsElement = (new InputConfig())
    ->setGcsSource($gcsSource)
    ->setMimeType($mimeType);
$inputConfigs = [$inputConfigsElement];
$gcsDestination = (new GcsDestination())
    ->setOutputUriPrefix($outputUri);
$outputConfig = (new OutputConfig())
    ->setGcsDestination($gcsDestination);
$formattedParent = $translationServiceClient->locationName($projectId, $location);
$models = ['ja' => $modelPath];

try {
    $operationResponse = $translationServiceClient->batchTranslateText(
        $formattedParent,
        $sourceLanguage,
        $targetLanguageCodes,
        $inputConfigs,
        $outputConfig,
        ['models' => $models]
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        // Display the translation for each input text provided
        printf('Total Characters: %s' . PHP_EOL, $response->getTotalCharacters());
        printf('Translated Characters: %s' . PHP_EOL, $response->getTranslatedCharacters());
    } else {
        $error = $operationResponse->getError();
        print($error->getMessage());
    }
} finally {
    $translationServiceClient->close();
}

Python

Antes de probar este código de muestra, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Python.

from google.cloud import translate

def batch_translate_text_with_model(
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/file.txt",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
    project_id="YOUR_PROJECT_ID",
    model_id="YOUR_MODEL_ID",
):
    """Batch translate text using Translation model.
     Model can be AutoML or General[built-in] model. """

    client = translate.TranslationServiceClient()

    # Supported file types: https://cloud.google.com/translate/docs/supported-formats
    gcs_source = {"input_uri": input_uri}
    location = "us-central1"

    input_configs_element = {
        "gcs_source": gcs_source,
        "mime_type": "text/plain",  # Can be "text/plain" or "text/html".
    }
    gcs_destination = {"output_uri_prefix": output_uri}
    output_config = {"gcs_destination": gcs_destination}
    parent = f"projects/{project_id}/locations/{location}"

    model_path = "projects/{}/locations/{}/models/{}".format(
        project_id, location, model_id  # The location of AutoML model.
    )

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    models = {"ja": model_path}  # takes a target lang as key.

    operation = client.batch_translate_text(
        request={
            "parent": parent,
            "source_language_code": "en",
            "target_language_codes": ["ja"],  # Up to 10 language codes here.
            "input_configs": [input_configs_element],
            "output_config": output_config,
            "models": models,
        }
    )

    print("Waiting for operation to complete...")
    response = operation.result()

    # Display the translation for each input text provided.
    print("Total Characters: {}".format(response.total_characters))
    print("Translated Characters: {}".format(response.translated_characters))

Ruby

Antes de probar este código de muestra, sigue las instrucciones de configuración para Ruby que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Ruby.

require "google/cloud/translate"

# input_uri = "gs://cloud-samples-data/text.txt"
# output_uri = "gs://YOUR_BUCKET_ID/path_to_store_results/"
# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# model_id = "[MODEL ID]"

source_lang = "en"
target_lang = "ja"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id
model = "projects/#{project_id}/locations/#{location_id}/models/#{model_id}"
models = { target_lang => model }
input_config = {
  mime_type:  mime_type,
  gcs_source: { input_uri: input_uri }
}
output_config = {
  gcs_destination: { output_uri_prefix: output_uri }
}

operation = client.batch_translate_text(
  parent:                parent,
  source_language_code:  source_lang,
  target_language_codes: [target_lang],
  input_configs:         [input_config],
  output_config:         output_config,
  models:                models
)

# Wait until the long running operation is done
operation.wait_until_done!

response = operation.response

puts "Total Characters: #{response.total_characters}"
puts "Translated Characters: #{response.translated_characters}"

Especifica modelos de AutoML para varios idiomas objetivo

LÍNEA DE CMD Y REST

Si tienes varios idiomas objetivo, puedes especificar un modelo personalizado para cada uno.

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-number-or-id: el número o ID de tu proyecto de Google Cloud

Método HTTP y URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

Cuerpo JSON de la solicitud:

{
  "models":{
    "es":"projects/project-number-or-id/locations/us-central1/models/model-id1",
    "fr":"projects/project-number-or-id/locations/us-central1/models/model-id2"},
  "sourceLanguageCode": "en",
  "targetLanguageCodes": ["es", "fr"],
  "inputConfigs": [
   {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name1"
      }
    },
    {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name2"
      }
    }
  ],
  "outputConfig": {
      "gcsDestination": {
        "outputUriPrefix": "gs://bucket-name-destination/"
      }
   }
 }

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText " | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-number/locations/us-central1/operations/20191105-08251564068323-5d3895ce-0000-2067-864c-001a1136fb06",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.BatchTranslateMetadata",
    "state": "RUNNING"
  }
}
La respuesta contiene el ID de una operación de larga duración.

Especifica un modelo de AutoML para un idioma objetivo y no otros

Puedes especificar un modelo personalizado para un idioma objetivo sin especificar un modelo para los otros idiomas objetivo. Con el código de Especificar modelos personalizados para varios idiomas objetivo, modifica el campo models para especificar el idioma objetivo del modelo, es en este ejemplo, y deja fr sin especificar:

  • "models": {'es':'projects/project-number-or-id/locations/us-central1/models/model-id'},

En el ejemplo anterior, project-number-or-id es tu ID o número de proyecto de Google Cloud, y model-id es el nombre que le asignaste a tu modelo de AutoML.

Traduce texto con un glosario

LÍNEA DE CMD Y REST

En este ejemplo, se muestra cómo especificar un glosario para el idioma objetivo.

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-number-or-id: el número o ID de tu proyecto de Google Cloud
  • glossary-id: tu ID de glosario, por ejemplo, “my-en-to-es-glosario”

Método HTTP y URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

Cuerpo JSON de la solicitud:

{
  "sourceLanguageCode": "en",
  "targetLanguageCodes": ["es"],
  "glossaries": {
    "es": {
      "glossary": "projects/project-number-or-id/locations/us-central1/glossaries/glossary-id"
    }
  },
  "inputConfigs": [{
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name1"
      }
    },
    {
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name2"
      }
    }
  ],
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "gs://bucket-name-destination/"
    }
  }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText " | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.BatchTranslateMetadata",
    "state": "RUNNING"
  }
}

C#

Antes de probar este código de muestra, sigue las instrucciones de configuración para C# que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para C#.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class BatchTranslateTextWithGlossary
    {
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// Glossary is applied for translation.
        /// </summary>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location">Region.</param>
        /// <param name="glossaryId">Required. Translation Glossary ID.</param>
        /// <param name="targetLanguage">Target language code.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        public static void BatchTranslateTextWithGlossarySample(
            string inputUri = "gs://cloud-samples-data/text.txt",
            string outputUri = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1",
            string glossaryId = "[YOUR_GLOSSARY_ID]",
            string targetLanguage = "en",
            string sourceLanguage = "ja")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string glossaryPath = $"projects/{projectId}/locations/{location}/glossaries/{glossaryId}";
            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode = sourceLanguage,
                TargetLanguageCodes =
                {
                    // Target language code.
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
                Glossaries =
                {
                    {
                        targetLanguage, new TranslateTextGlossaryConfig
                        {
                            Glossary = glossaryPath,
                        }
                    },
                },
            };
            // Poll until the returned long-running operation is completed.
            BatchTranslateResponse response = translationServiceClient.BatchTranslateText(request).PollUntilCompleted().Result;
            Console.WriteLine($"Total Characters: {response.TotalCharacters}");
            Console.WriteLine($"Translated Characters: {response.TranslatedCharacters}");
        }
    }

Go

Antes de probar este código de muestra, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Go.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// batchTranslateTextWithGlossary translates a large volume of text in asynchronous batch mode.
func batchTranslateTextWithGlossary(w io.Writer, projectID string, location string, inputURI string, outputURI string, sourceLang string, targetLang string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://cloud-samples-data/text.txt"
	// outputURI := "gs://YOUR_BUCKET_ID/path_to_store_results/"
	// sourceLang := "en"
	// targetLang := "ja"
	// glossaryID := "your-glossary-id"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.BatchTranslateTextRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode:  sourceLang,
		TargetLanguageCodes: []string{targetLang},
		InputConfigs: []*translatepb.InputConfig{
			{
				Source: &translatepb.InputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{InputUri: inputURI},
				},
				// Optional. Can be "text/plain" or "text/html".
				MimeType: "text/plain",
			},
		},
		Glossaries: map[string]*translatepb.TranslateTextGlossaryConfig{
			targetLang: {
				Glossary: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			},
		},
		OutputConfig: &translatepb.OutputConfig{
			Destination: &translatepb.OutputConfig_GcsDestination{
				GcsDestination: &translatepb.GcsDestination{
					OutputUriPrefix: outputURI,
				},
			},
		},
	}

	// The BatchTranslateText operation is async.
	op, err := client.BatchTranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("BatchTranslateText: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Total characters: %v\n", resp.GetTotalCharacters())
	fmt.Fprintf(w, "Translated characters: %v\n", resp.GetTranslatedCharacters())

	return nil
}

Java

Antes de probar este código de muestra, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Java.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.BatchTranslateMetadata;
import com.google.cloud.translate.v3.BatchTranslateResponse;
import com.google.cloud.translate.v3.BatchTranslateTextRequest;
import com.google.cloud.translate.v3.GcsDestination;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.InputConfig;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BatchTranslateTextWithGlossary {

  public static void batchTranslateTextWithGlossary()
      throws InterruptedException, ExecutionException, IOException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    String outputUri = "gs://your-gcs-bucket/path/to/results/";
    String glossaryId = "your-glossary-display-name";
    batchTranslateTextWithGlossary(
        projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId);
  }

  // Batch Translate Text with a Glossary.
  public static void batchTranslateTextWithGlossary(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String inputUri,
      String outputUri,
      String glossaryId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      InputConfig inputConfig =
          InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();

      // Configure where to store the output in a GCS bucket
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      // Configure the glossary used in the request
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

      // Build the request that will be sent to the API
      BatchTranslateTextRequest request =
          BatchTranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setSourceLanguageCode(sourceLanguage)
              .addTargetLanguageCodes(targetLanguage)
              .addInputConfigs(inputConfig)
              .setOutputConfig(outputConfig)
              .putGlossaries(targetLanguage, glossaryConfig)
              .build();

      // Start an asynchronous request
      OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future =
          client.batchTranslateTextAsync(request);

      System.out.println("Waiting for operation to complete...");
      BatchTranslateResponse response = future.get(180, TimeUnit.SECONDS);
      // Display the translation for each input text provided
      System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
      System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
  }
}

Node.js

Antes de probar este código de muestra, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Node.js.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const inputUri = 'gs://cloud-samples-data/text.txt';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// const glossaryId = 'YOUR_GLOSSARY_ID';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const client = new TranslationServiceClient();
async function batchTranslateTextWithGlossary() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    sourceLanguageCode: 'en',
    targetLanguageCodes: ['es'],
    inputConfigs: [
      {
        mimeType: 'text/plain', // mime types: text/plain, text/html
        gcsSource: {
          inputUri: inputUri,
        },
      },
    ],
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
    glossaries: {
      es: {
        glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
      },
    },
  };

  try {
    // Create a job using a long-running operation
    const [operation] = await client.batchTranslateText(request);

    // Wait for the operation to complete
    const [response] = await operation.promise();

    // Display the translation for each input text provided
    console.log(`Total Characters: ${response.totalCharacters}`);
    console.log(`Translated Characters: ${response.translatedCharacters}`);
  } catch (error) {
    console.error(error.details);
  }
}

batchTranslateTextWithGlossary();

PHP

Antes de probar este código de muestra, sigue las instrucciones de configuración para PHP que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para PHP.

use Google\Cloud\Translate\V3\GcsDestination;
use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Cloud\Translate\V3\TranslateTextGlossaryConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $inputUri = 'gs://cloud-samples-data/text.txt';
// $outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $glossaryId = '[YOUR_GLOSSARY_ID]';
// $targetLanguage = 'en';
// $sourceLanguage = 'de';
$glossaryPath = $translationServiceClient->glossaryName(
    $projectId,
    $location,
    $glossaryId
);
$targetLanguageCodes = [$targetLanguage];
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';
$inputConfigsElement = (new InputConfig())
    ->setGcsSource($gcsSource)
    ->setMimeType($mimeType);
$inputConfigs = [$inputConfigsElement];
$gcsDestination = (new GcsDestination())
    ->setOutputUriPrefix($outputUri);
$outputConfig = (new OutputConfig())
    ->setGcsDestination($gcsDestination);
$formattedParent = $translationServiceClient->locationName(
    $projectId,
    $location
);
$glossariesItem = (new TranslateTextGlossaryConfig())
    ->setGlossary($glossaryPath);
$glossaries = ['ja' => $glossariesItem];

try {
    $operationResponse = $translationServiceClient->batchTranslateText(
        $formattedParent,
        $sourceLanguage,
        $targetLanguageCodes,
        $inputConfigs,
        $outputConfig,
        ['glossaries' => $glossaries]
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        // Display the translation for each input text provided
        printf('Total Characters: %s' . PHP_EOL, $response->getTotalCharacters());
        printf('Translated Characters: %s' . PHP_EOL, $response->getTranslatedCharacters());
    } else {
        $error = $operationResponse->getError();
        print($error->getMessage());
    }
} finally {
    $translationServiceClient->close();
}

Python

Antes de probar este código de muestra, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Python.

from google.cloud import translate

def batch_translate_text_with_glossary(
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/file.txt",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
    project_id="YOUR_PROJECT_ID",
    glossary_id="YOUR_GLOSSARY_ID",
    timeout=180,
):
    """Translates a batch of texts on GCS and stores the result in a GCS location.
    Glossary is applied for translation."""

    client = translate.TranslationServiceClient()

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    location = "us-central1"

    # Supported file types: https://cloud.google.com/translate/docs/supported-formats
    gcs_source = {"input_uri": input_uri}

    input_configs_element = {
        "gcs_source": gcs_source,
        "mime_type": "text/plain",  # Can be "text/plain" or "text/html".
    }
    gcs_destination = {"output_uri_prefix": output_uri}
    output_config = {"gcs_destination": gcs_destination}

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

    # glossary is a custom dictionary Translation API uses
    # to translate the domain-specific terminology.
    glossary_path = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary_path)

    glossaries = {"ja": glossary_config}  # target lang as key

    operation = client.batch_translate_text(
        request={
            "parent": parent,
            "source_language_code": "en",
            "target_language_codes": ["ja"],  # Up to 10 language codes here.
            "input_configs": [input_configs_element],
            "glossaries": glossaries,
            "output_config": output_config,
        }
    )

    print("Waiting for operation to complete...")
    response = operation.result(timeout)

    print("Total Characters: {}".format(response.total_characters))
    print("Translated Characters: {}".format(response.translated_characters))

Ruby

Antes de probar este código de muestra, sigue las instrucciones de configuración para Ruby que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Ruby.

require "google/cloud/translate"

# input_uri = "gs://cloud-samples-data/text.txt"
# output_uri = "gs://YOUR_BUCKET_ID/path_to_store_results/"
# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# glossary_id = "[YOUR_GLOSSARY_ID]"

source_lang = "en"
target_lang = "ja"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id
glossary_path = client.glossary_path project:  project_id,
                                     location: location_id,
                                     glossary: glossary_id
glossaries = {
  target_lang => { glossary: glossary_path }
}
input_config = {
  mime_type:  mime_type,
  gcs_source: { input_uri: input_uri }
}
output_config = {
  gcs_destination: { output_uri_prefix: output_uri }
}

operation = client.batch_translate_text(
  parent:                parent,
  source_language_code:  source_lang,
  target_language_codes: [target_lang],
  input_configs:         [input_config],
  output_config:         output_config,
  glossaries:            glossaries
)

# Wait until the long running operation is done
operation.wait_until_done!

response = operation.response

puts "Total Characters: #{response.total_characters}"
puts "Translated Characters: #{response.translated_characters}"

Traduce textos con un modelo y un glosario personalizados de AutoML Translation

LÍNEA DE CMD Y REST

En este ejemplo, se muestra cómo especificar un modelo y un glosario personalizados para el idioma objetivo.

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-number-or-id: el número o ID de tu proyecto de Google Cloud

Método HTTP y URL:

POST https://translation.googleapis.com/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

Cuerpo JSON de la solicitud:

{
  "models": {
    "es": "projects/project_number_or_id/locations/us-central1/models/model-id"
  },
  "sourceLanguageCode": "en",
  "targetLanguageCodes": ["es"],
  "glossaries": {
    "es": {
      "glossary": "projects/project_number_or_id/locations/us-central1/glossaries/glossary-id"
    }
  },
  "inputConfigs": [{
      "gcsSource": {
        "inputUri": "gs://bucket-name-source/input-file-name"
      }
    },
    {
      "gcsSource": {
      "inputUri": "gs://bucket-name-source/input-file-name2"
      }
    }
  ],
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "gs://bucket-name-destination/"
    }
  }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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/v3/projects/project-number-or-id/locations/us-central1:batchTranslateText " | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.BatchTranslateMetadata",
    "state": "RUNNING"
  }
}

C#

Antes de probar este código de muestra, sigue las instrucciones de configuración para C# que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para C#.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class BatchTranslateTextWithGlossaryAndModel
    {
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// Glossary is applied for translation.
        /// A model is used for translation. Can be AutoML or General (built-in) Model.
        /// </summary>
        /// <param name="targetLanguage">Target language code.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        /// <param name="modelId">Translation model ID.</param>
        /// <param name="glossaryId">Translation Glossary ID.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location"> Region.</param>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        public static void BatchTranslateTextWithGlossaryAndModelSample(
            string inputUri = "gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt",
            string outputUri = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId = "[Google Cloud Project ID]",
            string location = "us-central1",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string modelId = "[YOUR-MODEL-ID]",
            string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string modelPath = $"projects/{projectId}/locations/{location}/models/{modelId}";
            string glossaryPath = $"projects/{projectId}/locations/{location}/glossaries/{glossaryId}";

            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode = sourceLanguage,
                TargetLanguageCodes =
                {
                    // Target language code.
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
                Models =
                {
                    // A model is used for Translation.
                    { targetLanguage, modelPath },
                },
                Glossaries =
                {
                    {
                        targetLanguage, new TranslateTextGlossaryConfig
                        {
                            Glossary = glossaryPath,
                        }
                    },
                },
            };
            // Poll until the returned long-running operation is completed.
            BatchTranslateResponse response = translationServiceClient.BatchTranslateText(request).PollUntilCompleted().Result;
            Console.WriteLine($"Total Characters: {response.TotalCharacters}");
            Console.WriteLine($"Translated Characters: {response.TranslatedCharacters}");
        }
    }

Go

Antes de probar este código de muestra, sigue las instrucciones de configuración para Go que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Go.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// batchTranslateTextWithGlossaryAndModel translates a large volume of text in asynchronous batch mode.
func batchTranslateTextWithGlossaryAndModel(w io.Writer, projectID string, location string, inputURI string, outputURI string, sourceLang string, targetLang string, glossaryID string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://cloud-samples-data/text.txt"
	// outputURI := "gs://YOUR_BUCKET_ID/path_to_store_results/"
	// sourceLang := "en"
	// targetLang := "ja"
	// glossaryID := "your-glossary-id"
	// modelID := "your-model-id"

	ctx := context.Background()
	client, err := translate.NewTranslationClient(ctx)
	if err != nil {
		return fmt.Errorf("NewTranslationClient: %v", err)
	}
	defer client.Close()

	req := &translatepb.BatchTranslateTextRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode:  sourceLang,
		TargetLanguageCodes: []string{targetLang},
		InputConfigs: []*translatepb.InputConfig{
			{
				Source: &translatepb.InputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{InputUri: inputURI},
				},
				// Optional. Can be "text/plain" or "text/html".
				MimeType: "text/plain",
			},
		},
		Glossaries: map[string]*translatepb.TranslateTextGlossaryConfig{
			targetLang: {
				Glossary: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			},
		},
		OutputConfig: &translatepb.OutputConfig{
			Destination: &translatepb.OutputConfig_GcsDestination{
				GcsDestination: &translatepb.GcsDestination{
					OutputUriPrefix: outputURI,
				},
			},
		},
		Models: map[string]string{
			targetLang: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		},
	}

	// The BatchTranslateText operation is async.
	op, err := client.BatchTranslateText(ctx, req)
	if err != nil {
		return fmt.Errorf("BatchTranslateText: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Total characters: %v\n", resp.GetTotalCharacters())
	fmt.Fprintf(w, "Translated characters: %v\n", resp.GetTranslatedCharacters())

	return nil
}

Java

Antes de probar este código de muestra, sigue las instrucciones de configuración para Java que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Java.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.translate.v3.BatchTranslateMetadata;
import com.google.cloud.translate.v3.BatchTranslateResponse;
import com.google.cloud.translate.v3.BatchTranslateTextRequest;
import com.google.cloud.translate.v3.GcsDestination;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.InputConfig;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BatchTranslateTextWithGlossaryAndModel {

  public static void batchTranslateTextWithGlossaryAndModel()
      throws InterruptedException, ExecutionException, IOException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String sourceLanguage = "your-source-language";
    String targetLanguage = "your-target-language";
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    String outputUri = "gs://your-gcs-bucket/path/to/results/";
    String glossaryId = "your-glossary-display-name";
    String modelId = "YOUR-MODEL-ID";
    batchTranslateTextWithGlossaryAndModel(
        projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId, modelId);
  }

  // Batch translate text with Model and Glossary
  public static void batchTranslateTextWithGlossaryAndModel(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String inputUri,
      String outputUri,
      String glossaryId,
      String modelId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      InputConfig inputConfig =
          InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();

      // Configure where to store the output in a GCS bucket
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      OutputConfig outputConfig =
          OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      // Configure the glossary used in the request
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

      // Configure the model used in the request
      String modelPath =
          String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);

      // Build the request that will be sent to the API
      BatchTranslateTextRequest request =
          BatchTranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setSourceLanguageCode(sourceLanguage)
              .addTargetLanguageCodes(targetLanguage)
              .addInputConfigs(inputConfig)
              .setOutputConfig(outputConfig)
              .putGlossaries(targetLanguage, glossaryConfig)
              .putModels(targetLanguage, modelPath)
              .build();

      // Start an asynchronous request
      OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future =
          client.batchTranslateTextAsync(request);

      System.out.println("Waiting for operation to complete...");
      BatchTranslateResponse response = future.get(180, TimeUnit.SECONDS);
      // Display the translation for each input text provided
      System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
      System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
  }
}

Node.js

Antes de probar este código de muestra, sigue las instrucciones de configuración para Node.js que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Node.js.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const inputUri = 'gs://cloud-samples-data/text.txt';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// const glossaryId = 'YOUR_GLOSSARY_ID';
// const modelId = 'YOUR_MODEL_ID';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const client = new TranslationServiceClient();
async function batchTranslateTextWithGlossaryAndModel() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    sourceLanguageCode: 'en',
    targetLanguageCodes: ['ja'],
    inputConfigs: [
      {
        mimeType: 'text/plain', // mime types: text/plain, text/html
        gcsSource: {
          inputUri: inputUri,
        },
      },
    ],
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
    glossaries: {
      ja: {
        glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
      },
    },
    models: {
      ja: `projects/${projectId}/locations/${location}/models/${modelId}`,
    },
  };

  try {
    // Create a job using a long-running operation
    const [operation] = await client.batchTranslateText(request);

    // Wait for operation to complete
    const [response] = await operation.promise();

    // Display the translation for each input text provided
    console.log(`Total Characters: ${response.totalCharacters}`);
    console.log(`Translated Characters: ${response.translatedCharacters}`);
  } catch (error) {
    console.error(error.details);
  }
}

batchTranslateTextWithGlossaryAndModel();

PHP

Antes de probar este código de muestra, sigue las instrucciones de configuración para PHP que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para PHP.

use Google\Cloud\Translate\V3\GcsDestination;
use Google\Cloud\Translate\V3\GcsSource;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Cloud\Translate\V3\TranslateTextGlossaryConfig;
use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $inputUri = 'gs://cloud-samples-data/text.txt';
// $outputUri = 'gs://YOUR_BUCKET_ID/path_to_store_results/';
// $projectId = '[Google Cloud Project ID]';
// $location = 'us-central1';
// $targetLanguage = 'en';
// $sourceLanguage = 'de';
// $modelId = '{your-model-id}';
// $glossaryId = '[YOUR_GLOSSARY_ID]';
$glossaryPath = $translationServiceClient->glossaryName(
    $projectId,
    $location,
    $glossaryId
);
$modelPath = sprintf(
    'projects/%s/locations/%s/models/%s',
    $projectId,
    $location,
    $modelId
);
$targetLanguageCodes = [$targetLanguage];
$gcsSource = (new GcsSource())
    ->setInputUri($inputUri);

// Optional. Can be "text/plain" or "text/html".
$mimeType = 'text/plain';
$inputConfigsElement = (new InputConfig())
    ->setGcsSource($gcsSource)
    ->setMimeType($mimeType);
$inputConfigs = [$inputConfigsElement];
$gcsDestination = (new GcsDestination())
    ->setOutputUriPrefix($outputUri);
$outputConfig = (new OutputConfig())
    ->setGcsDestination($gcsDestination);
$formattedParent = $translationServiceClient->locationName($projectId, $location);
$models = ['ja' => $modelPath];
$glossariesItem = (new TranslateTextGlossaryConfig())
    ->setGlossary($glossaryPath);
$glossaries = ['ja' => $glossariesItem];

try {
    $operationResponse = $translationServiceClient->batchTranslateText(
        $formattedParent,
        $sourceLanguage,
        $targetLanguageCodes,
        $inputConfigs,
        $outputConfig,
        [
            'models' => $models,
            'glossaries' => $glossaries
        ]
    );
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        $response = $operationResponse->getResult();
        // Display the translation for each input text provided
        printf('Total Characters: %s' . PHP_EOL, $response->getTotalCharacters());
        printf('Translated Characters: %s' . PHP_EOL, $response->getTranslatedCharacters());
    } else {
        $error = $operationResponse->getError();
        print($error->getMessage());
    }
} finally {
    $translationServiceClient->close();
}

Python

Antes de probar este código de muestra, sigue las instrucciones de configuración para Python que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Python.

from google.cloud import translate

def sample_batch_translate_text_with_glossary_and_model(
    input_uri,
    output_uri,
    project_id,
    location,
    target_language,
    source_language,
    model_id,
    glossary_id,
):
    """
    Batch translate text with Glossary and Translation model
    """

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # input_uri = 'gs://cloud-samples-data/text.txt'
    # output_uri = 'gs://YOUR_BUCKET_ID/path_to_store_results/'
    # project = '[Google Cloud Project ID]'
    # location = 'us-central1'
    # target_language = 'en'
    # source_language = 'de'
    # model_id = '{your-model-id}'
    # glossary_id = '[YOUR_GLOSSARY_ID]'
    target_language_codes = [target_language]
    gcs_source = {"input_uri": input_uri}

    # Optional. Can be "text/plain" or "text/html".
    mime_type = "text/plain"
    input_configs_element = {"gcs_source": gcs_source, "mime_type": mime_type}
    input_configs = [input_configs_element]
    gcs_destination = {"output_uri_prefix": output_uri}
    output_config = {"gcs_destination": gcs_destination}
    parent = f"projects/{project_id}/locations/{location}"
    model_path = "projects/{}/locations/{}/models/{}".format(
        project_id, "us-central1", model_id
    )
    models = {target_language: model_path}

    glossary_path = client.glossary_path(
        project_id, "us-central1", glossary_id  # The location of the glossary
    )

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary_path)
    glossaries = {"ja": glossary_config}  # target lang as key

    operation = client.batch_translate_text(
        request={
            "parent": parent,
            "source_language_code": "en",
            "target_language_codes": target_language_codes,
            "input_configs": input_configs,
            "output_config": output_config,
            "models": models,
            "glossaries": glossaries,
        }
    )

    print("Waiting for operation to complete...")
    response = operation.result()

    # Display the translation for each input text provided
    print("Total Characters: {}".format(response.total_characters))
    print("Translated Characters: {}".format(response.translated_characters))

Ruby

Antes de probar este código de muestra, sigue las instrucciones de configuración para Ruby que encontrarás en la guía de inicio rápido sobre las bibliotecas cliente de Translation. Si deseas obtener más información, consulta la documentación de referencia de la API de Translation para Ruby.

require "google/cloud/translate"

# input_uri = "gs://cloud-samples-data/text.txt"
# output_uri = "gs://YOUR_BUCKET_ID/path_to_store_results/"
# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"
# model_id = "[MODEL ID]"
# glossary_id = "[YOUR_GLOSSARY_ID]"

source_lang = "en"
target_lang = "ja"
# Optional. Can be "text/plain" or "text/html".
mime_type = "text/plain"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id
glossary_path = client.glossary_path project:  project_id,
                                     location: location_id,
                                     glossary: glossary_id
model = "projects/#{project_id}/locations/#{location_id}/models/#{model_id}"
models = { target_lang => model }
glossaries = {
  target_lang => { glossary: glossary_path }
}
input_config = {
  mime_type:  mime_type,
  gcs_source: { input_uri: input_uri }
}
output_config = {
  gcs_destination: { output_uri_prefix: output_uri }
}

operation = client.batch_translate_text(
  parent:                parent,
  source_language_code:  source_lang,
  target_language_codes: [target_lang],
  input_configs:         [input_config],
  output_config:         output_config,
  models:                models,
  glossaries:            glossaries
)

# Wait until the long running operation is done
operation.wait_until_done!

response = operation.response

puts "Total Characters: #{response.total_characters}"
puts "Translated Characters: #{response.translated_characters}"

Estado de la operación

Una solicitud por lotes es una operación de larga duración, por lo que puede tomar una cantidad considerable de tiempo en completarse. Puedes consultar el estado de esta operación para ver si se completó o puedes cancelar la operación.

Para obtener más información, consulta la página sobre las operaciones de larga duración.