テキストの翻訳(Advanced)

Cloud Translation - Advanced では、カスタムモデルを使用したテキスト翻訳が可能で、用語集の作成により Cloud Translation API でお客様の分野の専門用語を正しく翻訳できるようにします。

Google Cloud CLI のインストール、サービス アカウントでのプロジェクトの設定、アクセス トークンの取得を行う手順については、設定ページをご覧ください。用語集またはバッチ機能を使用する場合は、Cloud Storage バケットを作成し、サービス アカウントにアクセス権を付与する必要があります。

PDF などの書式設定されたドキュメントを翻訳するには、ドキュメントを翻訳するをご覧ください。

始める前に

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

モデルの比較

Cloud Translation - Advanced から翻訳をリクエストするときに、使用する翻訳モデルを指定できます。モデルが指定されていない場合、nmt モデルが使用されます。

モデル 適した事例
ニューラル機械翻訳(NMT)モデル

一般的なテキストを扱うケース。ニュース記事など、分野を特化しない一般的なウェブサイト コンテンツ。

ニュース記事、ソーシャル メディア、チャット アプリケーション、レビュー

AutoML Translation モデル 分野固有のテキスト。顧客から個別のユースケースに沿ったトレーニング データの提供を受け、Google の NMT モデルを特定の言語ペアで分野に対応したものにカスタマイズします。 金融ニュース、技術文書、その分野に固有の用語および専門用語を使用するテキスト

モデル ID を使用して翻訳モデルを指定します。NMT モデルの場合、モデル ID は general/nmt です。AutoML Translation モデルの ID については、次のセクションで説明します。

テキストの翻訳

入力テキストにはプレーン テキストまたは HTML を使用できます。Cloud Translation API は入力テキスト内の HTML タグは翻訳せず、タグ間にあるテキストのみを翻訳します。出力では、(未翻訳の)HTML タグは保持されます。タグは翻訳されたテキストに合わせて挿入されますが、ソース言語とターゲット言語には差異があるため、その位置調整は可能な範囲で行われます。出力内の HTML タグの順序は、翻訳による語順変化により、入力テキスト内の順序と異なる場合があります。

入力文字列の翻訳

REST

テキストを翻訳するには、POST リクエストを作成し、リクエスト本文に翻訳元の言語(source_language_code)、翻訳先の言語(target_language_code)、翻訳するテキスト(contents)を特定する JSON を指定します。翻訳するテキストの複数の文字列を JSON に含めることで指定できます(例を参照)。ソース言語とターゲット言語は ISO-639 コードで指定できます。

以下は、curl または PowerShell を使用した POST リクエストの例です。この例では、Google Cloud CLI を使用するプロジェクト用に設定されたサービス アカウントのアクセス トークンを使用します。Google Cloud CLI のインストール、サービス アカウントでのプロジェクトの設定、アクセス トークンの取得を行う手順については、設定ページをご覧ください。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_NUMBER_OR_ID: Google Cloud プロジェクトの数字または英数字の ID

HTTP メソッドと URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID:translateText

リクエストの本文(JSON):

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "ru",
  "contents": ["Dr. Watson, come here!", "Bring me some coffee!"]
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "translations": [
    {
      "translatedText": "Доктор Ватсон, иди сюда!",
    },
    {
      "translatedText": "Принеси мне кофе!",
    }
  ]
}

translations 配列の 2 つの translatedText フィールドに、リクエストした targetLanguageCode 言語(ru: ロシア語)の訳文が返されています。翻訳は、リクエスト内の対応するソースの配列と同じ順序で表示されます。

Go

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Go の設定手順を完了してください。詳細については、Cloud Translation Go API のリファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// Imports the Google Cloud Translation library
import (
	"context"
	"fmt"
	"io"

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

func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
	// projectID := "my-project-id"
	// sourceLang := "en-US"
	// targetLang := "fr"
	// text := "Text you wish to translate"

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

	// Construct request
	req := &translatepb.TranslateTextRequest{
		Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
		SourceLanguageCode: sourceLang,
		TargetLanguageCode: targetLang,
		MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
		Contents:           []string{text},
	}

	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.GetTranslations() {
		fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
	}

	return nil
}

Java

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Cloud Translation Java API のリファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// Imports the Google Cloud Translation library.
import com.google.cloud.translate.v3.LocationName;
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 TranslateText {

  // Set and pass variables to overloaded translateText() method for translation.
  public static void translateText() 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 targetLanguage = "your-target-language";
    String text = "your-text";
    translateText(projectId, targetLanguage, text);
  }

  // Translate text to target language.
  public static void translateText(String projectId, String targetLanguage, String text)
      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, "global");

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

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        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 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 translateText() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'sr-Latn',
  };

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

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

translateText();

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API のリファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# Imports the Google Cloud Translation library
from google.cloud import translate

# Initialize Translation client
def translate_text(
    text: str = "YOUR_TEXT_TO_TRANSLATE", project_id: str = "YOUR_PROJECT_ID"
) -> translate.TranslationServiceClient:
    """Translating Text."""

    client = translate.TranslationServiceClient()

    location = "global"

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

    # Translate text from English to French
    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",  # mime types: text/plain, text/html
            "source_language_code": "en-US",
            "target_language_code": "fr",
        }
    )

    # Display the translation for each input text provided
    for translation in response.translations:
        print(f"Translated text: {translation.translated_text}")

    return response

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Cloud Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Cloud Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Cloud Translation リファレンス ドキュメントをご覧ください。

カスタムモデルを使用してテキストを翻訳する

REST

翻訳に使用するモデルを指定するには、model クエリ パラメータを使用します。

次の例では、モデル ID が 1395675701985363739 のカスタムモデルを使用してテキストを翻訳します。カスタムモデルのモデル ID は、Google Cloud コンソールのモデルリストから取得できます。また、モデルのトレーニング時に API レスポンスから取得することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: Google Cloud プロジェクト ID。
  • LOCATION: カスタムモデルが配置されているリージョン(us-central1 など)。

HTTP メソッドと URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText

リクエストの本文(JSON):

{
  "model": "projects/PROJECT_ID/locations/LOCATION/models/1395675701985363739",
  "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."]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/v3/projects/PROJECT_ID/locations/LOCATION:translateText" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

{
  "translation": {
    "translatedText": "Доктор Ватсон, пожалуйста, откажитесь от своего мусора.
    Вы поделились нежелательной электронной почтой со мной. Давайте поговорим о
    спаме и важности рейтинга в конфиденциальном режиме.",
    "model": "projects/PROJECT_NUMBER/locations/LOCATION/models/1395675701985363739"
  }
}

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

// translateTextWithModel translates input text and returns translated text.
func translateTextWithModel(w io.Writer, projectID string, location string, sourceLang string, targetLang string, text string, modelID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// sourceLang := "en"
	// targetLang := "fr"
	// text := "Hello, world!"
	// 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.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},
		Model:              fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
	}

	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.GetTranslations() {
		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.LocationName;
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 TranslateTextWithModel {

  public static void translateTextWithModel() 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 modelId = "YOUR-MODEL-ID";
    translateTextWithModel(projectId, sourceLanguage, targetLanguage, text, modelId);
  }

  // Translating Text with Model
  public static void translateTextWithModel(
      String projectId, String sourceLanguage, String targetLanguage, String text, String modelId)
      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);
      String modelPath =
          String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);

      // 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)
              .setModel(modelPath)
              .build();

      TranslateTextResponse response = client.translateText(request);

      // Display the translation for each input text provided
      for (Translation translation : response.getTranslationsList()) {
        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 = 'us-central1';
// const modelId = 'YOUR_MODEL_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 translateTextWithModel() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    contents: [text],
    mimeType: 'text/plain', // mime types: text/plain, text/html
    sourceLanguageCode: 'en',
    targetLanguageCode: 'ja',
    model: `projects/${projectId}/locations/${location}/models/${modelId}`,
  };

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

  for (const translation of response.translations) {
    console.log(`Translated Content: ${translation.translatedText}`);
  }
}

translateTextWithModel();

Python

このサンプルを試す前に、Cloud Translation クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Cloud Translation Python API のリファレンス ドキュメントをご覧ください。

Cloud Translation に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from google.cloud import translate

def translate_text_with_model(
    text: str = "YOUR_TEXT_TO_TRANSLATE",
    project_id: str = "YOUR_PROJECT_ID",
    model_id: str = "YOUR_MODEL_ID",
) -> translate.TranslationServiceClient:
    """Translates a given text using Translation custom model."""

    client = translate.TranslationServiceClient()

    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"
    model_path = f"{parent}/models/{model_id}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.translate_text(
        request={
            "contents": [text],
            "target_language_code": "ja",
            "model": model_path,
            "source_language_code": "en",
            "parent": parent,
            "mime_type": "text/plain",  # mime types: text/plain, text/html
        }
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print(f"Translated text: {translation.translated_text}")

    return response

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Cloud Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Cloud Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Cloud Translation リファレンス ドキュメントをご覧ください。

文字変換

文字変換は、translateText メソッドの構成設定です。文字変換を有効にすると、ローマ字化されたテキスト(ラテン文字)がターゲット言語に直接翻訳されます。たとえば、ローマ字化された日本語のテキストを英語、スペイン語、中国語に直接翻訳できます。翻訳結果はターゲット言語の書記体系に従います。

文字変換リクエストには、ローマ字化されたテキストのみを含めます。ローマ字化されたテキストとされていないテキストを混在させると、Cloud Translation で整合性のある適切な翻訳が保証されません。

考慮事項

文字変換は、次の点で標準のテキスト翻訳とは異なります。

  • 文字変換は一部の言語のみに対応しています。詳細については、サポートされている言語ページの文字変換列をご覧ください。
  • MIME タイプは text/plain にする必要があります。HTML はサポートされていません。
  • 文字変換は、デフォルトの標準モデルでのみサポートされています。カスタムモデルはサポートされていません。
  • 文字変換のデフォルトのコンテンツ割り当ては低く設定されています。詳細については、割り当てと上限をご覧ください。

REST

translateText メソッドで transliteration_config フィールドを設定します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_NUMBER_OR_ID: Google Cloud プロジェクトの数字または英数字の ID。
  • LOCATION: このオペレーションを実行するリージョン。例: us-central1
  • SOURCE_LANGUAGE: (省略可)入力ドキュメントの言語コード。既知の場合は、言語サポートに記載されているいずれかの言語コードに設定します。
  • TARGET_LANGUAGE: 入力テキストの翻訳先のターゲット言語。言語サポートに記載されているいずれかの言語コードを設定します。
  • SOURCE_TEXT: 翻訳対象の原文をローマ字化したテキスト。

HTTP メソッドと URL:

POST https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/LOCATION:translateText

リクエストの本文(JSON):

{
  "source_language_code": "SOURCE_LANGUAGE",
  "target_language_code": "TARGET_LANGUAGE",
  "contents": "SOURCE_TEXT",
  "mime_type": "text/plain",
  "transliteration_config": { "enable_transliteration": true}
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "translations": [
    {
      "translatedText": "TRANSLATED_TEXT",
    }
  ]
}

参考情報