言語の検出(Advanced)

このドキュメントでは、Cloud Translation - Advanced を使用して、文字列の言語を検出する方法を説明します。

始める前に

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

テキスト文字列の言語の検出

テキスト文字列の言語を検出するには、次の形式の URL を使用して HTTP リクエストを送信します。

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

1 つの文字列の言語の検出

REST

テキストの言語を検出するには、POST リクエストを作成して適切なリクエスト本文を提供します。次の例は、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/locations/global:detectLanguage

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

{
   "content":"Доктор Ватсон, иди сюда!"
}

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

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

{
  "languages": [
    {
      "languageCode": "ru",
      "confidence": 1
    }
  ]
}
レスポンスで、languageCode によって検出された言語の言語コードが返されます。confidence は 0 から 1 の範囲の値になります。1 は 100% の信頼性を表します。

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

// detectLanguage detects the language of a text string.
func detectLanguage(w io.Writer, projectID string, text string) error {
	// projectID := "my-project-id"
	// text := "Hello, world!"

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

	req := &translatepb.DetectLanguageRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
		MimeType: "text/plain", // Mime types: "text/plain", "text/html"
		Source: &translatepb.DetectLanguageRequest_Content{
			Content: text,
		},
	}

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

	// Display list of detected languages sorted by detection confidence.
	// The most probable language is first.
	for _, language := range resp.GetLanguages() {
		// The language detected.
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		// Confidence of detection result for this language.
		fmt.Fprintf(w, "Confidence: %v\n", language.GetConfidence())
	}

	return nil
}

Java

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

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

import com.google.cloud.translate.v3.DetectLanguageRequest;
import com.google.cloud.translate.v3.DetectLanguageResponse;
import com.google.cloud.translate.v3.DetectedLanguage;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class DetectLanguage {

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

    detectLanguage(projectId, text);
  }

  // Detecting the language of a text string
  public static void detectLanguage(String projectId, 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
      DetectLanguageRequest request =
          DetectLanguageRequest.newBuilder()
              .setParent(parent.toString())
              .setMimeType("text/plain")
              .setContent(text)
              .build();

      DetectLanguageResponse response = client.detectLanguage(request);

      // Display list of detected languages sorted by detection confidence.
      // The most probable language is first.
      for (DetectedLanguage language : response.getLanguagesList()) {
        // The language detected
        System.out.printf("Language code: %s\n", language.getLanguageCode());
        // Confidence of detection result for this language
        System.out.printf("Confidence: %s\n", language.getConfidence());
      }
    }
  }
}

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

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

  console.log('Detected Languages:');
  for (const language of response.languages) {
    console.log(`Language Code: ${language.languageCode}`);
    console.log(`Confidence: ${language.confidence}`);
  }
}

detectLanguage();

Python

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

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

from google.cloud import translate

def detect_language(
    project_id: str = "YOUR_PROJECT_ID",
) -> translate.DetectLanguageResponse:
    """Detecting the language of a text string.

    Args:
        project_id: The GCP project ID.

    Returns:
        The detected language of the text.
    """
    client = translate.TranslationServiceClient()

    location = "global"

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

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.detect_language(
        content="Hello, world!",
        parent=parent,
        mime_type="text/plain",  # mime types: text/plain, text/html
    )

    # Display list of detected languages sorted by detection confidence.
    # The most probable language is first.
    for language in response.languages:
        # The language detected
        print(f"Language code: {language.language_code}")
        # Confidence of detection result for this language
        print(f"Confidence: {language.confidence}")

    return response

その他の言語

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

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

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

補足資料