용어집 만들기 및 사용(Advanced)

용어집은 Cloud Translation API가 분야별 용어를 일관성 있게 번역하는 데 사용하는 커스텀 사전입니다. 여기에는 일반적으로 명명된 항목을 번역하는 방법을 지정하는 과정이 포함됩니다.

다음과 같은 사용 사례에 용어집을 사용할 수 있습니다.

  • 제품 이름: 예를 들어 'Google Home'은 'Google Home'으로 번역해야 합니다.
  • 모호한 단어: 예를 들어 'bat'라는 단어는 스포츠 장비나 동물을 의미할 수 있습니다. 스포츠와 관련된 단어를 번역하는 중이라면 용어집을 사용하여 'bat'라는 단어에 동물에 대한 번역이 아니라 스포츠에 대한 번역을 Cloud Translation API에 제공할 수 있습니다.
  • 차용어: 예를 들어 프랑스어 'bouillabaisse'는 영어로도 'bouillabaisse'입니다. 'bouillabaisse'라는 영어 단어는 19세기 프랑스어에서 들어왔습니다. 따라서 프랑스 문화에 대한 지식이 없는 영어 화자는 bouillabaisse가 '부야베스'라는 생선 스튜 요리라는 것을 모를 수 있습니다. 프랑스어 'bouillabaisse'가 영어 'fish stew'로 번역되도록 용어집 번역을 재정의할 수 있습니다.

시작하기 전에

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

필수 권한

용어집을 사용하려면 서비스 계정에 용어집 관련 권한이 필요합니다. Cloud Translation API 편집자(roles/cloudtranslate.editor)와 같은 사전 정의된 IAM 역할 중 하나를 사용하여 서비스 계정에 역할을 부여하거나 필요한 권한을 부여하는 커스텀 역할을 생성할 수 있습니다. IAM 권한 참조에서 모든 Cloud Translation API 권한을 볼 수 있습니다. Cloud Translation 권한은 cloudtranslate로 시작합니다.

용어집을 만들려면 용어집 파일이 있는 Cloud Storage 버킷의 객체를 읽을 수 있는 권한도 필요합니다. 스토리지 객체 뷰어(roles/storage.objectViewer)와 같은 사전 정의된 IAM 역할 중 하나를 사용하여 서비스 계정에 역할을 부여하거나 객체를 읽을 수 있는 권한을 부여하는 커스텀 역할을 생성할 수 있습니다.

역할에 계정을 추가하는 방법에 대한 자세한 내용은 리소스에 대한 액세스 권한 부여, 변경, 취소를 참조하세요.

용어집 만들기

단일 토큰(단어) 또는 짧은 구문(보통 5단어 미만)이 용어집의 용어로 사용될 수 있습니다. 용어집 사용의 주요 단계는 다음과 같습니다.

  1. 용어집 파일 만들기
  2. Cloud Translation API를 사용하여 용어집 리소스 만들기
  3. 번역 요청 시 사용할 용어집 지정

한 프로젝트에 용어집이 여러 개 있을 수 있습니다. 사용 가능한 용어집 목록을 가져오고 더 이상 필요하지 않은 용어집을 삭제할 수 있습니다.

검색 제외 단어

Cloud Translation은 용어집에 포함된 일부 용어를 무시합니다. 이러한 용어를 검색 제외 단어라고 합니다. 검색 제외 단어를 번역할 때 Cloud Translation은 일치하는 용어집 항목을 무시합니다. 모든 검색 제외 단어 목록은 용어집을 참조하세요.

용어집 파일 만들기

기본적으로 용어집은 각 줄에 특정 용어가 여러 언어로 포함된 텍스트 파일입니다. Cloud Translation API는 한 쌍의 출발어 및 도착어에 원하는 번역을 지정하는 단방향 용어집과 여러 언어의 용어를 지정하는 동의어 세트를 모두 지원합니다.

용어집 입력 파일의 총 용어 수는 모든 용어를 모든 언어로 조합한 경우 1,040만(10,485,760) UTF-8 바이트를 초과할 수 없습니다. 용어집의 각 용어는 1,024 UTF-8 바이트 미만이어야 합니다. 1,024바이트를 초과하는 용어는 무시됩니다.

기본적으로 용어집 일치는 대소문자를 구분합니다. 용어집을 적용할 때 모든 항목의 대소문자를 무시할 수 있습니다. 대소문자를 구분하는 용어와 대소문자를 구분하지 않는 용어를 혼합하여 사용하는 경우 기본 동작을 사용하고, 대소문자를 구분하지 않는 용어의 경우 용어집에 두 양식을 모두 포함합니다.

단방향 용어집

Cloud Translation API는 TSV, CSV 또는 TMX 파일을 허용합니다.

TSV 및 CSV

탭으로 구분된 값(TSV)과 쉼표로 구분된 값(CSV)의 경우 각 행에는 탭(\t) 또는 쉼표(,)로 구분된 용어 쌍이 포함되어 있습니다. 다음 예시와 같이 첫 번째 열에는 출발어의 용어가 포함되고 두 번째 열에는 도착어의 용어가 포함됩니다.

단방향 용어집

Translation Memory eXchange(TMX)

Translation Memory eXchange(TMX)는 출발어와 도착어 번역을 제공하는 표준 XML 형식입니다. Cloud Translation API은 TMX 버전 1.4를 기반으로 하는 형식의 입력 파일을 지원합니다. 이 예에서는 필수 구조를 보여줍니다.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <header segtype="sentence" o-tmf="UTF-8"
  adminlang="en" srclang="en" datatype="PlainText"/>
  <body>
    <tu>
      <tuv xml:lang="en">
        <seg>account</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>cuenta</seg>
      </tuv>
    </tu>
    <tu>
      <tuv xml:lang="en">
        <seg>directions</seg>
      </tuv>
      <tuv xml:lang="es">
        <seg>indicaciones</seg>
      </tuv>
    </tu>
  </body>
</tmx>

올바른 형식의 TMX 파일에서 <header> 요소는 srclang 속성을 사용하여 출발어를 지정해야 하고, 모든 <tuv> 요소는 xml:lang 속성을 사용하여 포함된 텍스트의 언어를 지정해야 합니다. ISO-639 코드를 사용하여 출발어와 도착어를 지정하세요.

모든 <tu> 요소에는 출발어와 도착어가 동일한 <tuv> 요소 쌍이 포함되어야 합니다. <tu> 요소에 <tuv> 요소가 3개 이상 포함되어 있으면 Cloud Translation API는 출발어 및 도착어와 일치하는 첫 번째 <tuv> 요소만 처리하고 나머지는 무시합니다. <tu> 요소에 일치하는 <tuv> 요소 쌍이 없으면 Cloud Translation API는 잘못된 <tu> 요소를 건너뜁니다.

Cloud Translation API는 <seg> 요소를 처리하기 전에 주위의 마크업 태그를 제거합니다. <tuv> 요소에 <seg> 요소가 2개 이상 포함되어 있으면 Cloud Translation API는 텍스트를 사이에 공백이 있는 단일 요소로 연결합니다.

위에 표시되지 않은 XML 태그가 파일에 포함되어 있으면 Cloud Translation API가 해당 태그를 무시합니다.

파일이 올바른 XML 및 TMX 형식을 따르지 않는 경우(예: 종료 태그 또는 <tmx> 요소가 없는 경우) Cloud Translation API는 해당 요소 처리를 취소합니다. 또한 잘못된 <tu> 요소를 1,024개 넘게 건너뛴 경우에도 Cloud Translation API가 처리를 취소합니다.

동의어 세트(CSV)

동의어 세트의 경우 Cloud Translation API는 CSV 형식의 파일만 허용합니다. 동의어 세트를 정의하려면 각 줄에 여러 언어의 용어가 나열되는 다중 열 CSV 파일을 만듭니다.

이 파일의 첫 번째 행은 ISO-639 또는 BCP-47 언어 코드를 사용하여 각 열의 언어를 지정하는 헤더 행입니다. 또한 품사(pos) 및 설명(description)에 해당하는 선택적 열도 포함할 수 있습니다. 알고리즘은 현재 pos 정보를 사용하지 않으며 특정 pos 값의 유효성은 검사되지 않습니다.

각 후속 행에는 헤더에 지정된 언어의 동의어가 포함됩니다. 해당 용어가 모든 언어로 제공되지 않은 경우 열을 비워 둘 수 있습니다.

동의어 세트

용어집 리소스 만들기

동의어를 지정했으면 용어집 리소스를 만들어 Cloud Translation API에 용어집 파일을 제공합니다.

단방향 용어집

단방향 용어집을 만들 때는 출발어(source_language_code)와 도착어(target_language_code)를 지정하여 언어 쌍(language_pair)을 지정해야 합니다. 다음 예시에서는 REST API 및 명령줄을 사용하지만 클라이언트 라이브러리를 사용하여 단방향 용어집을 만들 수도 있습니다.

REST

새 용어집을 만들 때 용어집 ID(리소스 이름)를 지정합니다. 예를 들면 다음과 같습니다.
projects/my-project/locations/us-central1/glossaries/my-en-to-ru-glossary
여기서 my-project는 프로젝트 번호 또는 ID이고 my-en-ru-glossary는 사용자가 제공한 용어집 ID입니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • glossary-id: 용어집 ID(예: my_en_ru_glossary)
  • bucket-name: 용어집 파일이 있는 버킷의 이름
  • glossary-filename: 용어집 파일 이름

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
    },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://bucket-name/glossary-filename"
    }
  }
}

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

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

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-19T19:05:10.650047636Z"
  }
}

동의어 세트 용어집

동의어 세트에 용어집 용어를 지정했으면 용어집 리소스를 만들어 Cloud Translation API에 용어집 파일을 제공합니다.

REST

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • glossary-id: 용어집 ID
  • bucket-name: 용어집 파일이 있는 버킷의 이름
  • glossary-filename: 용어집 파일 이름

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id",
  "languageCodesSet": {
    "languageCodes": ["en", "en-GB", "ru", "fr", "pt-BR", "pt-PT", "es"]
  },
  "inputConfig": {
    "gcsSource": {
"inputUri": "gs://bucket-name/glossary-file-name"
    }
  }
}

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

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

{
  "name": "projects/project-number/locations/us-central1/operations/20191103-09061569945989-5d937985-0000-21ac-816d-f4f5e80782d4",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3beta1.CreateGlossaryMetadata",
    "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "state": "RUNNING",
    "submitTime": "2019-11-03T16:06:29.134496675Z"
  }
}

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"
)

// createGlossary creates a glossary to use for other operations.
func createGlossary(w io.Writer, projectID string, location string, glossaryID string, glossaryInputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "my-glossary-display-name"
	// glossaryInputURI := "gs://cloud-samples-data/translation/glossary.csv"

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

	req := &translatepb.CreateGlossaryRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Glossary: &translatepb.Glossary{
			Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
			Languages: &translatepb.Glossary_LanguageCodesSet_{
				LanguageCodesSet: &translatepb.Glossary_LanguageCodesSet{
					LanguageCodes: []string{"en", "ja"},
				},
			},
			InputConfig: &translatepb.GlossaryInputConfig{
				Source: &translatepb.GlossaryInputConfig_GcsSource{
					GcsSource: &translatepb.GcsSource{
						InputUri: glossaryInputURI,
					},
				},
			},
		},
	}

	// The CreateGlossary operation is async.
	op, err := client.CreateGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateGlossary: %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, "Created: %v\n", resp.GetName())
	fmt.Fprintf(w, "Input URI: %v\n", resp.InputConfig.GetGcsSource().GetInputUri())

	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.CreateGlossaryMetadata;
import com.google.cloud.translate.v3.CreateGlossaryRequest;
import com.google.cloud.translate.v3.GcsSource;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryInputConfig;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class CreateGlossary {

  public static void createGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    List<String> languageCodes = new ArrayList<>();
    languageCodes.add("your-language-code");
    String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt";
    createGlossary(projectId, glossaryId, languageCodes, inputUri);
  }

  // Create a equivalent term sets glossary
  // https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
  public static void createGlossary(
      String projectId, String glossaryId, List<String> languageCodes, String inputUri)
      throws IOException, ExecutionException, InterruptedException {

    // 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);
      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);

      // Supported Languages: https://cloud.google.com/translate/docs/languages
      Glossary.LanguageCodesSet languageCodesSet =
          Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build();

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
      GlossaryInputConfig inputConfig =
          GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build();

      Glossary glossary =
          Glossary.newBuilder()
              .setName(glossaryName.toString())
              .setLanguageCodesSet(languageCodesSet)
              .setInputConfig(inputConfig)
              .build();

      CreateGlossaryRequest request =
          CreateGlossaryRequest.newBuilder()
              .setParent(parent.toString())
              .setGlossary(glossary)
              .build();

      // Start an asynchronous request
      OperationFuture<Glossary, CreateGlossaryMetadata> future =
          client.createGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      Glossary response = future.get();
      System.out.println("Created Glossary.");
      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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 = 'global';
// const glossaryId = 'your-glossary-display-name';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function createGlossary() {
  // Construct glossary
  const glossary = {
    languageCodesSet: {
      languageCodes: ['en', 'es'],
    },
    inputConfig: {
      gcsSource: {
        inputUri: 'gs://cloud-samples-data/translation/glossary.csv',
      },
    },
    name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };

  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    glossary: glossary,
  };

  // Create glossary using a long-running operation
  const [operation] = await translationClient.createGlossary(request);

  // Wait for the operation to complete
  await operation.promise();

  console.log('Created glossary:');
  console.log(`InputUri ${request.glossary.inputConfig.gcsSource.inputUri}`);
}

createGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def create_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    input_uri: str = "YOUR_INPUT_URI",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """
    Create a equivalent term sets glossary. Glossary can be words or
    short phrases (usually fewer than five words).
    https://cloud.google.com/translate/docs/advanced/glossary#format-glossary
    """
    client = translate.TranslationServiceClient()

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    source_lang_code = "en"
    target_lang_code = "ja"
    location = "us-central1"  # The location of the glossary

    name = client.glossary_path(project_id, location, glossary_id)
    language_codes_set = translate.types.Glossary.LanguageCodesSet(
        language_codes=[source_lang_code, target_lang_code]
    )

    gcs_source = translate.types.GcsSource(input_uri=input_uri)

    input_config = translate.types.GlossaryInputConfig(gcs_source=gcs_source)

    glossary = translate.types.Glossary(
        name=name, language_codes_set=language_codes_set, input_config=input_config
    )

    parent = f"projects/{project_id}/locations/{location}"
    # glossary is a custom dictionary Translation API uses
    # to translate the domain-specific terminology.
    operation = client.create_glossary(parent=parent, glossary=glossary)

    result = operation.result(timeout)
    print(f"Created: {result.name}")
    print(f"Input Uri: {result.input_config.gcs_source.input_uri}")

    return result

추가 언어

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

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

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

작업 상태

용어집 리소스 만들기는 장기 실행 작업이므로 완료하는 데 상당한 시간이 걸릴 수 있습니다. 이 작업의 상태를 폴링하여 작업이 완료되었는지 확인하거나 작업을 취소할 수 있습니다.

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

용어집 사용

용어집으로 텍스트 번역

Cloud Translation - Advanced에서 텍스트 번역에 사용할 번역 모델을 명시적으로 지정합니다. 또한 분야별 용어에 사용할 용어집을 지정할 수도 있습니다.

REST

이 예시에서는 기본 NMT 모델과 용어집을 사용하여 텍스트를 번역합니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • glossary-id: 용어집 ID(예: my-en-ru-glossary)
  • BOOLEAN: 일치에 대소문자를 구분하지 않는지 여부입니다. 기본적으로 이 값은 false입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": "Dr. Watson, please discard your trash. You've shared unsolicited email with me. Let's talk about spam and importance ranking in a confidential mode.",
  "glossaryConfig": {
    "glossary": "projects/project-number/locations/us-central1/glossaries/glossary-id",
    "ignoreCase": BOOLEAN
  }
}

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

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

{
  "glossaryTranslations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со я . Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
    "glossaryConfig": {
      "glossary": "projects/project-number/locations/us-central1/glossaries/glossary-id",
      "ignoreCase": BOOLEAN
    }
  },
  "translations": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора. Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о спаме и важности рейтинга в конфиденциальном режиме.",
  }
}

translations 필드에는 용어집이 적용되기 전의 일반적인 기계 번역이 포함되고, glossaryTranslations 필드에는 용어집이 적용된 후의 번역이 포함됩니다.

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"
)

// translateTextWithGlossary translates input text and returns translated text.
func translateTextWithGlossary(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "ja"
	// text := "Hello world"
	// 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.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
		GlossaryConfig: &translatepb.TranslateTextGlossaryConfig{
			Glossary: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
		},
	}

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

	// Display the translation for each input text provided
	for _, translation := range resp.GetGlossaryTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslateTextRequest;
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class TranslateTextWithGlossary {

  public static void translateTextWithGlossary() throws IOException {
    // 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 text = "your-text";
    String glossaryId = "your-glossary-display-name";
    translateTextWithGlossary(projectId, sourceLanguage, targetLanguage, text, glossaryId);
  }

  // Translates a given text using a glossary.
  public static void translateTextWithGlossary(
      String projectId,
      String sourceLanguage,
      String targetLanguage,
      String text,
      String glossaryId)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      String location = "us-central1";
      LocationName parent = LocationName.of(projectId, location);

      GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
      TranslateTextGlossaryConfig glossaryConfig =
          TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();

      // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
      TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setSourceLanguageCode(sourceLanguage)
              .setTargetLanguageCode(targetLanguage)
              .addContents(text)
              .setGlossaryConfig(glossaryConfig)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getGlossaryTranslationsList()) {
        System.out.printf("Translated text: %s\n", translation.getTranslatedText());
      }
    }
  }
}

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 = 'global';
// const glossaryId = 'YOUR_GLOSSARY_ID';
// const text = 'text to translate';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();
async function translateTextWithGlossary() {
  const glossaryConfig = {
    glossary: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'es',
    glossaryConfig: glossaryConfig,
  };

  // Run request
  const [response] = await translationClient.translateText(request);

  for (const translation of response.glossaryTranslations) {
    console.log(`Translation: ${translation.translatedText}`);
  }
}

translateTextWithGlossary();

Python

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

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


from google.cloud import translate

def translate_text_with_glossary(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
) -> translate.TranslateTextResponse:
    """Translates a given text using a glossary.

    Args:
        text: The text to translate.
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to use.

    Returns:
        The translated text."""
    client = translate.TranslationServiceClient()
    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"

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

    glossary_config = translate.TranslateTextGlossaryConfig(glossary=glossary)

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.translate_text(
        request={
            "contents": [text],
            "target_language_code": "ja",
            "source_language_code": "en",
            "parent": parent,
            "glossary_config": glossary_config,
        }
    )

    print("Translated text: \n")
    for translation in response.glossary_translations:
        print(f"\t {translation.translated_text}")

    return response

추가 언어

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

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

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

용어집에 관한 정보 가져오기

REST

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

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

HTTP 메서드 및 URL:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

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

{
  "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
  "languagePair": {
    "sourceLanguageCode": "en",
    "targetLanguageCode": "ru"
  },
  "inputConfig": {
    "gcsSource": {
  "inputUri": "gs://bucket-name/glossary-file-name"
    }
  },
  "entryCount": 9603
}

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"
)

// getGlossary gets the specified glossary.
func getGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.GetGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

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

	fmt.Fprintf(w, "Glossary name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Entry count: %v\n", resp.GetEntryCount())
	fmt.Fprintf(w, "Input URI: %v\n", resp.GetInputConfig().GetGcsSource().GetInputUri())

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetGlossaryRequest;
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetGlossary {

  public static void getGlossary() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    getGlossary(projectId, glossaryId);
  }

  // Get a particular glossary based on the glossary ID
  public static void getGlossary(String projectId, String glossaryId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      GetGlossaryRequest request =
          GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      Glossary response = client.getGlossary(request);

      System.out.printf("Glossary name: %s\n", response.getName());
      System.out.printf("Entry count: %s\n", response.getEntryCount());
      System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
  }
}

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 = 'global';
// const glossaryId = 'YOUR_GLOSSARY_ID';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getGlossary() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };

  // Get glossary
  const [response] = await translationClient.getGlossary(request);

  console.log(`Glossary name: ${response.name}`);
  console.log(`Entry count: ${response.entryCount}`);
  console.log(`Input URI: ${response.inputConfig.gcsSource.inputUri}`);
}

getGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def get_glossary(
    project_id: str = "YOUR_PROJECT_ID", glossary_id: str = "YOUR_GLOSSARY_ID"
) -> translate.Glossary:
    """Get a particular glossary based on the glossary ID.

    Args:
        project_id: The GCP project ID.
        glossary_id: The ID of the glossary to retrieve.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    response = client.get_glossary(name=name)
    print(f"Glossary name: {response.name}")
    print(f"Entry count: {response.entry_count}")
    print(f"Input URI: {response.input_config.gcs_source.input_uri}")

    return response

추가 언어

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

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

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

용어집 나열

한 프로젝트에 수많은 용어집이 포함될 수 있습니다. 이 섹션에서는 특정 프로젝트에 사용할 수 있는 용어집의 목록을 검색하는 방법을 설명합니다.

REST

이 예시에서는 지정된 프로젝트와 관련된 모든 용어집을 나열합니다.

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

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

HTTP 메서드 및 URL:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries

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

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

{
  "glossaries": [
    {
      "name": "projects/project-number/locations/us-central1/glossaries/glossary-id",
      "languagePair": {
        "sourceLanguageCode": "en",
        "targetLanguageCode": "ru"
      },
      "inputConfig": {
        "gcsSource": {
          "inputUri": "gs://bucket-name/glossary-file-name"
        }
      },
      "entryCount": 9603
    },
    ...
  ]
}

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"
	"google.golang.org/api/iterator"
)

// listGlossaries gets the specified glossary.
func listGlossaries(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

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

	req := &translatepb.ListGlossariesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListGlossaries(ctx, req)

	// Iterate over all results
	for {
		glossary, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListGlossaries.Next: %w", err)
		}
		fmt.Fprintf(w, "Name: %v\n", glossary.GetName())
		fmt.Fprintf(w, "Entry count: %v\n", glossary.GetEntryCount())
		fmt.Fprintf(w, "Input URI: %v\n", glossary.GetInputConfig().GetGcsSource().GetInputUri())
		for _, languageCode := range glossary.GetLanguageCodesSet().GetLanguageCodes() {
			fmt.Fprintf(w, "Language code: %v\n", languageCode)
		}
		if languagePair := glossary.GetLanguagePair(); languagePair != nil {
			fmt.Fprintf(w, "Language pair: %v, %v\n",
				languagePair.GetSourceLanguageCode(), languagePair.GetTargetLanguageCode())
		}
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.ListGlossariesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class ListGlossaries {

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

  // List all the glossaries in a specified location
  public static void listGlossaries(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "us-central1");
      ListGlossariesRequest request =
          ListGlossariesRequest.newBuilder().setParent(parent.toString()).build();

      for (Glossary responseItem : client.listGlossaries(request).iterateAll()) {
        System.out.printf("Glossary name: %s\n", responseItem.getName());
        System.out.printf("Entry count: %s\n", responseItem.getEntryCount());
        System.out.printf(
            "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri());
      }
    }
  }
}

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 = 'global';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function listGlossaries() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  // Run request
  const [response] = await translationClient.listGlossaries(request);

  for (const glossary of response) {
    console.log(`Name: ${glossary.name}`);
    console.log(`Entry count: ${glossary.entryCount}`);
    console.log(`Input uri: ${glossary.inputConfig.gcsSource.inputUri}`);
    for (const languageCode of glossary.languageCodesSet.languageCodes) {
      console.log(`Language code: ${languageCode}`);
    }
  }
}

listGlossaries();

Python

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

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

from google.cloud import translate

def list_glossaries(project_id: str = "YOUR_PROJECT_ID") -> translate.Glossary:
    """List Glossaries.

    Args:
        project_id: The GCP project ID.

    Returns:
        The glossary.
    """
    client = translate.TranslationServiceClient()

    location = "us-central1"

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

    # Iterate over all results
    for glossary in client.list_glossaries(parent=parent):
        print(f"Name: {glossary.name}")
        print(f"Entry count: {glossary.entry_count}")
        print(f"Input uri: {glossary.input_config.gcs_source.input_uri}")

        # Note: You can create a glossary using one of two modes:
        # language_code_set or language_pair. When listing the information for
        # a glossary, you can only get information for the mode you used
        # when creating the glossary.
        for language_code in glossary.language_codes_set.language_codes:
            print(f"Language code: {language_code}")

    return glossary

추가 언어

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

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

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

용어집 업데이트

용어집을 업데이트하여 이름을 변경하거나 모든 항목을 새 용어집 입력 파일로 바꿀 수 있습니다. 용어집 항목의 변경사항을 롤백해야 하는 경우 원래 용어집 파일을 사용하여 수정된 용어집을 대체해야 합니다.

REST

용어집을 업데이트하려면 glossary.patch 메서드를 사용하여 PATCH 요청을 보냅니다. 다음 예시에서는 동의어 세트 용어집을 업데이트합니다. list 메서드를 사용하여 특정 용어집의 ID를 찾습니다.

update_mask 쿼리 매개변수는 용어집 입력 파일, 용어집 표시 이름 또는 둘 모두를 업데이트할 것인지 지정합니다. 하나 이상의 업데이트 마스크 매개변수가 필요합니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 기존 용어집의 ID입니다.
  • LANGUAGE_CODE: 이 동의어 세트 용어집의 언어를 지정하는 언어 코드입니다.
  • GLOSSARY_FILE_PATH: 용어집 입력 파일의 위치와 파일 이름입니다.

HTTP 메서드 및 URL:

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID?update_mask=input_config&update_mask=display_name

JSON 요청 본문:

{
  "name":"projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID",
  "languageCodesSet": {
    "languageCodes": ["LANGUAGE_CODE", ...]
  },
  "inputConfig": {
    "gcsSource": {
      "inputUri": "gs://GLOSSARY_FILE_PATH"
    }
  }
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.translation.v3.UpdateGlossaryMetadata",
    "glossary": {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID",
      "languageCodesSet": {
        "languageCodes": ["LANGUAGE_CODE", ...]
      },
      "inputConfig": {
        "gcsSource": {
        "inputUri": "gs://GLOSSARY_FILE_PATH"
        }
      },
      "entryCount": NUMBER_OF_ENTRIES,
      "submitTime": "2022-04-22T23:16:30.628806944Z",
      "endTime": "2022-04-22T23:41:15.115797Z",
      "displayName": "GLOSSARY_ID"
    },
    "state": "RUNNING",
    "submitTime": "2022-04-22T23:50:24.337964527Z"
  }
}

추가 언어

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

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

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

용어집 삭제

다음 예시에서는 용어집을 삭제합니다.

REST

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • glossary-id: 용어집 ID

HTTP 메서드 및 URL:

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/us-central1/glossaries/glossary-id

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

성공 상태 코드(2xx)와 빈 응답을 받게 됩니다.

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"
)

// deleteGlossary deletes a glossary.
func deleteGlossary(w io.Writer, projectID string, location string, glossaryID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// glossaryID := "glossary-id"

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

	req := &translatepb.DeleteGlossaryRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/glossaries/%s", projectID, location, glossaryID),
	}

	// The DeleteGlossary operation is async.
	op, err := client.DeleteGlossary(ctx, req)
	if err != nil {
		return fmt.Errorf("DeleteGlossary: %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, "Deleted: %v\n", resp.GetName())

	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.DeleteGlossaryMetadata;
import com.google.cloud.translate.v3.DeleteGlossaryRequest;
import com.google.cloud.translate.v3.DeleteGlossaryResponse;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DeleteGlossary {

  public static void deleteGlossary() throws InterruptedException, ExecutionException, IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    String glossaryId = "your-glossary-display-name";
    deleteGlossary(projectId, glossaryId);
  }

  // Delete a specific glossary based on the glossary ID
  public static void deleteGlossary(String projectId, String glossaryId)
      throws InterruptedException, ExecutionException, IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
      DeleteGlossaryRequest request =
          DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();

      // Start an asynchronous request
      OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future =
          client.deleteGlossaryAsync(request);

      System.out.println("Waiting for operation to complete...");
      DeleteGlossaryResponse response = future.get();
      System.out.format("Deleted Glossary: %s\n", response.getName());
    }
  }
}

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 = 'global';
// const glossaryId = 'YOUR_GLOSSARY_ID';

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

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function deleteGlossary() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    name: `projects/${projectId}/locations/${location}/glossaries/${glossaryId}`,
  };

  // Delete glossary using a long-running operation
  const [operation] = await translationClient.deleteGlossary(request);

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

  console.log(`Deleted glossary: ${response.name}`);
}

deleteGlossary();

Python

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

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

from google.cloud import translate_v3 as translate

def delete_glossary(
    project_id: str = "YOUR_PROJECT_ID",
    glossary_id: str = "YOUR_GLOSSARY_ID",
    timeout: int = 180,
) -> translate.Glossary:
    """Delete a specific glossary based on the glossary ID.

    Args:
        project_id: The ID of the GCP project that owns the glossary.
        glossary_id: The ID of the glossary to delete.
        timeout: The timeout for this request.

    Returns:
        The glossary that was deleted.
    """
    client = translate.TranslationServiceClient()

    name = client.glossary_path(project_id, "us-central1", glossary_id)

    operation = client.delete_glossary(name=name)
    result = operation.result(timeout)
    print(f"Deleted: {result.name}")

    return result

추가 언어

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

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

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

용어집 항목 관리

용어집 항목은 한 언어의 용어를 다른 언어의 용어에 매핑합니다. 용어집에 새 항목을 추가하거나 기존 용어집의 모든 항목을 나열하거나 기존 항목을 수정할 수 있습니다.

새 항목 만들기

새 항목을 만들어 기존 용어집에 용어를 추가합니다. 단방향 용어집의 경우 한 용어가 출발어이고 다른 하나는 도착어인 용어 쌍을 제공합니다. 동의어 세트 용어집의 경우 세트의 각 항목이 용어 및 언어 코드를 지정하는 용어 세트를 제공합니다.

REST

다음 예시에서는 동의어 세트 용어집의 항목을 만듭니다. 요청당 하나의 항목만 만들 수 있습니다. 자세한 내용은 glossaryEntries.create 메서드를 참조하세요.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 기존 용어집의 ID입니다.
  • LANGUAGE_CODE: 용어 언어를 지정하는 언어 코드입니다.
  • TERM: 용어집에 추가할 용어입니다.
  • DESCRIPTION: 용어집 항목에 대한 정보입니다.

HTTP 메서드 및 URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

JSON 요청 본문:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

추가 언어

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

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

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

용어집 항목 나열

기존 용어집의 모든 항목을 나열합니다. 예를 들어 특정 용어집에서 용어 및 언어를 확인하려는 경우에 유용합니다.

REST

모든 용어집 항목을 나열하려면 glossaryEntries.list 메서드로 GET 요청을 보냅니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 기존 용어집의 ID입니다.

HTTP 메서드 및 URL:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries

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

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

{
  "glossaryEntries": [
    {
      "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
      "termsSet": {
        "terms": [
          {
            "languageCode": "LANGUAGE_CODE",
            "text": "TERM"
          },
        ...
        ]
      },
      "description": "DESCRIPTION"
    },
    ...
  ]
}

추가 언어

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

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

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

용어집 항목 가져오기

단일 항목을 가져와 해당 정보를 확인합니다.

REST

단일 용어집 항목을 가져오려면 glossaryEntries.get 메서드를 사용하여 GET 요청을 보냅니다. list 메서드를 사용하여 특정 항목의 ID를 찾습니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 기존 용어집의 ID입니다.
  • GLOSSARY_ENTRY_ID: 기존 용어집 항목의 ID입니다.

HTTP 메서드 및 URL:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

추가 언어

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

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

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

용어집 항목 업데이트

단일 항목을 업데이트하거나 용어집의 모든 항목을 대체할 수 있습니다. 모든 항목을 바꾸려면 용어집 업데이트를 참조하세요.

단방향 용어집의 항목을 수정하려면 한 용어가 출발어이고 다른 용어가 도착어인 용어 쌍을 제공합니다. 동의어 세트 용어집의 경우 세트의 각 항목이 용어 및 언어 코드를 지정하는 용어 세트를 제공합니다.

REST

다음 예시에서는 동의어 세트 용어집의 항목을 업데이트합니다. 자세한 내용은 glossaryEntries.patch 메서드를 참조하세요.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 업데이트할 항목이 포함된 기존 용어집의 ID입니다.
  • GLOSSARY_ENTRY_ID: 업데이트할 용어집 항목의 ID입니다.
  • LANGUAGE_CODE: 용어 언어를 지정하는 언어 코드입니다.
  • TERM: 업데이트할 용어입니다.
  • DESCRIPTION: 용어집 항목에 대한 정보입니다.

HTTP 메서드 및 URL:

PATCH https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

JSON 요청 본문:

{
  termsSet: {
   terms: {
     languageCode: "LANGUAGE_CODE",
     text: "TERM"
    },
    ...
  },
  description: "DESCRIPTION"
}

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

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

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID",
  "termsSet": {
    "terms": [
      {
        "languageCode": "LANGUAGE_CODE",
        "text": "TERM"
      },
      ...
    ]
  },
  "description": "DESCRIPTION"
}

추가 언어

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

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

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

용어집 항목 삭제

단일 용어집 항목을 삭제합니다.

REST

단일 용어집 항목을 삭제하려면 glossaryEntries.delete 메서드를 사용하여 삭제 요청을 보냅니다. list 메서드를 사용하여 특정 항목의 ID를 찾습니다.

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

  • PROJECT_NUMBER_OR_ID: Google Cloud 프로젝트의 숫자 또는 영숫자 ID
  • LOCATION: 업데이트할 용어집이 있는 리전입니다(예: us-central1).
  • GLOSSARY_ID: 삭제할 항목이 포함된 기존 용어집의 ID입니다.
  • GLOSSARY_ENTRY_ID: 삭제할 용어집 항목의 ID입니다.

HTTP 메서드 및 URL:

DELETE https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION/glossaries/GLOSSARY_ID/glossaryEntries/GLOSSARY_ENTRY_ID

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

성공 상태 코드(2xx)와 빈 응답을 받게 됩니다.

추가 언어

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

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

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

추가 리소스

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