远程函数和 Translation API 教程

本教程介绍如何创建 BigQuery 远程函数,调用 Cloud Translation API,以及如何使用 SQL 和 Python 将任何语言的内容翻译成西班牙语。

此函数的使用场景包括以下各项:

  • 将网站上的用户评论翻译成当地语言
  • 将来自众多语言的支持请求翻译成支持案例工作器的一种通用语言

目标

  • 为您的账号分配必要的角色。
  • 创建 Cloud Functions 函数。
  • 创建 BigQuery 数据集。
  • 创建 BigQuery 连接和服务账号。
  • 向 BigQuery 服务账号授予权限。
  • 创建 BigQuery 远程函数。
  • 调用 BigQuery 远程函数。

费用

在本文档中,您将使用 Google Cloud 的以下收费组件:

您可使用价格计算器根据您的预计使用情况来估算费用。 Google Cloud 新用户可能有资格申请免费试用

准备工作

我们建议您为本教程创建一个 Google Cloud 项目。此外,请确保您拥有完成本教程所需的角色。

设置 Google Cloud 项目

如需为本教程设置 Google Cloud 项目,请完成以下步骤:

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 BigQuery、BigQuery Connection、Cloud Translation、Cloud Functions、Cloud Build、Cloud Logging、Cloud Pub/Sub、Artifact Registry 和 Cloud Run Admin API。

    启用 API

  5. 在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目

    转到“项目选择器”

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 BigQuery、BigQuery Connection、Cloud Translation、Cloud Functions、Cloud Build、Cloud Logging、Cloud Pub/Sub、Artifact Registry 和 Cloud Run Admin API。

    启用 API

账号所需的角色

如需获得执行本教程中任务所需的权限,请让管理员向您授予项目的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理访问权限

这些预定义角色包含执行本教程中的任务所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需执行本教程中的任务,您需要拥有以下权限:

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

您也可以使用自定义角色或其他预定义角色来获取这些权限。

Compute Engine 默认服务账号所需的角色

启用 Cloud Functions 的 API 后,系统创建了一个 Compute Engine 默认服务账号。如需完成本教程,您必须为此默认服务账号提供 Cloud Translation API User 角色。

  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 User

  7. 点击保存

创建 Cloud Functions 函数

使用 Cloud Functions 创建一个将输入文本翻译为西班牙语的函数。

  1. 使用以下规范创建 Cloud Functions 函数

    • 对于环境,选择第 2 代
    • 对于函数名称,请输入 translation-handler
    • 区域部分,选择 us-central1
    • 对于实例数上限,请输入 10

      此设置位于运行时、构建、连接和安全设置部分。

      在本教程中,我们使用低于默认值的值来控制发送到 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]
    
    

    使用 us-central1 更新 <your location>

  3. 在文件列表中,选择 requirements.txt,然后粘贴以下文本:

    Flask==2.2.2
    functions-framework==3.5.0
    google-cloud-translate==3.11.1
    Werkzeug==2.3.7
    

  4. 点击部署,然后等待函数部署。

  5. 点击触发器标签页。

  6. 复制触发器网址值并保存,以备日后使用。您必须在创建 BigQuery 远程函数时使用此网址。

创建 BigQuery 数据集

创建 BigQuery 数据集,其中包含远程函数。创建数据集时,请添加以下规范:

  • 数据集 ID 部分,输入 remote_function_test
  • 对于位置类型,请选择多区域
  • 对于多区域,请选择美国(美国的多个区域)

创建 BigQuery 连接和服务账号

创建 BigQuery 连接,以便在 Cloud Functions 和 Cloud Run 中使用任何支持的语言实现远程函数。创建连接时,系统会为该连接创建一个服务账号。

  1. 使用以下规范创建 Google Cloud 资源连接

    • 对于连接类型,请选择 BigLake 和远程函数(Cloud 资源)
    • 对于连接 ID,请输入 remote-function-connection
    • 对于位置类型,请选择多区域
    • 对于多区域,请选择美国(美国的多个区域)
  2. 打开外部连接列表,然后选择 us.remote-function-connection

  3. 复制服务账号 ID 并保存,以备日后使用。您必须在下一步向此 ID 授予权限。

向 BigQuery 服务账号授予权限

您在上一步创建的服务账号需要使用 Cloud Run 的权限,以便 BigQuery 远程函数可以使用 Cloud Functions 函数。如需向服务账号授予权限,请完成以下步骤:

  1. 转到 Cloud Run 页面

    转到 Cloud Run

  2. 选择您的项目。

  3. 选中 translation-handler 旁边的复选框。

  4. 权限面板中,点击添加主账号

  5. 新的主账号字段中,输入您之前复制的服务账号 ID。

  6. 分配角色列表中,搜索并选择 Cloud Run Invoker

  7. 点击保存

创建 BigQuery 远程函数

如需使用 Cloud Functions 函数通过 BigQuery 远程函数将文本翻译成西班牙语,请完成以下步骤。

  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 Functions 函数时保存的触发器网址。

  3. 点击运行。系统会显示类似以下内容的消息:

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

调用 BigQuery 远程函数

创建远程函数后,请进行测试以确保它与 Cloud 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. 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

后续步骤