処理リクエストの送信

Google Cloud アカウントを設定し、プロセッサを作成したら、Document AI プロセッサにリクエストを送信できます。

リクエストの送信に使用されるコードは、すべてのプロセッサで同じです。各プロセッサが出力する情報で、プロセッサの機能の違いを確認できます。

Document AI の v1 API バージョンまたは Google Cloud コンソールを使用すると、特定のプロセッサ バージョンに処理リクエストを送信できます。プロセッサ バージョンを指定しない場合、デフォルトのバージョンが使用されます。詳細については、プロセッサ バージョンの管理をご覧ください。

オンライン処理

オンライン(同期)リクエストでは、処理する単一のドキュメントを送信できます。Document AI はリクエストを直ちに処理し、document を返します。

プロセッサにリクエストを送信する

次のコードサンプルは、プロセッサにリクエストを送信する方法を示しています。

REST

このサンプルでは、rawDocument オブジェクトでドキュメント コンテンツ(Base64 でエンコードされた文字列を介したバイト単位の未加工のドキュメント コンテンツ)を指定する方法を示します。

また、Document AI から返される Document JSON 形式と同じ inlineDocument を指定することもできます。これにより、同じ形式をやり取りしてリクエストをチェーンできます(ドキュメントを分類してからコンテンツを抽出する場合など)。

リクエストのデータを使用する前に、次のように置き換えます。

  • 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: 処理する個々のページのリスト。
    • または、フィールド fromStart または fromEnd を指定して、ドキュメントの先頭または末尾から特定のページ数を処理します。

† このコンテンツは、inlineDocument オブジェクトで base64 エンコードされたコンテンツを使用して指定することもできます。

HTTP メソッドと URL:

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: プロセッサのバージョン ID。詳細については、プロセッサ バージョンを選択するをご覧ください。例:
    • 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 メソッドと URL:

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(