发送处理请求

设置 Google Cloud 账号创建处理器后,您可以向 Document AI 处理器发送请求。

用于发送请求的代码对于所有处理器都是相同的。您会发现每个处理器输出的信息中都存在处理器功能方面的差异。

使用 v1 API 版本的 Document AI 或在 Google Cloud 控制台中,您可以向该特定处理器版本发送处理请求。如果您未指定处理器版本,则系统会使用默认版本。 如需了解详情,请参阅管理处理器版本

在线处理

通过在线(同步)请求,您可以发送单个文档进行处理。 Document AI 会立即处理请求并返回 document

向处理方发送请求

以下代码示例展示了如何向处理器发送请求。

REST

此示例展示了如何在 rawDocument 对象中提供文档内容(以字节为单位的原始文档内容,通过 base64 编码的字符串)。

或者,您也可以指定 inlineDocument,这与 Document AI 返回的 Document JSON 格式相同。这样,您便可以通过来回传递相同格式来链接请求(例如,如果您要对文档进行分类,然后提取其内容)。

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:处理器的位置,例如:
    • us - 美国
    • eu - 欧盟
  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • PROCESSOR_ID:自定义处理器的 ID。
  • skipHumanReview:一个布尔值,用于停用人工审核(仅受人机协同处理器支持)。
    • true - 跳过人工审核
    • false - 启用人工审核(默认)
  • MIME_TYPE:有效的 MIME 类型选项之一。
  • IMAGE_CONTENT:有效的内嵌文档内容之一,表示为字节流。对于 JSON 表示形式,二进制图片数据的 base64 编码(ASCII 字符串)。此字符串应类似于以下字符串:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    如需了解详情,请参阅 Base64 编码主题。
  • FIELD_MASK:指定要在 Document 输出中包含哪些字段。这是完全限定字段名称的逗号分隔列表,格式为 FieldMask
    • 示例:text,entities,pages.pageNumber
  • INDIVIDUAL_PAGES:要处理的各个网页的列表。
    • 或者,提供字段 fromStartfromEnd 以处理文档开头或结尾处的指定数量的页面。

† 也可以使用 inlineDocument 对象中的 base64 编码内容来指定此内容。

HTTP 方法和网址:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process

请求 JSON 正文:

{
  "skipHumanReview": skipHumanReview,
  "rawDocument": {
    "mimeType": "MIME_TYPE",
    "content": "IMAGE_CONTENT"
  },
  "fieldMask": "FIELD_MASK",
  "processOptions": {
    "individualPageSelector" {
      "pages": [INDIVIDUAL_PAGES]
    }
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:process" | Select-Object -Expand Content

如果请求成功,服务器将返回一个 200 OK HTTP 状态代码以及 JSON 格式的响应。响应正文包含一个 Document 实例。

向处理器版本发送请求

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:处理器的位置,例如:
    • us - 美国
    • eu - 欧盟
  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • PROCESSOR_ID:自定义处理器的 ID。
  • PROCESSOR_VERSION:处理器版本标识符。如需了解详情,请参阅选择处理器版本。例如:
    • pretrained-TYPE-vX.X-YYYY-MM-DD
    • stable
    • rc
  • skipHumanReview:一个布尔值,用于停用人工审核(仅受人机协同处理器支持)。
    • true - 跳过人工审核
    • false - 启用人工审核(默认)
  • MIME_TYPE:有效的 MIME 类型选项之一。
  • IMAGE_CONTENT:有效的内嵌文档内容之一,表示为字节流。对于 JSON 表示形式,二进制图片数据的 base64 编码(ASCII 字符串)。此字符串应类似于以下字符串:
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    如需了解详情,请参阅 Base64 编码主题。
  • FIELD_MASK:指定要在 Document 输出中包含哪些字段。这是完全限定字段名称的逗号分隔列表,格式为 FieldMask
    • 示例:text,entities,pages.pageNumber

† 也可以使用 inlineDocument 对象中的 base64 编码内容来指定此内容。

HTTP 方法和网址:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process

请求 JSON 正文:

{
  "skipHumanReview": skipHumanReview,
  "rawDocument": {
    "mimeType": "MIME_TYPE",
    "content": "IMAGE_CONTENT"
  },
  "fieldMask": "FIELD_MASK"
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID/processorVersions/PROCESSOR_VERSION:process" | Select-Object -Expand Content

如果请求成功,服务器将返回一个 200 OK HTTP 状态代码以及 JSON 格式的响应。响应正文包含一个 Document 实例。

C#

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

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


using Google.Cloud.DocumentAI.V1;
using Google.Protobuf;
using System;
using System.IO;

public class QuickstartSample
{
    public Document Quickstart(
        string projectId = "your-project-id",
        string locationId = "your-processor-location",
        string processorId = "your-processor-id",
        string localPath = "my-local-path/my-file-name",
        string mimeType = "application/pdf"
    )
    {
        // Create client
        var client = new DocumentProcessorServiceClientBuilder
        {
            Endpoint = $"{locationId}-documentai.googleapis.com"
        }.Build();

        // Read in local file
        using var fileStream = File.OpenRead(localPath);
        var rawDocument = new RawDocument
        {
            Content = ByteString.FromStream(fileStream),
            MimeType = mimeType
        };

        // Initialize request argument(s)
        var request = new ProcessRequest
        {
            Name = ProcessorName.FromProjectLocationProcessor(projectId, locationId, processorId).ToString(),
            RawDocument = rawDocument
        };

        // Make the request
        var response = client.ProcessDocument(request);

        var document = response.Document;
        Console.WriteLine(document.Text);
        return document;
    }
}

Java

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

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


import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.ProcessRequest;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.cloud.documentai.v1.RawDocument;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ProcessDocument {
  public static void processDocument()
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-project-location"; // Format is "us" or "eu".
    String processerId = "your-processor-id";
    String filePath = "path/to/input/file.pdf";
    processDocument(projectId, location, processerId, filePath);
  }

  public static void processDocument(
      String projectId, String location, String processorId, String filePath)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // 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.
    String endpoint = String.format("%s-documentai.googleapis.com:443", location);
    DocumentProcessorServiceSettings settings =
        DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();
    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      // The full resource name of the processor, e.g.:
      // projects/project-id/locations/location/processor/processor-id
      // You must create new processors in the Cloud Console first
      String name =
          String.format("projects/%s/locations/%s/processors/%s", projectId, location, processorId);

      // Read the file.
      byte[] imageFileData = Files.readAllBytes(Paths.get(filePath));

      // Convert the image data to a Buffer and base64 encode it.
      ByteString content = ByteString.copyFrom(imageFileData);

      RawDocument document =
          RawDocument.newBuilder().setContent(content).setMimeType("application/pdf").build();

      // Configure the process request.
      ProcessRequest request =
          ProcessRequest.newBuilder().setName(name).setRawDocument(document).build();

      // Recognizes text entities in the PDF document
      ProcessResponse result = client.processDocument(request);
      Document documentResponse = result.getDocument();

      // Get all of the document text as one big string
      String text = documentResponse.getText();

      // Read the text recognition output from the processor
      System.out.println("The document contains the following paragraphs:");
      Document.Page firstPage = documentResponse.getPages(0);
      List<Document.Page.Paragraph> paragraphs = firstPage.getParagraphsList();

      for (Document.Page.Paragraph paragraph : paragraphs) {
        String paragraphText = getText(paragraph.getLayout().getTextAnchor(), text);
        System.out.printf("Paragraph text:\n%s\n", paragraphText);
      }

      // Form parsing provides additional output about
      // form-formatted PDFs. You must create a form
      // processor in the Cloud Console to see full field details.
      System.out.println("The following form key/value pairs were detected:");

      for (Document.Page.FormField field : firstPage.getFormFieldsList()) {
        String fieldName = getText(field.getFieldName().getTextAnchor(), text);
        String fieldValue = getText(field.getFieldValue().getTextAnchor(), text);

        System.out.println("Extracted form fields pair:");
        System.out.printf("\t(%s, %s))\n", fieldName, fieldValue);
      }
    }
  }

  // Extract shards from the text field
  private static String getText(Document.TextAnchor textAnchor, String text) {
    if (textAnchor.getTextSegmentsList().size() > 0) {
      int startIdx = (int)