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

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

始める前に

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

テキストの翻訳例

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

REST

Basic translate メソッドへの REST メソッド呼び出しを使用して、Cloud Translation - Basic リクエストを行います。ソース言語とターゲット言語は ISO-639 コードで指定できます。

以下は、curl または PowerShell を使用した POST リクエストの例です。

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

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

HTTP メソッドと URL:

POST https://translation.googleapis.com/language/translate/v2

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

{
  "q": "The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.",
  "source": "en",
  "target": "es",
  "format": "text"
}

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

curl

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

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

PowerShell

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

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/language/translate/v2" | Select-Object -Expand Content

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

{
  "data": {
    "translations": [{
      "translatedText": "La Gran Pirámide de Giza (también conocida como la Pirámide de Khufu o la Pirámide de Keops) es la más antigua y más grande de las tres pirámides en el complejo de la pirámide de Giza."
    }]
  }
}

Go

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

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func translateText(targetLanguage, text string) (string, error) {
	// text := "The Go Gopher is cute"
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return "", fmt.Errorf("language.Parse: %w", err)
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return "", err
	}
	defer client.Close()

	resp, err := client.Translate(ctx, []string{text}, lang, nil)
	if err != nil {
		return "", fmt.Errorf("Translate: %w", err)
	}
	if len(resp) == 0 {
		return "", fmt.Errorf("Translate returned empty response to text: %s", text)
	}
	return resp[0].Text, nil
}

Java

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

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

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

Translation translation = translate.translate("¡Hola Mundo!");
System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());

Node.js

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

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

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const text = 'The text to translate, e.g. Hello, world!';
// const target = 'The target language, e.g. ru';

async function translateText() {
  // Translates the text into the target language. "text" can be a string for
  // translating a single piece of text, or an array of strings for translating
  // multiple texts.
  let [translations] = await translate.translate(text, target);
  translations = Array.isArray(translations) ? translations : [translations];
  console.log('Translations:');
  translations.forEach((translation, i) => {
    console.log(`${text[i]} => (${target}) ${translation}`);
  });
}

translateText();

Python

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

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

def translate_text(target: str, text: str) -> dict:
    """Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = text.decode("utf-8")

    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

    return result

その他の言語

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

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

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

補足資料

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