用語集の作成と使用(高度な機能)

用語集は、お客様のドメイン固有の用語を統一して翻訳するために Cloud Translation API が使用するカスタム辞書です。用語集には通常、固有表現の対訳も含まれます。

用語集は次のようなユースケースで使用できます。

  • 商品名: たとえば、「Google Home」は「Google Home」に翻訳する必要があります。
  • あいまいな単語: たとえば、「bat」という単語は、スポーツ用品や動物を指します。スポーツに関する単語を翻訳する場合は、用語集を使用して、動物の「コウモリ」ではなく「バット」というスポーツ用語としての翻訳を Cloud Translation API に渡すことをおすすめします。
  • 借用語: たとえば、フランス語の「bouillabaisse」は英語の「bouillabaisse」に翻訳されます。英語では、19 世紀にフランス語から「bouillabaisse」という語を取り入れました。フランスの文化的背景のない英語スピーカーは、bouillabaisse が魚の煮込み料理であるとは知らないかもしれません。用語集は、フランス語の「bouillabaisse」が英語の「fish stew」に翻訳されるように翻訳をオーバーライドできます。

始める前に

Cloud Translation API を使用するには、Cloud Translation API が有効になっているプロジェクトと適切な認証情報が必要です。また、この API の呼び出しを支援する一般的なプログラミング言語のクライアント ライブラリをインストールすることもできます。詳細については、設定ページをご覧ください。

必要な権限

用語集を操作するには、サービス アカウントに用語集に固有の権限が必要です。サービス アカウントにロールを付与するには、Cloud Translation API 編集者(roles/cloudtranslate.editor)などの IAM 事前定義ロールの 1 つを使用するか、必要な権限を付与するカスタムロールを作成します。Cloud Translation API のすべての権限は、IAM の権限のリファレンスで確認できます。Cloud Translation の権限は cloudtranslate で始まります。

用語集を作成するには、用語集ファイルが存在する Cloud Storage バケット内のオブジェクトを読み取る権限も必要です。サービス アカウントにロールを付与するには、ストレージ オブジェクト閲覧者(roles/storage.objectViewer)などの IAM 事前定義ロールの 1 つを使用するか、オブジェクトを読み取る権限を付与するカスタムロールを作成します

ロールにアカウントを追加する方法については、リソースに対するアクセス権の付与、変更、取り消しをご覧ください。

用語集を作成する

用語集には、単一のトークン(単語)または短いフレーズ(通常は 5 単語未満)が登録されています。用語集を使用する主な手順は次のとおりです。

  1. 用語集ファイルを作成する
  2. Cloud Translation API を使用して用語集リソースを作成する
  3. 翻訳を依頼するときに、使用する用語集を指定する

1 つのプロジェクトで複数の用語集を使用することもあります。この場合、利用可能な用語集のリストを取得したり、不要になった用語集を削除したりできます。

ストップ語

Cloud Translation は、用語集に含まれている一部の用語を無視します。このような用語をストップ語と呼びます。Cloud Translation でストップ語を翻訳すると、一致する用語集エントリは無視されます。すべてのストップ語のリストについては、用語集のストップ語をご覧ください。

用語集ファイルを作成する

基本的に、用語集は 1 つの用語と各国語の訳語が 1 行に記述されているテキスト ファイルです。用語集には、ソース言語とターゲット言語のペアが 1 つだけの用語集と、1 つの用語が複数の言語で定義されている多言語の用語セットがありますが、Cloud Translation API はこの両方をサポートしています。

用語集入力ファイル内の用語の合計数は、すべての言語の合計で 1,040 万(10,485,760)UTF-8 バイト以下にしてください。用語集の用語は、1 件につき 1024 UTF-8 バイト未満にする必要があります。1,024 バイトより長い用語は無視されます。

デフォルトでは、用語集の一致は大文字と小文字が区別されます。用語集を適用する場合、すべてのエントリの大文字と小文字の区別は無視できます。大文字と小文字を区別する用語と区別しない用語が混在している場合は、デフォルトの動作を使用します。区別しない用語については、用語集に両方のフォームを含めてください。

単一言語ペアの用語集

Cloud Translation API は TSV、CSV、TMX ファイルに対応しています。

TSV と CSV

タブ区切り値(TSV)とカンマ区切り値(CSV)の場合、各行には 1 つのタブ(\t)またはカンマ(,)で区切られた用語のペアが含まれます。次の例に示すように、最初の列にはソース言語の用語が含まれ、2 番目の列にはターゲット言語の用語が含まれます。

単一言語ペアの用語集

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> 要素のペアが含まれます。1 つの <tu> 要素に 3 つ以上の <tuv> 要素が含まれる場合、Cloud Translation API はソース言語に一致する最初の <tuv> とターゲット言語に一致する最初の同要素のみを処理し、残りは無視します。<tu> 要素の中に対応する <tuv> 要素のペアがない場合、Cloud Translation API はその無効な <tu> 要素をスキップします。

Cloud Translation API は、<seg> 要素の前後のマークアップ タグを削除してから、それを処理します。1 つの <tuv> 要素に複数の <seg> 要素が含まれている場合、Cloud Translation API はスペースを間に挿入してそれらのテキストを 1 つの要素に連結します。

ファイルに上記以外の XML タグが含まれている場合、Cloud Translation API はこれらのタグを無視します。

ファイルが XML と TMX の正しい形式に従っていない場合(たとえば、終了タグや <tmx> 要素がない場合)、Cloud Translation API はファイルの処理を中止します。Cloud Translation API は、1,024 個を超える無効な <tu> 要素をスキップした場合も処理を中止します。

多言語の用語セット(CSV)

多言語の用語セットでは、Cloud Translation API は CSV 形式のファイルのみに対応しています。多言語の用語セットを定義するには、複数列の CSV ファイルを作成します。1 行に 1 つの用語を定義し、各国語の対訳を同じ行に記述します。

ファイルの先頭行は、各列の言語を表すヘッダーになります。言語の指定には ISO-639 または BCP-47 言語コードを使用します。また、品詞(pos)や説明(description)の列を追加することもできます。現在、アルゴリズムでは pos の情報は使用されず、pos の値は検証されません。

以降の行では、ヘッダーに指定されている言語の順番で対訳が並びます。1 つの用語に対して、すべての言語で訳語があるとは限りません。その場合、該当する列を空白にします。

多言語の用語セット

用語集リソースを作成する

多言語の用語セットを準備したら、用語集リソースを作成して 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 は PROJECT_NUMBER_OR_ID で、my-en-ru-glossary はユーザーが指定した 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