快速入门

本指南介绍了开始使用 Document AI Warehouse 所需的所有设置步骤。

控制台简介 Google Cloud

Google Cloud console 是用于预配、配置、管理和 监控使用 Google Cloud 产品的系统的网页界面。您可以使用 Google Cloud 控制台设置和管理 Document AI Warehouse 资源。

创建项目

如需使用 Google Cloud提供的服务,您必须创建一个项目

项目可以整理您的所有 Google Cloud 资源。项目由以下部分组成:

  • 一组协作者
  • 已启用的 API(以及其他资源)
  • 监控工具
  • 结算信息
  • 身份验证和访问权限控制

您可以创建一个项目,也可以创建多个项目。您可以使用 项目按 Google Cloud 资源层次结构组织资源 。如需详细了解项目,请参阅 Resource Manager 文档

在 Google Cloud 控制台的项目选择器页面上, 选择或创建 Google Cloud 项目。

选择或创建项目所需的角色

  • 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已被授予角色的任何项目。
  • 创建项目:如需创建项目,您需要 Project Creator 角色 (roles/resourcemanager.projectCreator),该角色包含 resourcemanager.projects.create 权限。了解如何授予 角色

转到“项目选择器”

启用结算功能

结算账号定义了一组给定资源的付款方。结算账号可以关联到一个或多个项目。项目的资源使用费将记在关联的结算账号名下。您应在创建项目时配置结算信息。如需了解 详情,请参阅结算文档

验证是否已为您的 Google Cloud 项目启用结算功能。

预配和初始化服务

首次使用 Document AI Warehouse 之前,您必须在 Document AI Warehouse 预配页面上预配和 初始化与项目关联的资源。

如需预配资源,您必须被授予项目的 Content Warehouse AdminService Usage Admin 角色。

预配步骤

  1. 选择一个区域。

    在预配页面上,选择要启用的区域

    每个区域都是独立的。因此,如果您想使用多个区域,请分别预配每个区域。

  2. 启用核心 API。{:#enable-core-api}:

    点击启用 。这会在您的项目上启用 Document AI Warehouse API。

    启用 API 后,点击下一步

  3. 预配实例。

    此步骤会在 Document AI Warehouse 服务中为您的项目预配资源。您必须从三种访问权限控制模式中进行选择。请仔细查看这些模式,以便为您的使用场景选择合适的模式。如需了解更多 信息,请参阅访问权限控制模式页面

    1. 选择访问权限控制 (ACL) 模式。

      • [推荐] 针对 Cloud Identity 用户实施文档级访问权限控制。

        适用于通过 Cloud Identity 管理用户或群组的组织。

        • Document AI Warehouse 界面支持此模式对用户进行身份验证。
        • 贵组织的 LDAP 和 Active Directory 用户和群组可以 同步到Cloud Identity

        • Google Workspace 用户可以 轻松 添加到 Cloud Identity

      • 针对自备身份服务的用户实施文档级访问权限控制。

        如果您的用户无法添加或同步到 Cloud Identity,请使用此模式。但是:

        • Document AI Warehouse 界面不支持此模式,可能需要使用自定义客户端应用。
        • 自定义客户端应用将与身份提供方验证用户身份,并通过 Document AI Warehouse API 传递用户和群组成员身份。
      • 公开访问权限:不进行文档级访问权限控制。

        • Document AI Warehouse 界面支持此模式对用户进行身份验证。
        • 此模式通常用于向公众用户(无需身份验证)授予访问权限。
        • 自定义门户可以使用具有所需角色(例如“Document Viewer”角色)的服务账号访问所有文档,并将此访问权限转给无需进行身份验证的公众用户。
      针对 Cloud Identity 用户实施文档级访问权限控制 针对自备身份服务的用户实施文档级访问权限控制 通用访问权限
      文档级访问权限
      Document AI Warehouse 界面支持 是(如果用户拥有项目级访问权限)

    2. 启用问答功能:

      如果您想在项目中启用生成式 AI 搜索功能,请勾选问答 。如需了解详情(包括如何列入许可名单以使用该功能),请参阅生成式 AI 搜索

  4. 触发预配:

    点击预配 以开始预配您的项目。设置实例需要一段时间(3-5 分钟)。

  5. 创建默认架构。

    在初始化步骤中,点击创建 。这会创建一个默认架构,可用于 OCR 提取的 PDF 或 TXT 文件。它包含用于编制索引的原始文本字段,但不包含属性。

  6. 查看实例:

    这会完成您的预配过程。如果您的项目使用文档级 访问权限控制,请继续下一部分 以设置项目级权限。

    如果您已列入许可名单以使用 Google Cloud 控制台界面功能,则可以点击开始 使用,以便在 Google Cloud 控制台中开始使用 Document AI Warehouse。

    如果您未列入许可名单以使用 Google Cloud 控制台界面功能,则可以继续 配置 Web 应用 ,了解如何设置 Document AI Warehouse Web 应用。

  7. 在 IAM 中为您的用户配置所需权限。 如果启用了文档级访问权限控制,则需要项目级权限和 IAM 权限。如需了解详情,请参阅所需 权限

设置项目级权限

如果您的项目启用了文档级访问权限控制(在 ACL 模式 选择中选择选项 1),则必须向管理员账号 以及用户授予项目级权限。

为此,请在预配后的最终视图中前往项目权限

请按照以下步骤将您的管理员账号添加为 Document Admin

  1. 点击添加用户

  2. 输入管理员的电子邮件地址,然后选择 Document Admin 作为访问权限级别。 点击保存

  3. 对于其他用户,您可以将其添加为:

    1. 文档管理员:拥有对项目中所有文档的完整访问权限的角色,包括上传文档以及查看/修改/删除所有文档,无论文档所有者是谁。此外,文档管理员还可以更改所有文档的权限。

    2. 文档编辑者:拥有查看和修改所有 文档的权限的角色,但无法在项目中创建和删除文档 ,也无法更改文档的权限。

    3. Document Viewer:仅拥有查看所有 文档的权限的角色。文档查看者无法创建、修改、删除或更改文档的权限。

    4. 文档创建者:仅拥有文档上传权限的角色。文档创建者对其上传的文档拥有完整权限,但对任何其他文档没有任何其他权限,除非他们获得这些文档的明确权限。

  4. 电子邮件地址可以是单个用户的电子邮件地址,也可以是群组的电子邮件地址。指定群组电子邮件地址时,请在类型 字段中选择群组

所需权限

在 Document AI Warehouse 中,我们在 IAM 的基础上构建了一个独立的 ACL 系统。对于文档级 ACL 项目,您需要在 Document AI Warehouse 的 ACL 系统中获取额外的项目级权限。对于公开访问权限项目,只需要 IAM 权限。

以下是所需权限的摘要表:

文档 ACL 项目

用户类型 IAM 角色 Document AI Warehouse 的项目级权限
管理员用户 Content Warehouse Admin Document Admin
普通用户 Content Warehouse document Schema Viewer Document Creator/Editor/Viewer,具体取决于预期权限

公开访问权限项目

用户类型 IAM 角色
管理员用户 1. Content Warehouse Admin
2. Content Warehouse document admin
普通用户 1. Content Warehouse document Schema Viewer
2. Content Warehouse document creator/viewer/editor,具体取决于预期权限
公开访问权限项目的 IAM 角色
角色名称 角色名称 用途
Content Warehouse document creator contentwarehouse.documentCreator 创建文档
Content Warehouse document viewer contentwarehouse.documentViewer 查看任何文档
Content Warehouse document editor contentwarehouse.documentEditor 修改任何文档(不包括创建和删除)
Content Warehouse document admin contentwarehouse.documentAdmin 管理任何文档(包括创建和删除)
Content Warehouse Admin contentwarehouse.admin 管理任何文档以及架构和规则

如需了解详情,请参阅 IAM 角色和 权限

设置访问令牌(用于通过命令行调用 API)

如需使用命令行工具调用 Document AI Warehouse API,请按照以下步骤操作。

在您的环境中使用服务帐号密钥文件

安装并初始化 Google Cloud CLI(可选)

gcloud CLI 提供了一组工具,可用于管理上托管的资源和应用。 Google Cloud

以下链接提供了相关说明:

安装 Google Cloud CLI。 安装完成后, 初始化 Google Cloud CLI,方法是运行以下命令:

gcloud init

如果您使用的是外部身份提供方 (IdP),则必须先 使用联合身份登录 gcloud CLI

生成访问令牌

如果您在前面的步骤中设置了身份验证,则可以使用 Google Cloud CLI 测试您的身份验证环境。执行以下命令,确认没有错误发生并且返回了凭据:

AUTH_TOKEN=$(gcloud auth application-default print-access-token --scopes=https://www.googleapis.com/auth/cloud-platform)

预计 AUTH_TOKEN 已设置,例如:

$ echo $AUTH_TOKEN
ya29.c.b0AXv0zTPvXmEMZXCe781qL0Y3r1EKnw3k4DJcoWGZkyWKx-nMNVQVErQ3ge6XA2RXsTU1tf_SMLgeWC6xwS51tP8QZhbypuGczBzMgKWYExwATHt3Vn553edl8tmqCMjROgdQjCDd8i7as-236r4d8gNwKsR192gNgNw_0zzs0MPyNVmqydpfmpj8yBwJI5QWna1331GTGKgd3Ia16fTzAHrZC_GkcO0wJPo....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................

测试调用 Document AI Warehouse API

所有 Document AI Warehouse API REST 示例都会使用 AUTH_TOKEN 对 API 调用进行身份验证。例如,以下命令会检索您定义的所有与项目关联的文档架构(在大多数情况下,请使用“us”作为位置):

  curl --header "Authorization: Bearer $AUTH_TOKEN" https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER>/locations/LOCATION/documentSchemas

代码示例

Java

如需了解详情,请参阅 Document AI Warehouse Java API 参考文档

如需向 Document AI Warehouse 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅 为本地开发环境设置身份验证

public class QuickStart {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String userId = "your-user-id"; // Format is user:<user-id>
    quickStart(projectId, location, userId);
  }

  public static void quickStart(String projectId, String location, String userId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentSchemaServiceSettings documentSchemaServiceSettings = 
         DocumentSchemaServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Schema Service client
    try (DocumentSchemaServiceClient documentSchemaServiceClient =
        DocumentSchemaServiceClient.create(documentSchemaServiceSettings)) {
      /*  The full resource name of the location, e.g.:
      projects/{project_number}/locations/{location} */
      String parent = LocationName.format(projectNumber, location);

      /* Create Document Schema with Text Type Property Definition
       * More detail on managing Document Schemas: 
       * https://cloud.google.com/document-warehouse/docs/manage-document-schemas */
      DocumentSchema documentSchema = DocumentSchema.newBuilder()
          .setDisplayName("My Test Schema")
          .setDescription("My Test Schema's Description")
          .addPropertyDefinitions(
            PropertyDefinition.newBuilder()
              .setName("test_symbol")
              .setDisplayName("Searchable text")
              .setIsSearchable(true)
              .setTextTypeOptions(TextTypeOptions.newBuilder().build())
              .build()).build();

      // Define Document Schema request
      CreateDocumentSchemaRequest createDocumentSchemaRequest =
          CreateDocumentSchemaRequest.newBuilder()
            .setParent(parent)
            .setDocumentSchema(documentSchema).build();

      // Create Document Schema
      DocumentSchema documentSchemaResponse =
          documentSchemaServiceClient.createDocumentSchema(createDocumentSchemaRequest); 


      // Create Document Service Client Settings
      DocumentServiceSettings documentServiceSettings = 
          DocumentServiceSettings.newBuilder().setEndpoint(endpoint).build();

      // Create Document Service Client and Document with relevant properties 
      try (DocumentServiceClient documentServiceClient =
          DocumentServiceClient.create(documentServiceSettings)) {
        TextArray textArray = TextArray.newBuilder().addValues("Test").build();
        Document document = Document.newBuilder()
              .setDisplayName("My Test Document")
              .setDocumentSchemaName(documentSchemaResponse.getName())
              .setPlainText("This is a sample of a document's text.")
              .addProperties(
                Property.newBuilder()
                  .setName(documentSchema.getPropertyDefinitions(0).getName())
                  .setTextValues(textArray)).build();

        // Define Request Metadata for enforcing access control
        RequestMetadata requestMetadata = RequestMetadata.newBuilder()
            .setUserInfo(
            UserInfo.newBuilder()
              .setId(userId).build()).build();

        // Define Create Document Request 
        CreateDocumentRequest createDocumentRequest = CreateDocumentRequest.newBuilder()
            .setParent(parent)
            .setDocument(document)
            .setRequestMetadata(requestMetadata)
            .build();

        // Create Document
        CreateDocumentResponse createDocumentResponse =
            documentServiceClient.createDocument(createDocumentRequest);

        System.out.println(createDocumentResponse.getDocument().getName());
        System.out.println(documentSchemaResponse.getName());
      }
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Node.js

如需了解详情,请参阅 Document AI Warehouse Node.js API 参考文档

如需向 Document AI Warehouse 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅 为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 * const projectNumber = 'YOUR_PROJECT_NUMBER';
 * const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
 * const userId = 'user:xxx@example.com'; // Format is "user:xxx@example.com"
 */

// Import from google cloud
const {DocumentSchemaServiceClient, DocumentServiceClient} =
  require('@google-cloud/contentwarehouse').v1;

const apiEndpoint =
  location === 'us'
    ? 'contentwarehouse.googleapis.com'
    : `${location}-contentwarehouse.googleapis.com`;

// Create service client
const schemaClient = new DocumentSchemaServiceClient({
  apiEndpoint: apiEndpoint,
});
const serviceClient = new DocumentServiceClient({apiEndpoint: apiEndpoint});

// Get Document Schema
async function quickstart() {
  // The full resource name of the location, e.g.:
  // projects/{project_number}/locations/{location}
  const parent = `projects/${projectNumber}/locations/${location}`;

  // Initialize request argument(s)
  const schemaRequest = {
    parent: parent,
    documentSchema: {
      displayName: 'My Test Schema',
      propertyDefinitions: [
        {
          name: 'testPropertyDefinitionName', // Must be unique within a document schema (case insensitive)
          displayName: 'searchable text',
          isSearchable: true,
          textTypeOptions: {},
        },
      ],
    },
  };

  // Create Document Schema
  const documentSchema =
    await schemaClient.createDocumentSchema(schemaRequest);

  const documentRequest = {
    parent: parent,
    document: {
      displayName: 'My Test Document',
      documentSchemaName: documentSchema[0].name,
      plainText: "This is a sample of a document's text.",
      properties: [
        {
          name: 'testPropertyDefinitionName',
          textValues: {values: ['GOOG']},
        },
      ],
    },
    requestMetadata: {userInfo: {id: userId}},
  };

  // Make Request
  const response = serviceClient.createDocument(documentRequest);

  // Print out response
  response.then(
    result => console.log(`Document Created: ${JSON.stringify(result)}`),
    error => console.log(`error: ${error}`)
  );
}

Python

如需了解详情,请参阅 Document AI Warehouse Python API 参考文档

如需向 Document AI Warehouse 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅 为本地开发环境设置身份验证


from google.cloud import contentwarehouse

# TODO(developer): Uncomment these variables before running the sample.
# project_number = 'YOUR_PROJECT_NUMBER'
# location = 'YOUR_PROJECT_LOCATION' # Format is 'us' or 'eu'
# user_id = "user:xxxx@example.com" # Format is "user:xxxx@example.com"


def quickstart(project_number: str, location: str, user_id: str) -> None:
    # Create a Schema Service client
    document_schema_client = contentwarehouse.DocumentSchemaServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}
    parent = document_schema_client.common_location_path(
        project=project_number, location=location
    )

    # Define Schema Property of Text Type
    property_definition = contentwarehouse.PropertyDefinition(
        name="stock_symbol",  # Must be unique within a document schema (case insensitive)
        display_name="Searchable text",
        is_searchable=True,
        text_type_options=contentwarehouse.TextTypeOptions(),
    )

    # Define Document Schema Request
    create_document_schema_request = contentwarehouse.CreateDocumentSchemaRequest(
        parent=parent,
        document_schema=contentwarehouse.DocumentSchema(
            display_name="My Test Schema",
            property_definitions=[property_definition],
        ),
    )

    # Create a Document schema
    document_schema = document_schema_client.create_document_schema(
        request=create_document_schema_request
    )

    # Create a Document Service client
    document_client = contentwarehouse.DocumentServiceClient()

    # The full resource name of the location, e.g.:
    # projects/{project_number}/locations/{location}
    parent = document_client.common_location_path(
        project=project_number, location=location
    )

    # Define Document Property Value
    document_property = contentwarehouse.Property(
        name=document_schema.property_definitions[0].name,
        text_values=contentwarehouse.TextArray(values=["GOOG"]),
    )

    # Define Document
    document = contentwarehouse.Document(
        display_name="My Test Document",
        document_schema_name=document_schema.name,
        plain_text="This is a sample of a document's text.",
        properties=[document_property],
    )

    # Define Request
    create_document_request = contentwarehouse.CreateDocumentRequest(
        parent=parent,
        document=document,
        request_metadata=contentwarehouse.RequestMetadata(
            user_info=contentwarehouse.UserInfo(id=user_id)
        ),
    )

    # Create a Document for the given schema
    response = document_client.create_document(request=create_document_request)

    # Read the output
    print(f"Rule Engine Output: {response.rule_engine_output}")
    print(f"Document Created: {response.document}")

后续步骤