サポートされている言語の検出(Advanced)

Cloud Translation API を使用して、NMT モデルでサポートされている言語の一覧を表示します。AutoML Translation でサポートされる言語ペアを表示するには、カスタムモデルの言語サポートをご覧ください。

始める前に

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

サポートされている言語を一覧表示する

REST

サポートされているすべての言語のリストを取得するには、https://translation.googleapis.com/v3/projects/project-number-or-id/locations/location/supportedLanguages URL に GET リクエストを行います。次の例は、curl と PowerShell を使用した GET リクエストを示しています。この例では、Google Cloud CLI を使用するプロジェクト用に設定されたサービス アカウントのアクセス トークンを使用します。Google Cloud CLI のインストール、サービス アカウントでのプロジェクトの設定、アクセス トークンの取得を行う手順については、設定ページをご覧ください。

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

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

HTTP メソッドと URL:

GET https://translation.googleapis.com/v3/projects/PROJECT_NUMBER_OR_ID/locations/global/supportedLanguages

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

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

{
  "languages": [
     "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    ....
    {
      "languageCode": "zu",
      "supportSource": true,
      "supportTarget": true
    }
   ]
}

リストは言語コード別にアルファベット順になります。このクエリは、サポートされている言語の ISO-639 言語コードを返します。一部の言語コードには zh-CN や zh-TW のような国コードも含まれます。例:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

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

// getSupportedLanguages gets a list of supported language codes.
func getSupportedLanguages(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

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

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

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

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguages {

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

  // Getting a list of supported language codes
  public static void getSupportedLanguages(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, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
      }
    }
  }
}

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 getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

Python

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

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

from google.cloud import translate

def get_supported_languages(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.SupportedLanguages:
    """Getting a list of supported language codes.

    Args:
        project_id: The GCP project ID.

    Returns:
        A list of supported language codes.
    """
    client = translate.TranslationServiceClient()

    parent = f"projects/{project_id}"

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(parent=parent)

    # List language codes of supported languages.
    print("Supported Languages:")
    for language in response.languages:
        print(f"Language Code: {language.language_code}")

    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/global/supportedLanguages?display_language_code=sq

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

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

{
  "languages": [{
      "languageCode": "af",
      "displayName": "Afrikanisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "displayName": "Amarikisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "en",
      "displayName": "Anglisht",
      "supportSource": true,
      "supportTarget": true
    },
    ...{
      "languageCode": "zu",
      "displayName": "Zulu",
      "supportSource": true,
      "supportTarget": true
    }

	]
}

この場合、上記と同じ言語コードと、ターゲット言語の言語名が入った文字列 name がクエリから返されます。この例では、言語はアルバニア語(sq)です。

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

// getSupportedLanguagesForTarget gets a list of supported language codes with target language names.
func getSupportedLanguagesForTarget(w io.Writer, projectID string, languageCode string) error {
	// projectID := "my-project-id"
	// languageCode := "is"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/global", projectID),
		DisplayLanguageCode: languageCode,
	}

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

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		fmt.Fprintf(w, "Display name: %v\n", language.GetDisplayName())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguagesForTarget {

  public static void getSupportedLanguagesForTarget() 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 languageCode = "your-language-code";
    getSupportedLanguagesForTarget(projectId, languageCode);
  }

  // Listing supported languages with target language name
  public static void getSupportedLanguagesForTarget(String projectId, String languageCode)
      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");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder()
              .setParent(parent.toString())
              .setDisplayLanguageCode(languageCode)
              .build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
        System.out.printf("Display Name: %s\n", language.getDisplayName());
      }
    }
  }
}

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 getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    displayLanguageCode: 'en',
  };

  // Get supported languages
  const [response] = await translationClient.getSupportedLanguages(request);

  for (const language of response.languages) {
    // Supported language code, generally consisting of its ISO 639-1 identifier, for
    // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
    // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
    console.log(`Language - Language Code: ${language.languageCode}`);
    // Human readable name of the language localized in the display language specified
    // in the request.
    console.log(`Language - Display Name: ${language.displayName}`);
    // Can be used as source language.
    console.log(`Language - Support Source: ${language.supportSource}`);
    // Can be used as target language.
    console.log(`Language - Support Target: ${language.supportTarget}`);
  }
}

getSupportedLanguages();

Python

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

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

from google.cloud import translate

def get_supported_languages_with_target(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.SupportedLanguages:
    """Listing supported languages with target language name.

    Args:
        project_id: Your Google Cloud project ID.

    Returns:
        Supported languages.
    """
    client = translate.TranslationServiceClient()

    location = "global"

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

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(
        display_language_code="is", parent=parent  # target language code
    )
    # List language codes of supported languages
    for language in response.languages:
        print(f"Language Code: {language.language_code}")
        print(f"Display Name: {language.display_name}")

    return response

その他の言語

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

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

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

補足資料