Cloud Translation Advanced でテキストを翻訳する

このドキュメントでは、Cloud Translation Advanced を使用してサンプル テキストを翻訳する方法について説明します。

始める前に

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

テキストの翻訳例

次の例は、Cloud Translation - Advanced を使用して、テキストを指定の対象言語に翻訳する方法を示しています。

REST

curl または PowerShell を使用してリクエストを行います。

ソース言語とターゲット言語は、ISO-639 コードを使用して指定します。ソース言語は英語(en)、ターゲット言語はロシア語(ru)です。クエリの形式は、「text」(書式なしテキスト)として表示されます。

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

  • 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!"],
  "mimeType": "text/plain"
}

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

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

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

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 リファレンス ドキュメントをご覧ください。

補足資料

  • テキストの翻訳について詳しくは、テキストの翻訳(Advanced)入門ガイドをご覧ください。
  • 一般的な問題またはエラーの解決に関するヘルプについては、トラブルシューティングページをご覧ください。
  • Cloud Translation に関する一般的な質問については、よくある質問のページをご覧ください。
  • Cloud Translation は、2 つのエディションで使用できます。各エディションの詳細については、Basic と Advanced の比較をご覧ください。