リモート関数と Translation API のチュートリアル

このチュートリアルでは、BigQuery リモート関数を作成し、Cloud Translation API を呼び出して、SQL と Python を使用して任意の言語からスペイン語へのコンテンツ翻訳を実行する方法について説明します。

この関数のユースケースには次のようなものがあります。

  • ウェブサイトへのユーザー コメントをローカル言語に翻訳する
  • サポートケース作業者向けに、サポート リクエストを複数の言語から 1 つの共通言語に翻訳する

目標

  • アカウントに必要なロールを割り当てます。
  • Cloud Run functions の関数を作成します。
  • BigQuery データセットを作成します。
  • BigQuery の接続とサービス アカウントを作成します。
  • BigQuery サービス アカウントに権限を付与します。
  • BigQuery リモート関数を作成します。
  • BigQuery リモート関数を呼び出します。

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

このチュートリアル用に Google Cloud プロジェクトを作成することをおすすめします。また、このチュートリアルを完了するために必要なロールが付与されていることを確認してください。

Google Cloud プロジェクトを設定する

このチュートリアル用に Google Cloud プロジェクトを設定する手順は次のとおりです。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the BigQuery, BigQuery Connection, Cloud Translation, Cloud Run functions, Cloud Build, Cloud Logging, Cloud Pub/Sub, Artifact Registry, and Cloud Run Admin APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the BigQuery, BigQuery Connection, Cloud Translation, Cloud Run functions, Cloud Build, Cloud Logging, Cloud Pub/Sub, Artifact Registry, and Cloud Run Admin APIs.

    Enable the APIs

  8. アカウントに必要なロール

    このチュートリアルのタスクを実行するために必要な権限を取得するには、プロジェクトに対して次の IAM ロールを付与するよう管理者に依頼してください。

    ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

    これらの事前定義ロールには、このチュートリアルのタスクを実行するために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

    必要な権限

    このチュートリアルのタスクを実行するには、次の権限が必要です。

    • bigquery.datasets.create
    • bigquery.connections.create
    • bigquery.connections.get
    • cloudfunctions.functions.create

    カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

    Compute Engine のデフォルト サービス アカウントに必要なロール

    Cloud Run functions に対してこの API を有効にしたときに、Compute Engine のデフォルト サービス アカウントが作成されました。このチュートリアルを完了するには、このデフォルトのサービス アカウントに Cloud Translation API ユーザー ロールを付与する必要があります。

    1. プロジェクトに割り当てられている ID を取得します

    2. Compute Engine のデフォルトのサービス アカウントをコピーします。デフォルトのサービス アカウントは次のようになります。

      PROJECT_NUMBER-compute@developer.gserviceaccount.com
      

      PROJECT_NUMBER は、実際のプロジェクト ID に置き換えます。

    3. Google Cloud コンソールで、[IAM] ページに移動します。

      [IAM] に移動

    4. プロジェクトを選択します。

    5. [ アクセス権を付与] をクリックし、[新しいプリンシパル] フィールドに、先ほどコピーした Compute Engine のデフォルト サービス アカウントを貼り付けます。

    6. [ロールを割り当てる] のリストで、[Cloud Translation API ユーザー] を見つけて選択します。

    7. [保存] をクリックします。

    Cloud Run functions の関数を作成する

    Cloud Run functions を使用して、入力テキストをスペイン語に変換する関数を作成します。

    1. 次の仕様で Cloud Run functions の関数を作成します

      • [環境] には、[第 2 世代] を選択します。
      • [関数名] に「translation-handler」と入力します。
      • [リージョン] で、[us-central1] を選択します。
      • [インスタンスの最大数] に「10」と入力します。

        この設定は、[Runtime, build, connections and security settings] セクションにあります。

        このチュートリアルでは、デフォルトよりも小さい値を使用して、Translation に送信されるリクエスト レートを制御します。

      • [ランタイム] では [Python 3.10] を選択します。

      • [エントリ ポイント] に「handle_translation」と入力します。

    2. ファイルリストで main.py を選択し、次のコードを貼り付けます。

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

      BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

      from __future__ import annotations
      
      
      import flask
      import functions_framework
      from google.api_core.retry import Retry
      from google.cloud import translate
      
      # Construct a Translation Client object
      translate_client = translate.TranslationServiceClient()
      
      
      # Register an HTTP function with the Functions Framework
      @functions_framework.http
      def handle_translation(request: flask.Request) -> flask.Response:
          """BigQuery remote function to translate input text.
      
          Args:
              request: HTTP request from BigQuery
              https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#input_format
      
          Returns:
              HTTP response to BigQuery
              https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#output_format
          """
          try:
              # Parse request data as JSON
              request_json = request.get_json()
              # Get the project of the query
              caller = request_json["caller"]
              project = extract_project_from_caller(caller)
              if project is None:
                  return flask.make_response(
                      flask.jsonify(
                          {
                              "errorMessage": (
                                  'project can\'t be extracted from "caller":' f" {caller}."
                              )
                          }
                      ),
                      400,
                  )
              # Get the target language code, default is Spanish ("es")
              context = request_json.get("userDefinedContext", {})
              target = context.get("target_language", "es")
      
              calls = request_json["calls"]
              translated = translate_text([call[0] for call in calls], project, target)
      
              return flask.jsonify({"replies": translated})
          except Exception as err:
              return flask.make_response(
                  flask.jsonify({"errorMessage": f"Unexpected error {type(err)}:{err}"}),
                  400,
              )
      
      
      def extract_project_from_caller(job: str) -> str:
          """Extract project id from full resource name of a BigQuery job.
      
          Args:
              job: full resource name of a BigQuery job, like
                "//bigquery.googleapi.com/projects/<project>/jobs/<job_id>"
      
          Returns:
              project id which is contained in the full resource name of the job.
          """
          path = job.split("/")
          return path[4] if len(path) > 4 else None
      
      
      def translate_text(
          calls: list[str], project: str, target_language_code: str
      ) -> list[str]:
          """Translates the input text to specified language using Translation API.
      
          Args:
              calls: a list of input text to translate.
              project: the project where the translate service will be used.
              target_language_code: The ISO-639 language code to use for translation
                of the input text. See
                https://cloud.google.com/translate/docs/advanced/discovering-supported-languages-v3#supported-target
                  for the supported language list.
      
          Returns:
              a list of translated text.
          """
          location = "<your location>"
          parent = f"projects/{project}/locations/{location}"
          # Call the Translation API, passing a list of values and the target language
          response = translate_client.translate_text(
              request={
                  "parent": parent,
                  "contents": calls,
                  "target_language_code": target_language_code,
                  "mime_type": "text/plain",
              },
              retry=Retry(),
          )
          # Convert the translated value to a list and return it
          return [translation.translated_text for translation in response.translations]
      
      

      <your location>us-central1 に更新します。

    3. ファイルリストで requirements.txt を選択し、次のテキストを貼り付けます。

      Flask==2.2.2
      functions-framework==3.8.2
      google-cloud-translate==3.18.0
      Werkzeug==2.3.8
      

    4. [デプロイ] をクリックし、関数がデプロイされるのを待ちます。

    5. [トリガー] タブをクリックします。

    6. [トリガー URL] の値をコピーし、後で使用できるように保存します。BigQuery リモート関数を作成するときに、この URL を使用する必要があります。

    BigQuery データセットを作成する

    リモート関数を含む BigQuery データセットを作成します。このデータセットを作成するときに、次の仕様を含めます。

    • [データセット ID] に「remote_function_test」と入力します。
    • [ロケーション タイプ] で [マルチリージョン] を選択します。
    • [マルチリージョン] で [US(米国の複数のリージョン)] を選択します。

    BigQuery の接続とサービス アカウントを作成する

    BigQuery 接続を作成して、Cloud Run functions と Cloud Run でサポートされている任意の言語でリモート関数を実装できるようにします。接続を作成すると、その接続用のサービス アカウントが作成されます。

    1. 次の仕様で Google Cloud リソース接続を作成します。

      • [接続タイプ] で、[BigLake とリモート関数(クラウド リソース)] を選択します。
      • [接続 ID] に「remote-function-connection」と入力します。
      • [ロケーション タイプ] で [マルチリージョン] を選択します。
      • [マルチリージョン] で [US(米国の複数のリージョン)] を選択します。
    2. [外部接続] リストを開き、[us.remote-function-connection] を選択します。

    3. サービス アカウント ID をコピーして、後で使用できるように保存します。次のステップで、この ID に権限を付与する必要があります。

    BigQuery サービス アカウントに権限を付与する

    前の手順で作成したサービス アカウントには、BigQuery リモート関数が Cloud Run functions の関数を使用できるように、Cloud Run を使用する権限が必要です。サービス アカウントに権限を付与する手順は、次のとおりです。

    1. [Cloud Run] ページに移動します。

      Cloud Run に移動

    2. プロジェクトを選択します。

    3. translation-handler の横のチェックボックスをオンにします。

    4. [権限] パネルで、[プリンシパルを追加] をクリックします。

    5. [新しいプリンシパル] フィールドに、前の手順でコピーしたサービス アカウント ID を入力します。

    6. [ロールを割り当てる] のリストで、[Cloud Run 起動元] を見つけて選択します。

    7. [保存] をクリックします。

    BigQuery リモート関数を作成する

    BigQuery リモート関数を使用してテキストをスペイン語に変換する Cloud Run functions の関数を使用する手順は、次のとおりです。

    1. Google Cloud コンソールで、[BigQuery] ページに移動します。

      [BigQuery] に移動

    2. クエリエディタで以下のクエリを入力します。

      CREATE OR REPLACE FUNCTION `remote_function_test.translate_text`(x STRING)
      RETURNS
      STRING
          REMOTE WITH CONNECTION `us.remote-function-connection`
      OPTIONS (
          endpoint = 'TRIGGER_URL',
          max_batching_rows = 10);
      

      TRIGGER_URL は、Cloud Run functions の関数の作成時に保存したトリガー URL に置き換えます。

    3. [実行] をクリックします。次のようなメッセージが表示されます。

      This statement created a new function named
      your_project.remote_function_test.translate_text.
      

    BigQuery リモート関数を呼び出す

    リモート関数を作成したら、その関数をテストして、Cloud Run functions の関数にリンクされており、期待される結果がスペイン語で生成されることを確認します。

    1. BigQuery クエリエディタで次のクエリを入力し、[実行] をクリックします。

      SELECT
        remote_function_test.translate_text('This new feature is fantastic!')
          AS translated_text;
      

      結果は次のようになります。

      +-------------------------------------------+
      | translated_text                           |
      +-------------------------------------------+
      | ¡Esta nueva característica es fantástica! |
      +-------------------------------------------+
      
    2. 省略可: 一般公開データセットでリモート関数をテストするには、次のクエリを入力して [実行] をクリックします。返される結果を制限するには、LIMIT 句を使用します。

      SELECT
          text,
          remote_function_test.translate_text(text) AS translated_text
      FROM
          (SELECT text FROM `bigquery-public-data.hacker_news.full` LIMIT 3);
      

      結果は次のようになります。

      +---------------------------------------------------------------------------+
      | text                            | translated_text                         |
      +---------------------------------------------------------------------------+
      | These benchmarks look good.     | Estos puntos de referencia se ven bien. |
      | Who is using Java?              | ¿Quién está usando Java?                |
      | You need more database storage. | Necesitas más almacenamiento.           |
      +---------------------------------------------------------------------------+
      

    リソースを削除する

    このプロジェクトでこれらの関数を使用する予定がない場合は、プロジェクトを削除することで、追加費用の発生を回避できます。これにより、プロジェクトに関連付けられているすべてのリソースが完全に削除されます。

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    次のステップ