使用 ML.PROCESS_DOCUMENT 函式處理文件

本文說明如何搭配使用 ML.PROCESS_DOCUMENT 函式和遠端模型,從物件資料表中的文件擷取實用洞察資訊。

支援的地區

您必須在 US 或 EU 多區域中,建立本程序使用的遠端模型。您必須在遠端模型所在的區域中執行 ML.PROCESS_DOCUMENT 函式。

必要的角色

如要建立遠端模型及處理文件,您必須具備下列專案層級的身分與存取權管理 (IAM) 角色:

  • 建立文件處理器:Document AI 編輯者 (roles/documentai.editor)
  • 建立及使用 BigQuery 資料集、資料表和模型:BigQuery 資料編輯者 (roles/bigquery.dataEditor)
  • 建立、委派及使用 BigQuery 連線:BigQuery 連線管理員 (roles/bigquery.connectionsAdmin)

    如果您未設定預設連線,可以在執行 CREATE MODEL 陳述式時建立並設定。如要執行這項操作,您必須具備專案的 BigQuery 管理員 (roles/bigquery.admin) 角色。詳情請參閱「設定預設連線」。

  • 將權限授予連線的服務帳戶:專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)

  • 建立 BigQuery 工作:BigQuery 工作使用者 (roles/bigquery.jobUser)

這些預先定義的角色具備執行本文件所述工作所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

  • 建立資料集:bigquery.datasets.create
  • 建立、委派及使用連線: bigquery.connections.*
  • 設定服務帳戶權限:resourcemanager.projects.getIamPolicy和resourcemanager.projects.setIamPolicy
  • 建立模型並執行推論:
    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.models.updateMetadata
  • 建立物件資料表:bigquery.tables.create 和 bigquery.tables.update
  • 建立文件處理器:
    • documentai.processors.create
    • documentai.processors.update
    • documentai.processors.delete

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the BigQuery, BigQuery Connection API, and Document AI APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the BigQuery, BigQuery Connection API, and Document AI APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

建立處理器

在 Document AI 中建立處理器來處理文件。處理器必須是支援的類型。

建立資料集

您必須在相同區域建立資料集、連線和文件處理器。

建立 BigQuery 資料集來存放資源:

控制台

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中,點選專案名稱。

  4. 依序點選 「View actions」(查看動作)>「Create dataset」(建立資料集)。

  5. 在「Create dataset」(建立資料集) 頁面執行下列操作:

    1. 在「資料集 ID」部分,輸入資料集名稱。

    2. 在「位置類型」部分,選取「區域」或「多區域」。

      • 如果選取「Region」(區域),請從「Region」(區域) 清單中選取位置。
      • 如果選取「Multi-region」(多區域),請從「Multi-region」(多區域) 清單中選取「US」(美國) 或「Europe」(歐洲)。
    3. 點選「建立資料集」。

bq

  1. 如要建立新的資料集,請使用 bq mk 指令並加上 --location 旗標:

    bq --location=LOCATION mk -d DATASET_ID

    更改下列內容:

    • LOCATION:資料集的位置。
    • DATASET_ID:您要建立的資料集 ID。
  2. 確認資料集已建立:

    bq ls

建立連線

建立 Cloud 資源連結,並取得連結的服務帳戶。建立連線時,請選擇與上一步建立的資料集相同的位置。

如果您已設定預設連線,或具備 BigQuery 管理員角色,則可略過這個步驟。

選取下列選項之一:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中展開專案名稱,然後點選「Connections」(連線)。

  4. 在「Connections」(連線) 頁面,按一下「Create connection」(建立連線)。

  5. 在「連線類型」部分,選擇「Vertex AI 遠端模型、遠端函式、BigLake 和 Spanner (Cloud 資源)」。

  6. 在「連線 ID」欄位輸入連線名稱。

  7. 在「位置類型」部分,選取連線位置。連線應與資料集等其他資源位於相同位置。

  8. 點選「建立連線」。

  9. 點選「前往連線」。

  10. 在「連線資訊」窗格中,複製服務帳戶 ID,以便在後續步驟中使用。

SQL

使用 CREATE CONNECTION 陳述式:

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在查詢編輯器中輸入下列陳述式:

    CREATE CONNECTION [IF NOT EXISTS] `CONNECTION_NAME`
    OPTIONS (
      connection_type = "CLOUD_RESOURCE",
      friendly_name = "FRIENDLY_NAME",
      description = "DESCRIPTION"
      );

    替換下列內容:

    • CONNECTION_NAME:連線名稱,格式為 PROJECT_ID.LOCATION.CONNECTION_ID、LOCATION.CONNECTION_ID 或 CONNECTION_ID。如果省略專案或位置,系統會根據執行陳述式的專案和位置推論。
    • FRIENDLY_NAME (選用):連線的描述性名稱。
    • DESCRIPTION (選用):連線說明。

  3. 按一下「 執行」。

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」。

bq

  1. 在指令列環境中建立連線:

    bq mk --connection --location=REGION --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE CONNECTION_ID

    --project_id 參數會覆寫預設專案。

    更改下列內容:

    • REGION:連線區域
    • PROJECT_ID:您的 Google Cloud 專案 ID
    • CONNECTION_ID:連線 ID

    建立連線資源時,BigQuery 會建立專屬的系統服務帳戶,並與連線建立關聯。

    疑難排解:如果收到下列連線錯誤,請更新 Google Cloud SDK:

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. 擷取並複製服務帳戶 ID,以便在後續步驟中使用:

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    輸出結果會與下列內容相似:

    name                          properties
    1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱 BigQuery Python API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def create_connection(
    project_id: str,
    location: str,
    connection_id: str,
):
    """Creates a BigQuery connection to a Cloud Resource.

    Cloud Resource connection creates a service account which can then be
    granted access to other Google Cloud resources for federated queries.

    Args:
        project_id: The Google Cloud project ID.
        location: The location of the connection (for example, "us-central1").
        connection_id: The ID of the connection to create.
    """

    parent = client.common_location_path(project_id, location)

    connection = bigquery_connection_v1.Connection(
        friendly_name="Example Connection",
        description="A sample connection for a Cloud Resource.",
        cloud_resource=bigquery_connection_v1.CloudResourceProperties(),
    )

    try:
        created_connection = client.create_connection(
            parent=parent, connection_id=connection_id, connection=connection
        )
        print(f"Successfully created connection: {created_connection.name}")
        print(f"Friendly name: {created_connection.friendly_name}")
        print(
            f"Service Account: {created_connection.cloud_resource.service_account_id}"
        )

    except google.api_core.exceptions.AlreadyExists:
        print(f"Connection with ID '{connection_id}' already exists.")
        print("Please use a different connection ID.")
    except Exception as e:
        print(f"An unexpected error occurred while creating the connection: {e}")

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 BigQuery Node.js API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Creates a new BigQuery connection to a Cloud Resource.
 *
 * A Cloud Resource connection creates a service account that can be granted access
 * to other Google Cloud resources.
 *
 * @param {string} projectId The Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location The location of the project to create the connection in. for example, 'us-central1'
 * @param {string} connectionId The ID of the connection to create. for example, 'example-connection-id'
 */
async function createConnection(projectId, location, connectionId) {
  const parent = client.locationPath(projectId, location);

  const connection = {
    friendlyName: 'Example Connection',
    description: 'A sample connection for a Cloud Resource',
    // The service account for this cloudResource will be created by the API.
    // Its ID will be available in the response.
    cloudResource: {},
  };

  const request = {
    parent,
    connectionId,
    connection,
  };

  try {
    const [response] = await client.createConnection(request);

    console.log(`Successfully created connection: ${response.name}`);
    console.log(`Friendly name: ${response.friendlyName}`);

    console.log(`Service Account: ${response.cloudResource.serviceAccountId}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.log(`Connection '${connectionId}' already exists.`);
    } else {
      console.error(`Error creating connection: ${err.message}`);
    }
  }
}

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 BigQuery Java API 參考文件。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.api.gax.rpc.AlreadyExistsException;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.bigquery.connection.v1.CloudResourceProperties;
import com.google.cloud.bigquery.connection.v1.Connection;
import com.google.cloud.bigquery.connection.v1.CreateConnectionRequest;
import com.google.cloud.bigquery.connection.v1.LocationName;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import java.io.IOException;

public class CreateConnection {

  /**
   * Creates a BigQuery connection to a Cloud Resource. A Cloud Resource connection provisions a
   * service account that can be granted access to other Google Cloud resources for federated
   * queries.
   *
   * @param projectId The Google Cloud project ID (for example, "example-project-id").
   * @param location The geographic location of the connection (for example, "us-central1").
   * @param connectionId The ID of the connection to create (for example, "example-connection-id").
   */
  public static void createConnection(String projectId, String location, String connectionId) {
    LocationName parent = LocationName.of(projectId, location);

    // CloudResourceProperties provisions a managed Google Cloud service account on creation.
    CloudResourceProperties cloudResourceProperties = CloudResourceProperties.newBuilder().build();
    Connection connection =
        Connection.newBuilder()
            .setFriendlyName("Example Connection")
            .setDescription("Cloud Resource connection for federated queries.")
            .setCloudResource(cloudResourceProperties)
            .build();

    CreateConnectionRequest request =
        CreateConnectionRequest.newBuilder()
            .setParent(parent.toString())
            .setConnectionId(connectionId)
            .setConnection(connection)
            .build();

    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      Connection response = client.createConnection(request);

      System.out.printf("Successfully created connection: %s%n", response.getName());
      System.out.printf("Friendly name: %s%n", response.getFriendlyName());
      System.out.printf(
          "Service Account: %s%n", response.getCloudResource().getServiceAccountId());
    } catch (AlreadyExistsException err) {
      System.err.printf(
          "error: connection '%s' already exists in location '%s' for project '%s': %s%n",
          connectionId, location, projectId, err.getMessage());
    } catch (ApiException | IOException err) {
      System.err.printf(
          "error: failed to create connection '%s' in location '%s' for project '%s': %s%n",
          connectionId, location, projectId, err.getMessage());
    }
  }

Terraform

使用 google_bigquery_connection 資源。

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

下列範例會在 US 區域建立名為 my_cloud_resource_connection 的 Cloud 資源連結:


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell。
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    每個專案只需執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,環境變數就會遭到覆寫。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. 在 Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須有 .tf 副檔名,例如 main.tf。在本教學課程中,這個檔案稱為 main.tf。
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在進行教學課程,可以複製每個章節或步驟中的程式碼範例。

    將程式碼範例複製到新建立的 main.tf。

    您也可以從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 請查看並修改範例參數,以便套用至您的環境。
  4. 儲存變更。
  5. 初始化 Terraform。每個目錄只需執行一次這項操作。
    terraform init

    如要使用最新版 Google 供應商,請視需要加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 查看設定,確認 Terraform 要建立或更新的資源符合預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台的使用者介面中,前往資源頁面,確認 Terraform 已建立或更新資源。

將存取權授予服務帳戶

選取下列選項之一:

控制台

  1. 前往「IAM & Admin」(IAM 與管理) 頁面。

    前往「IAM & Admin」(IAM 與管理) 頁面

  2. 按一下 「Grant Access」(授予存取權)。

    「Add principals」(新增主體) 對話方塊隨即開啟。

  3. 在「新增主體」欄位,輸入先前複製的服務帳戶 ID。

  4. 在「Select a role」(選取角色) 欄位中,依序選取「Document AI」和「Document AI Viewer」(Document AI 檢視者)。

  5. 按一下 [Add another role] (新增其他角色)。

  6. 在「Select a role」(請選擇角色) 欄位中,依序選取「Cloud Storage」和「Storage Object Viewer」(Storage 物件檢視者)。

  7. 按一下 [儲存]。

gcloud

使用 gcloud projects add-iam-policy-binding 指令:

gcloud projects add-iam-policy-binding 'PROJECT_NUMBER' --member='serviceAccount:MEMBER' --role='roles/documentai.viewer' --condition=None
gcloud projects add-iam-policy-binding 'PROJECT_NUMBER' --member='serviceAccount:MEMBER' --role='roles/storage.objectViewer' --condition=None

替換下列內容:

  • PROJECT_NUMBER:您的專案編號。
  • MEMBER:您先前複製的服務帳戶 ID。

如未授予權限,會導致 Permission denied 錯誤。

建立模型

建立遠端模型,REMOTE_SERVICE_TYPE 為 CLOUD_AI_DOCUMENT_V1:

CREATE OR REPLACE MODEL
`PROJECT_ID.DATASET_ID.MODEL_NAME`
REMOTE WITH CONNECTION {DEFAULT | `PROJECT_ID.REGION.CONNECTION_ID`}
OPTIONS (
  REMOTE_SERVICE_TYPE = 'CLOUD_AI_DOCUMENT_V1',
  DOCUMENT_PROCESSOR = 'PROCESSOR_ID'
);

替換下列內容:

  • PROJECT_ID:您的專案 ID。
  • DATASET_ID:要包含模型的資料集 ID。
  • MODEL_NAME:模型名稱。
  • REGION:連線使用的區域。
  • CONNECTION_ID:連線 ID,例如 myconnection。

    在 Google Cloud 控制台查看連線詳細資料時,連線 ID 是「Connection ID」(連線 ID) 中顯示的完整連線 ID 最後一個部分的值,例如 projects/myproject/locations/connection_location/connections/myconnection。

  • PROCESSOR_ID:程序 ID。如要找出這個值,請查看處理器詳細資料,然後查看「Basic Information」(基本資訊) 區段中的「ID」列。

如要查看模型輸出內容資料欄,請在模型建立後,按一下查詢結果中的「Go to model」(前往模型)。輸出資料欄會顯示在「Schema」(結構定義) 分頁的「Labels」(標籤) 部分。

建立物件資料表

針對 Cloud Storage 中的一組文件建立物件資料表。物件資料表中的文件必須是支援的類型。

處理文件

使用 ML.PROCESS_DOCUMENT 處理所有文件:

SELECT *
FROM ML.PROCESS_DOCUMENT(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  TABLE `PROJECT_ID.DATASET_ID.OBJECT_TABLE_NAME`
  [, PROCESS_OPTIONS => ( JSON 'PROCESS_OPTIONS')]
);

替換下列內容:

  • PROJECT_ID:您的專案 ID。
  • DATASET_ID:模型所在資料集的 ID。
  • MODEL_NAME:模型名稱。
  • OBJECT_TABLE_NAME:物件資料表的名稱,其中包含要處理的文件 URI。
  • PROCESS_OPTIONS:指定文件處理方式的 JSON 設定。例如,您可以使用這項設定,為版面配置剖析器指定文件分塊

或者,您也可以使用 ML.PROCESS_DOCUMENT 處理部分文件:

SELECT *
FROM ML.PROCESS_DOCUMENT(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  (SELECT *
  FROM `PROJECT_ID.DATASET_ID.OBJECT_TABLE_NAME`
  WHERE FILTERS
  LIMIT NUM_DOCUMENTS
  )
  [, PROCESS_OPTIONS => ( JSON 'PROCESS_OPTIONS')]
);

替換下列內容:

  • PROJECT_ID:您的專案 ID。
  • DATASET_ID:模型所在資料集的 ID。
  • MODEL_NAME:模型名稱。
  • OBJECT_TABLE_NAME:物件資料表的名稱,其中包含要處理的文件 URI。
  • FILTERS:篩選條件,用於篩除要在物件資料表資料欄中處理的文件。
  • NUM_DOCUMENTS: :要處理的文件數量上限。
  • PROCESS_OPTIONS:定義設定的 JSON 設定,例如版面配置剖析器的分塊設定

範例

範例 1

下列範例使用費用剖析器,處理 documents 資料表代表的文件:

SELECT *
FROM ML.PROCESS_DOCUMENT(
  MODEL `myproject.mydataset.expense_parser`,
  TABLE `myproject.mydataset.documents`
);

這項查詢會傳回剖析後的費用報表,包括費用報表中的貨幣、總金額、收據日期和明細項目。ml_process_document_result 欄包含費用剖析器的原始輸出內容,ml_process_document_status 欄則包含文件處理作業傳回的所有錯誤。

示例 2

以下範例說明如何篩選物件資料表,選擇要處理的文件,然後將結果寫入新資料表:

CREATE TABLE `myproject.mydataset.expense_details`
AS
SELECT uri, content_type, receipt_date, purchase_time, total_amount, currency
FROM
  ML.PROCESS_DOCUMENT(
    MODEL `myproject.mydataset.expense_parser`,
    (SELECT * FROM `myproject.mydataset.expense_reports`
    WHERE uri LIKE '%restaurant%'));

後續步驟