일괄 요청(Advanced)

오프라인에서 명령어로 일괄 번역을 수행하면 대량의 텍스트(배치당 파일 한도 100개)를 다양한 타겟 언어(최대 10개)로 번역할 수 있습니다. 총 콘텐츠 크기는 100M 유니코드 코드포인트 이하여야 하며 UTF-8 인코딩을 사용해야 합니다.

시작하기 전에

Cloud Translation API를 사용을 시작하려면 Cloud Translation API가 사용 설정된 프로젝트가 있고 적절한 사용자 인증 정보가 있어야 합니다. 공통 프로그래밍 언어용 클라이언트 라이브러리를 설치하여 API를 호출할 수도 있습니다. 자세한 내용은 설정 페이지를 참조하세요.

권한

일괄 번역의 경우 Cloud Translation 권한 외에 Cloud Storage 버킷에 대한 액세스 권한이 있어야 합니다. 일괄 번역 입력 파일은 Cloud Storage 버킷에서 읽어오고 출력 파일은 Cloud Storage 버킷에 기록됩니다. 예를 들어 버킷에서 입력 파일을 읽어오려면 최소한 버킷에 대한 읽기 객체 권한(roles/storage.objectViewer 역할로 제공됨)이 있어야 합니다. Cloud Storage 역할에 대한 자세한 내용은 Cloud Storage 문서를 참조하세요.

입력 파일

text/html(HTML) 및 text/plain(.tsv 및 .txt)이라는 두 가지 MIME 유형만 지원됩니다.

TSV 파일 사용

파일 확장자가 TSV이면 열 1~2개를 포함할 수 있습니다. 첫 번째 열(선택 사항)은 텍스트 요청의 ID입니다. 첫 번째 열이 없으면 Google은 입력 파일의 행 번호(0 기반)를 출력 파일의 ID로 사용합니다. 두 번째 열은 번역할 실제 텍스트입니다. 최상의 결과를 얻으려면 각 행이 유니코드 코드포인트 10,000개 이하여야 합니다. 그렇지 않으면 오류가 반환 될 수 있습니다.

텍스트 또는 HTML 사용

지원되는 다른 파일 확장자는 텍스트 파일(.txt) 또는 HTML이며 하나의 큰 텍스트 덩어리로 처리됩니다.

일괄 요청

일괄 번역을 요청할 때는 번역할 콘텐츠가 포함된 입력 구성 파일(InputConfig)과 최종 번역을 저장할 출력 위치(OutputConfig)의 경로를 제공합니다. Cloud Storage 버킷이 최소 두 개 필요합니다. 소스 버킷에는 번역할 콘텐츠가 포함되고 대상 버킷에는 번역된 결과 파일이 포함됩니다. 번역 프로세스가 시작되기 전에 대상 폴더가 비어 있어야 합니다.

요청이 처리됨에 따라 결과가 실시간으로 출력 위치에 기록됩니다. 사용자가 도중에 요청을 취소하더라도 입력 파일 수준의 부분 출력이 여전히 출력 Cloud Storage 위치에 생성됩니다. 따라서 번역된 문자 수만큼 요금이 계속 청구됩니다.

REST

이 예시에서는 번역을 위해 전송된 입력 파일 두 개를 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText

JSON 요청 본문:

{
  "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/"
      }
   }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "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"
  }
}
응답에는 장기 실행 작업의 ID가 포함됩니다.

Go

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Go API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Java API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.ThreadLocalRandom;
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...");

      // random number between 300 - 450 (maximum allowed seconds)
      long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
      BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS);

      System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
      System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Node.js API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  // Setup timeout for long-running operation. Timeout specified in ms.
  const options = {timeout: 240000};
  // Batch translate text using a long-running operation with a timeout of 240000ms.
  const [operation] = await translationClient.batchTranslateText(
    request,
    options
  );

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

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

batchTranslateText();

Python

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Python API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import translate

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

    Args:
        input_uri: The input URI of the texts to be translated.
        output_uri: The output URI of the translated texts.
        project_id: The ID of the project that owns the destination bucket.
        timeout: The timeout for this batch translation operation.

    Returns:
        The translated texts.
    """

    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/languages
    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(f"Total Characters: {response.total_characters}")
    print(f"Translated Characters: {response.translated_characters}")

    return response

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Cloud Translation 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 Cloud Translation 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Cloud Translation 참조 문서를 참조하세요.

AutoML 모델을 사용하여 일괄 요청

일괄 요청에 커스텀 모델을 사용할 수 있습니다. 여러 도착어가 관련되어 있는 경우 다양한 시나리오가 있습니다.

도착어에 대한 AutoML 모델 지정

REST

이 예시에서는 도착어의 커스텀 모델을 지정하는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText

JSON 요청 본문:

{
  "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/"
      }
   }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "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"
  }
}
응답에는 장기 실행 작업의 ID가 포함됩니다.

Go

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Go API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Java API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.ThreadLocalRandom;
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...");

      // random number between 300 - 450 (maximum allowed seconds)
      long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
      BatchTranslateResponse response = future.get(randomNumber, 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

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Node.js API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  const options = {timeout: 240000};
  // Create a job using a long-running operation
  const [operation] = await client.batchTranslateText(request, options);

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

batchTranslateTextWithModel();

Python

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Python API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import translate

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

    Args:
        input_uri: The input file to translate.
        output_uri: The output file to save the translation results.
        project_id: The ID of the GCP project that owns the model.
        model_id: The model ID.

    Returns:
        The response from the batch translation API.
    """

    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(f"Total Characters: {response.total_characters}")
    print(f"Translated Characters: {response.translated_characters}")

    return response

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Cloud Translation 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 Cloud Translation 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Cloud Translation 참조 문서를 참조하세요.

여러 도착어에 대한 AutoML 모델 지정

REST

도착어가 여러 개인 경우 각 도착어에 커스텀 모델을 지정할 수 있습니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText

JSON 요청 본문:

{
  "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/"
      }
   }
 }

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "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"
  }
}
응답에는 장기 실행 작업의 ID가 포함됩니다.

특정 도착어에 대한 AutoML 모델 지정

다른 도착어가 아닌 특정 도착어에 커스텀 모델을 지정할 수 있습니다. 여러 도착어에 커스텀 모델 지정 코드를 사용하여 models 필드를 수정하면 모델의 도착어(이 예시에서 es)를 지정하고 fr은 지정하지 않습니다.

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

여기서 PROJECT_NUMBER_OR_ID는 Google Cloud 프로젝트 번호 또는 ID이고 model-id는 AutoML 모델에 지정한 이름입니다.

용어집을 사용하여 텍스트 번역

REST

이 예시에서는 도착어에 용어집을 지정하는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • glossary-id: 용어집 ID(예: 'my-en-to-es-glossary')

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText

JSON 요청 본문:

{
  "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/"
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

다음과 비슷한 JSON 응답이 표시됩니다.

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

Go

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Go API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Java API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.ThreadLocalRandom;
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...");

      // random number between 300 - 450 (maximum allowed seconds)
      long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
      BatchTranslateResponse response = future.get(randomNumber, 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

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Node.js API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  const options = {timeout: 240000};
  // Create a job using a long-running operation
  const [operation] = await client.batchTranslateText(request, options);

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

batchTranslateTextWithGlossary();

Python

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Python API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import translate

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

    Args:
        input_uri (str): The input file to translate.
        output_uri (str): The output file to save the translations to.
        project_id (str): The ID of the GCP project that owns the location.
        glossary_id (str): The ID of the glossary to use.
        timeout (int): The amount of time, in seconds, to wait for the operation to complete.

    Returns:
        The response from the batch.
    """

    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(f"Total Characters: {response.total_characters}")
    print(f"Translated Characters: {response.translated_characters}")

    return response

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Cloud Translation 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 Cloud Translation 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Cloud Translation 참조 문서를 참조하세요.

AutoML Translation 커스텀 모델 및 용어집을 사용하여 텍스트 번역

REST

이 예시에서는 도착어에 커스텀 모델과 용어집을 지정하는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText

JSON 요청 본문:

{
  "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/"
    }
  }
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1:batchTranslateText"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

다음과 비슷한 JSON 응답이 표시됩니다.

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

Go

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Go API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Java API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.ThreadLocalRandom;
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...");

      // random number between 300 - 450 (maximum allowed seconds)
      long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
      BatchTranslateResponse response = future.get(randomNumber, 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

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Node.js API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  const options = {timeout: 240000};
  // Create a job using a long-running operation
  const [operation] = await client.batchTranslateText(request, options);

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

batchTranslateTextWithGlossaryAndModel();

Python

이 샘플을 사용해 보기 전에 Cloud Translation 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Cloud Translation Python API 참조 문서를 확인하세요.

Cloud Translation에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import translate

def batch_translate_text_with_glossary_and_model(
    input_uri: str,
    output_uri: str,
    project_id: str,
    model_id: str,
    glossary_id: str,
) -> translate.TranslateTextResponse:
    """Batch translate text with Glossary and Translation model.
    Args:
        input_uri: The input text to be translated.
        output_uri: The output text to be translated.
        project_id: The ID of the GCP project that owns the model.
        model_id: The ID of the model
        glossary_id: The ID of the glossary

    Returns:
        The translated text.
    """

    client = translate.TranslationServiceClient()

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

    target_language_codes = ["ja"]
    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 = {"ja": 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(f"Total Characters: {response.total_characters}")
    print(f"Translated Characters: {response.translated_characters}")

    return response

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Cloud Translation 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 Cloud Translation 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Cloud Translation 참조 문서를 참조하세요.

작업 상태

일괄 요청은 장기 실행 작업이므로 완료하는 데 상당한 시간이 걸릴 수 있습니다. 이 작업의 상태를 폴링하여 작업이 완료되었는지 확인하거나 작업을 취소할 수 있습니다.

자세한 내용은 장기 실행 작업을 참조하세요.

추가 리소스

  • 일반적인 문제 또는 오류를 해결하는 데 도움이 필요하면 문제 해결 페이지를 참조하세요.