Enterprise Document OCR

Document AI の一部として Enterprise Document OCR を使用すると、さまざまなドキュメントからテキストとレイアウト情報を検出して抽出できます。構成可能な機能を使用すると、特定のドキュメント処理要件を満たすようにシステムをカスタマイズできます。

概要

Enterprise Document OCR は、アルゴリズムや機械学習に基づくデータ入力、データ精度の向上と検証などのタスクに使用できます。Enterprise Document OCR を使用して、次のようなタスクを処理することもできます。

  • テキストのデジタル化: 検索、ルールベースのドキュメント処理パイプライン、カスタムモデルの作成のために、ドキュメントからテキストとレイアウト データを抽出します。
  • 大規模言語モデル アプリケーションの使用: LLM のコンテキスト理解と OCR のテキストとレイアウトの抽出機能を使用して、質問と回答を自動化します。データから分析情報を引き出し、ワークフローを効率化します。
  • アーカイブ: 紙のドキュメントを機械で読み取り可能なテキストにデジタル化して、ドキュメントのアクセシビリティを向上させます。

ユースケースに最適な OCR の選択

ソリューション プロダクト 説明 ユースケース
Document AI Enterprise Document OCR ドキュメントのユースケースに特化したモデル。高度な機能には、画像の品質スコア、言語ヒント、回転補正などがあります。 ドキュメントからテキストを抽出する場合におすすめです。ユースケースには、PDF、スキャンした画像、Microsoft DocX ファイルなどがあります。
Document AI OCR アドオン 特定の要件に対応するプレミアム機能。Enterprise Document OCR バージョン 2.0 以降とのみ互換性があります。 数式の検出と認識、フォント スタイル情報の受信、チェックボックス抽出の有効化が必要な場合。
Cloud Vision API テキスト検出 Google Cloud 標準 OCR モデルに基づく、グローバルに利用可能な REST API。デフォルトの割り当ては 1 分あたり 1,800 リクエストです。 低レイテンシと高容量が求められる一般的なテキスト抽出のユースケース。
Cloud Vision OCR Google Distributed Cloud(非推奨) Google Cloud Marketplace のアプリケーション。GKE Enterprise を使用して任意の GKE クラスタにコンテナとしてデプロイできます。 データ所在地またはコンプライアンスの要件を満たすため。

検出と抽出

Enterprise Document OCR は、PDF や画像からブロック、段落、行、単語、記号を検出できます。また、ドキュメントの傾きを補正して精度を向上させることもできます。

サポートされているレイアウト検出と抽出の属性:

印刷されたテキスト 手書き入力 段落 ブロック ライン Word シンボルレベル ページ番号
デフォルト デフォルト デフォルト デフォルト デフォルト デフォルト 構成可能 デフォルト

構成可能な Enterprise Document OCR 機能には、次のものがあります。

  • デジタル PDF から埋め込みテキストまたはネイティブ テキストを抽出する: この機能は、回転したテキスト、極端なフォントサイズやスタイル、部分的に隠れたテキストなど、ソース ドキュメントに表示されているとおりにテキストや記号を抽出します。

  • 回転補正: Enterprise Document OCR を使用してドキュメント画像を前処理し、抽出の品質や処理に影響する可能性のある回転の問題を修正します。

  • 画質スコア: ドキュメントのルーティングに役立つ品質指標を受け取ります。画質スコアは、ぼやけ、通常より小さいフォントの存在、グレアなど、8 つのディメンションでページレベルの品質指標を提供します。

  • ページ範囲を指定する: OCR の入力ドキュメントのページ範囲を指定します。これにより、不要なページにかかる費用と処理時間を節約できます。

  • 言語検出: 抽出されたテキストで使用されている言語を検出します。

  • 言語と手書きのヒント: データセットの既知の特性に基づいて OCR モデルに言語または手書きのヒントを提供することで、精度を向上させます。

OCR 構成を有効にする方法については、OCR 構成を有効にするをご覧ください。

OCR アドオン

Enterprise Document OCR には、必要に応じて個々の処理リクエストで有効にできるオプションの分析機能が用意されています。

次のアドオン機能は、安定版の pretrained-ocr-v2.0-2023-06-02 バージョンと pretrained-ocr-v2.1-2024-08-07 バージョン、リリース候補版の pretrained-ocr-v2.1.1-2025-01-31 バージョンで利用できます。

  • Math OCR: LaTeX 形式のドキュメントから数式を特定して抽出します。
  • チェックボックスの抽出: チェックボックスを検出し、Enterprise Document OCR レスポンスでそのステータス(マーク付き / マークなし)を抽出します。
  • フォント スタイルの検出: フォントの種類、フォント スタイル、手書き、太さ、色など、単語レベルのフォント プロパティを識別します。

リストされているアドオンを有効にする方法については、OCR アドオンを有効にするをご覧ください。

サポートされているファイル形式

Enterprise Document OCR は、PDF、GIF、TIFF、JPEG、PNG、BMP、WebP のファイル形式をサポートしています。詳細については、サポートされているファイルをご覧ください。

Enterprise Document OCR は、同期で最大 15 ページ、非同期で最大 30 ページの DocX ファイルもサポートしています。割り当て増加リクエスト(QIR)を行うには、割り当ての調整をリクエストするの手順に沿って操作します。DocX のサポートは限定公開プレビュー版です。アクセス権のリクエストについては、Google アカウント チームにお問い合わせください。

高度なバージョニング

高度なバージョニングはプレビュー版です。基盤となる AI / ML OCR モデルのアップグレードにより、OCR の動作が変更される可能性があります。厳密な整合性が必要な場合は、固定モデル バージョンを使用して、以前の OCR モデルの動作を最大 18 か月間固定します。これにより、同じ画像に対して OCR 関数が同じ結果を返すようになります。プロセッサ バージョンの表をご覧ください。

プロセッサのバージョン

この機能と互換性があるプロセッサ バージョンは次のとおりです。詳細については、プロセッサ バージョンの管理をご覧ください。

バージョン ID リリース チャンネル 説明
pretrained-ocr-v1.2-2022-11-10 Stable v1.0 のフリーズされたモデル バージョン: コンテナ イメージで最大 18 か月間フリーズされたバージョン スナップショットのモデルファイル、構成、バイナリ。
pretrained-ocr-v2.0-2023-06-02 Stable ドキュメントのユースケースに特化した、本番環境に対応したモデル。すべての OCR アドオンへのアクセスが含まれます。
pretrained-ocr-v2.1-2024-08-07 Stable v2.1 の主な改善点は、印刷されたテキストの認識精度の向上、チェックボックス検出の精度の向上、読み取り順序の精度の向上です。
pretrained-ocr-v2.1.1-2025-01-31 リリース候補 v2.1.1 は V2.1 と同様で、US、EU、asia-southeast1 を除くすべてのリージョンで利用できます。

Enterprise Document OCR を使用してドキュメントを処理する

このクイックスタートでは、Enterprise Document OCR の概要について説明します。利用可能な OCR 構成を有効または無効にして、ワークフローのドキュメント OCR 結果を最適化する方法について説明します。

  1. Google Cloud アカウントにログインします。 Google Cloudを初めて使用する場合は、アカウントを作成して、実際のシナリオで Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $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 Document AI API, if it is 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 API

  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 Document AI API, if it is 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 API

Enterprise Document OCR プロセッサを作成する

まず、Enterprise Document OCR プロセッサを作成します。詳細については、プロセッサの作成と管理をご覧ください。

OCR 構成

すべての OCR 構成は、ProcessDocumentRequest または BatchProcessDocumentsRequest の ProcessOptions.ocrConfig でそれぞれのフィールドを設定することで有効にできます。

詳細については、処理リクエストを送信するをご覧ください。

画質分析

インテリジェントなドキュメント品質分析では、機械学習を使用して、コンテンツの読みやすさに基づいてドキュメントの品質評価を行います。この品質評価は品質スコア [0, 1] として返されます。1 は品質が完全であることを意味します。検出された品質スコアが 0.5 未満の場合、品質が低い理由のリスト(可能性が高い順)も返されます。0.5 を超える可能性は、陽性検出と見なされます。

ドキュメントに欠陥があると見なされた場合、API は次の 8 つのドキュメント欠陥タイプを返します。

  • quality/defect_blurry
  • quality/defect_noisy
  • quality/defect_dark
  • quality/defect_faint
  • quality/defect_text_too_small
  • quality/defect_document_cutoff
  • quality/defect_text_cutoff
  • quality/defect_glare

現在のドキュメント品質分析には、いくつかの制限があります。

  • 欠陥のないデジタル ドキュメントで偽陽性が返されることがあります。この機能は、スキャンまたは撮影されたドキュメントに最適です。
  • グレアの欠陥は局所的です。これらの存在がドキュメント全体の読みやすさを妨げることはないかもしれません。

入力

処理リクエストで ProcessOptions.ocrConfig.enableImageQualityScores を true に設定して有効にします。この追加機能により、処理呼び出しに OCR 処理と同等のレイテンシが追加されます。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
        "enableImageQualityScores": true
      }
    }
  }

出力

欠陥検出の結果が Document.pages[].imageQualityScores[] に表示されます。

  {
    "pages": [
      {
        "imageQualityScores": {
          "qualityScore": 0.7811847,
          "detectedDefects": [
            {
              "type": "quality/defect_document_cutoff",
              "confidence": 1.0
            },
            {
              "type": "quality/defect_glare",
              "confidence": 0.97849524
            },
            {
              "type": "quality/defect_text_cutoff",
              "confidence": 0.5
            }
          ]
        }
      }
    ]
  }

完全な出力例については、プロセッサ出力の例をご覧ください。

言語ヒント

OCR プロセッサは、OCR エンジンのパフォーマンスを向上させるために定義する言語ヒントをサポートしています。言語ヒントを適用すると、OCR は推測された言語ではなく、選択された言語に合わせて最適化されます。

入力

BCP-47 言語コードのリストを使用して ProcessOptions.ocrConfig.hints[].languageHints[] を設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
        "hints": {
          "languageHints": ["en", "es"]
        }
      }
    }
  }

完全な出力例については、プロセッサ出力の例をご覧ください。

記号検出

ドキュメント レスポンスの記号(または個々の文字)レベルでデータを入力します。

入力

処理リクエストで ProcessOptions.ocrConfig.enableSymbol を true に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
        "enableSymbol": true
      }
    }
  }

出力

この機能が有効になっている場合、Document.pages[].symbols[] フィールドに値が入力されます。

完全な出力例については、プロセッサ出力の例をご覧ください。

組み込みの PDF 解析

デジタル PDF ファイルから埋め込みテキストを抽出します。有効にすると、デジタル テキストがある場合に、組み込みのデジタル PDF モデルが自動的に使用されます。デジタル以外のテキストがある場合は、光学 OCR モデルが自動的に使用されます。ユーザーは、両方のテキスト結果が統合されたものを受け取ります。

入力

処理リクエストで ProcessOptions.ocrConfig.enableNativePdfParsing を true に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
        "enableNativePdfParsing": true
      }
    }
  }

ボックス内の文字の検出

デフォルトでは、Enterprise Document OCR には、ボックス内の文字のテキスト抽出品質を向上させる検出機能が有効になっています。以下に例を示します。

enterprise-document-ocr-1

ボックス内の文字で OCR の品質に問題が発生している場合は、この機能を無効にできます。

入力

処理リクエストで ProcessOptions.ocrConfig.disableCharacterBoxesDetection を true に設定して無効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
        "disableCharacterBoxesDetection": true
      }
    }
  }

以前のレイアウト

ヒューリスティック レイアウト検出アルゴリズムが必要な場合は、従来のレイアウトを有効にできます。これは、現在の ML ベースのレイアウト検出アルゴリズムの代替として機能します。これは推奨される構成ではありません。お客様は、ドキュメント ワークフローに基づいて最適なレイアウト アルゴリズムを選択できます。

入力

処理リクエストで ProcessOptions.ocrConfig.advancedOcrOptions を ["legacy_layout"] に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
          "advancedOcrOptions": ["legacy_layout"]
      }
    }
  }

ページ範囲を指定する

デフォルトでは、OCR はドキュメント内のすべてのページからテキストとレイアウト情報を抽出します。特定のページ番号またはページ範囲を選択して、それらのページからのみテキストを抽出できます。

ProcessOptions でこれを構成するには、次の 3 つの方法があります。

  • 2 ページ目と 5 ページ目のみを処理するには:
  {
    "individualPageSelector": {"pages": [2, 5]}
  }
  • 最初の 3 ページのみを処理するには:
  {
    "fromStart": 3
  }
  • 最後の 4 ページのみを処理するには:
  {
    "fromEnd": 4
  }

レスポンスでは、各 Document.pages[].pageNumber はリクエストで指定された同じページに対応します。

OCR アドオンの使用

これらの Enterprise Document OCR のオプションの分析機能は、必要に応じて個々の処理リクエストで有効にできます。

数学 OCR

Math OCR は、LaTeX として表される数式などの数式を、境界ボックスの座標とともに検出、認識、抽出します。

LaTeX 表現の例を次に示します。

  • 画像が検出されました

    enterprise-document-ocr-2

  • LaTeX への変換

    enterprise-document-ocr-3

入力

処理リクエストで ProcessOptions.ocrConfig.premiumFeatures.enableMathOcr を true に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
          "premiumFeatures": {
            "enableMathOcr": true
          }
      }
    }
  }

出力

Math OCR の出力は、"type": "math_formula" を含む Document.pages[].visualElements[] に表示されます。

"visualElements": [
  {
    "layout": {
      "textAnchor": {
        "textSegments": [
          {
            "endIndex": "46"
          }
        ]
      },
      "confidence": 1,
      "boundingPoly": {
        "normalizedVertices": [
          {
            "x": 0.14662756,
            "y": 0.27891156
          },
          {
            "x": 0.9032258,
            "y": 0.27891156
          },
          {
            "x": 0.9032258,
            "y": 0.8027211
          },
          {
            "x": 0.14662756,
            "y": 0.8027211
          }
        ]
      },
      "orientation": "PAGE_UP"
    },
    "type": "math_formula"
  }
]

Document の完全な JSON 出力は、こちらのリンクで確認できます。

選択マークの抽出

有効にすると、モデルはドキュメント内のすべてのチェックボックスとラジオボタンを、境界ボックスの座標とともに抽出します。

入力

処理リクエストで ProcessOptions.ocrConfig.premiumFeatures.enableSelectionMarkDetection を true に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
          "premiumFeatures": {
            "enableSelectionMarkDetection": true
          }
      }
    }
  }

出力

チェックボックスの出力は、"type": "unfilled_checkbox" または "type": "filled_checkbox" を含む Document.pages[].visualElements[] に表示されます。

"visualElements": [
  {
    "layout": {
      "confidence": 0.89363575,
      "boundingPoly": {
        "vertices": [
          {
            "x": 11,
            "y": 24
          },
          {
            "x": 37,
            "y": 24
          },
          {
            "x": 37,
            "y": 56
          },
          {
            "x": 11,
            "y": 56
          }
        ],
        "normalizedVertices": [
          {
            "x": 0.017488075,
            "y": 0.38709676
          },
          {
            "x": 0.05882353,
            "y": 0.38709676
          },
          {
            "x": 0.05882353,
            "y": 0.9032258
          },
          {
            "x": 0.017488075,
            "y": 0.9032258
          }
        ]
      }
    },
    "type": "unfilled_checkbox"
  },
  {
    "layout": {
      "confidence": 0.9148201,
      "boundingPoly": ...
    },
    "type": "filled_checkbox"
  }
],

Document の完全な JSON 出力は、こちらのリンクで確認できます。

フォント スタイルの検出

フォントスタイルの検出を有効にすると、Enterprise Document OCR はフォント属性を抽出します。これは、より適切な後処理に使用できます。

トークン(単語)レベルでは、次の属性が検出されます。

  • 手書き入力の検出
  • フォント スタイル
  • フォントサイズ
  • フォントの種類
  • フォントの色
  • フォントの太さ
  • 文字間隔
  • 太字
  • 斜体
  • 下線
  • テキストの色(RGBa)
  • 背景色(RGBa)

入力

処理リクエストで ProcessOptions.ocrConfig.premiumFeatures.computeStyleInfo を true に設定して有効にします。

  {
    "rawDocument": {
      "mimeType": "MIME_TYPE",
      "content": "IMAGE_CONTENT"
    },
    "processOptions": {
      "ocrConfig": {
          "premiumFeatures": {
            "computeStyleInfo": true
          }
      }
    }
  }

出力

フォントスタイルの出力は、Document.pages[].tokens[].styleInfo に StyleInfo タイプで表示されます。

"tokens": [
  {
    "styleInfo": {
      "fontSize": 3,
      "pixelFontSize": 13,
      "fontType": "SANS_SERIF",
      "bold": true,
      "fontWeight": 564,
      "textColor": {
        "red": 0.16862746,
        "green": 0.16862746,
        "blue": 0.16862746
      },
      "backgroundColor": {
        "red": 0.98039216,
        "green": 0.9882353,
        "blue": 0.99215686
      }
    }
  },
  ...
]

Document の完全な JSON 出力は、こちらのリンクで確認できます。

ドキュメント オブジェクトを Vision AI API 形式に変換する

Document AI Toolbox には、Document AI API の Document 形式を Vision AI の AnnotateFileResponse 形式に変換するツールが含まれています。これにより、ユーザーはドキュメント OCR プロセッサと Vision AI API のレスポンスを比較できます。サンプルコードを以下に示します。

Vision AI API レスポンスと Document AI API レスポンスおよびコンバータの既知の不一致:

  • Vision AI API レスポンスでは、画像リクエストの場合は vertices のみが入力され、PDF リクエストの場合は normalized_vertices のみが入力されます。Document AI レスポンスとコンバータは、vertices と normalized_vertices の両方に値を入力します。
  • Vision AI API レスポンスは、単語の最後の記号に detected_break を入力します。Document AI API レスポンスとコンバータは、単語と単語の最後の記号に detected_break を入力します。
  • Vision AI API レスポンスでは、常に symbols フィールドが入力されます。デフォルトでは、Document AI のレスポンスに記号フィールドは入力されません。Document AI レスポンスとコンバータで記号フィールドが入力されるようにするには、enable_symbol 機能を詳細に設定します。

コードサンプル

次のコードサンプルは、OCR 構成とアドオンを有効にして処理リクエストを送信し、フィールドを読み取ってターミナルに出力する方法を示しています。

REST

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

  • 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†: 有効なインライン ドキュメント コンテンツの 1 つ。バイト ストリームとして表されます。JSON 表現の場合、バイナリ画像データの base64 エンコード(ASCII 文字列)。これは次のような文字列になります。
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    詳細については、Base64 エンコードをご覧ください。
  • FIELD_MASK: Document 出力に含めるフィールドを指定します。これは、FieldMask 形式の完全修飾フィールド名のカンマ区切りのリストです。
    • 例: text,entities,pages.pageNumber
  • OCR 構成
    • ENABLE_NATIVE_PDF_PARSING:(ブール値)PDF から埋め込みテキストを抽出します(利用可能な場合)。
    • ENABLE_IMAGE_QUALITY_SCORES:(ブール値)ドキュメントのインテリジェントな品質スコアを有効にします。
    • ENABLE_SYMBOL:(ブール値)記号(文字)の OCR 情報を含めます。
    • DISABLE_CHARACTER_BOXES_DETECTION:(ブール値)OCR エンジンで文字ボックス検出機能をオフにします。
    • LANGUAGE_HINTS: OCR に使用する BCP-47 言語コードのリスト。
    • ADVANCED_OCR_OPTIONS: OCR の動作をさらに微調整するための高度な OCR オプションのリスト。現在有効な値は次のとおりです。
      • legacy_layout: ヒューリスティック レイアウト検出アルゴリズム。現在の ML ベースのレイアウト検出アルゴリズムの代替として機能します。
  • プレミアム OCR アドオン
    • ENABLE_SELECTION_MARK_DETECTION:(ブール値)OCR エンジンで選択マーク検出機能を有効にします。
    • COMPUTE_STYLE_INFO(ブール値)フォント識別モデルを有効にして、フォント スタイル情報を返します。
    • ENABLE_MATH_OCR:(ブール値)LaTeX 数学公式を抽出できるモデルを有効にします。
  • INDIVIDUAL_PAGES: 処理する個々のページのリスト。
    • または、fromStart フィールドまたは fromEnd フィールドを指定して、ドキュメントの先頭または末尾から特定のページ数を処理します。

† このコンテンツは、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",
  "processOptions": {
    "ocrConfig": {
      "enableNativePdfParsing": ENABLE_NATIVE_PDF_PARSING,
      "enableImageQualityScores": ENABLE_IMAGE_QUALITY_SCORES,
      "enableSymbol": ENABLE_SYMBOL,
      "disableCharacterBoxesDetection": DISABLE_CHARACTER_BOXES_DETECTION,
      "hints": {
        "languageHints": [
          "LANGUAGE_HINTS"
        ]
      },
      "advancedOcrOptions": ["ADVANCED_OCR_OPTIONS"],
      "premiumFeatures": {
        "enableSelectionMarkDetection": ENABLE_SELECTION_MARK_DETECTION,
        "computeStyleInfo": COMPUTE_STYLE_INFO,
        "enableMathOcr": ENABLE_MATH_OCR,
      }
    },
    "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/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 のインスタンスが含まれます。

Python

詳細については、Document AI Python API リファレンス ドキュメントをご覧ください。

Document AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


from typing import Optional, Sequence

from google.api_core.client_options import ClientOptions
from google.cloud import documentai

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_PROCESSOR_LOCATION" # Format is "us" or "eu"
# processor_id = "YOUR_PROCESSOR_ID" # Create processor before running sample
# processor_version = "rc" # Refer to https://cloud.google.com/document-ai/docs/manage-processor-versions for more information
# file_path = "/path/to/local/pdf"
# mime_type = "application/pdf" # Refer to https://cloud.google.com/document-ai/docs/file-types for supported file types


def process_document_ocr_sample(
    project_id: str,
    location: str,
    processor_id: str,
    processor_version: str,
    file_path: str,
    mime_type: str,
) -> None:
    # Optional: Additional configurations for Document OCR Processor.
    # For more information: https://cloud.google.com/document-ai/docs/enterprise-document-ocr
    process_options = documentai.ProcessOptions(
        ocr_config=documentai.OcrConfig(
            enable_native_pdf_parsing=True,
            enable_image_quality_scores=True,
            enable_symbol=True,
            # OCR Add Ons https://cloud.google.com/document-ai/docs/ocr-add-ons
            premium_features=documentai.OcrConfig.PremiumFeatures(
                compute_style_info=True,
                enable_math_ocr=False,  # Enable to use Math OCR Model
                enable_selection_mark_detection=True,
            ),
        )
    )
    # Online processing request to Document AI
    document = process_document(
        project_id,
        location,
        processor_id,
        processor_version,
        file_path,
        mime_type,
        process_options=process_options,
    )

    text = document.text
    print(f"Full document text: {text}\n")
    print(f"There are {len(document.pages)} page(s) in this document.\n")

    for page in document.pages:
        print(f"Page {page.page_number}:")
        print_page_dimensions(page.dimension)
        print_detected_languages(page.detected_languages)

        print_blocks(page.blocks, text)
        print_paragraphs(page.paragraphs, text)
        print_lines(page.lines, text)
        print_tokens(page.tokens, text)

        if page.symbols:
            print_symbols(page.symbols, text)

        if page.image_quality_scores:
            print_image_quality_scores(page.image_quality_scores)

        if page.visual_elements:
            print_visual_elements(page.visual_elements, text)


def print_page_dimensions(dimension: documentai.Document.Page.Dimension) -> None:
    print(f"    Width: {str(dimension.width)}")
    print(f"    Height: {str(dimension.height)}")


def print_detected_languages(
    detected_languages: Sequence[documentai.Document.Page.DetectedLanguage],
) -> None:
    print("    Detected languages:")
    for lang in detected_languages:
        print(f"        {lang.language_code} ({lang.confidence:.1%} confidence)")


def print_blocks(blocks: Sequence[documentai.Document.Page.Block], text: str) -> None:
    print(f"    {len(blocks)} blocks detected:")
    first_block_text = layout_to_text(blocks[0].layout, text)
    print(f"        First text block: {repr(first_block_text)}")
    last_block_text = layout_to_text(blocks[-1].layout, text)
    print(f"        Last text block: {repr(last_block_text)}")


def print_paragraphs(
    paragraphs: Sequence[documentai.Document.Page.Paragraph], text: str
) -> None:
    print(f"    {len(paragraphs)} paragraphs detected:")
    first_paragraph_text = layout_to_text(paragraphs[0].layout, text)
    print(f"        First paragraph text: {repr(first_paragraph_text)}")
    last_paragraph_text = layout_to_text(paragraphs[-1].layout, text)
    print(f"        Last paragraph text: {repr(last_paragraph_text)}")


def print_lines(lines: Sequence[documentai.Document.Page.Line], text: str) -> None:
    print(f"    {len(lines)} lines detected:")
    first_line_text = layout_to_text(lines[0].layout, text)
    print(f"        First line text: {repr(first_line_text)}")
    last_line_text = layout_to_text(lines[-1].layout, text)
    print(f"        Last line text: {repr(last_line_text)}")


def print_tokens(tokens: Sequence[documentai.Document.Page.Token], text: str) -> None:
    print(f"    {len(tokens)} tokens detected:")
    first_token_text = layout_to_text(tokens[0].layout, text)
    first_token_break_type = tokens[0].detected_break.type_.name
    print(f"        First token text: {repr(first_token_text)}")
    print(f"        First token break type: {repr(first_token_break_type)}")
    if tokens[0].style_info:
        print_style_info(tokens[0].style_info)

    last_token_text = layout_to_text(tokens[-1].layout, text)
    last_token_break_type = tokens[-1].detected_break.type_.name
    print(f"        Last token text: {repr(last_token_text)}")
    print(f"        Last token break type: {repr(last_token_break_type)}")
    if tokens[-1].style_info:
        print_style_info(tokens[-1].style_info)


def print_symbols(
    symbols: Sequence[documentai.Document.Page.Symbol], text: str
) -> None:
    print(f"    {len(symbols)} symbols detected:")
    first_symbol_text = layout_to_text(symbols[0].layout, text)
    print(f"        First symbol text: {repr(first_symbol_text)}")
    last_symbol_text = layout_to_text(symbols[-1].layout, text)
    print(f"        Last symbol text: {repr(last_symbol_text)}")


def print_image_quality_scores(
    image_quality_scores: documentai.Document.Page.ImageQualityScores,
) -> None:
    print(f"    Quality score: {image_quality_scores.quality_score:.1%}")
    print("    Detected defects:")

    for detected_defect in image_quality_scores.detected_defects:
        print(f"        {detected_defect.type_}: {detected_defect.confidence:.1%}")


def print_style_info(style_info: documentai.Document.Page.Token.StyleInfo) -> None:
    """
    Only supported in version `pretrained-ocr-v2.0-2023-06-02`
    """
    print(f"           Font Size: {style_info.font_size}pt")
    print(f"           Font Type: {style_info.font_type}")
    print(f"           Bold: {style_info.bold}")
    print(f"           Italic: {style_info.italic}")
    print(f"           Underlined: {style_info.underlined}")
    print(f"           Handwritten: {style_info.handwritten}")
    print(
        f"           Text Color (RGBa): {style_info.text_color.red}, {style_info.text_color.green}, {style_info.text_color.blue}, {style_info.text_color.alpha}"
    )


def print_visual_elements(
    visual_elements: Sequence[documentai.Document.Page.VisualElement], text: str
) -> None:
    """
    Only supported in version `pretrained-ocr-v2.0-2023-06-02`
    """
    checkboxes = [x for x in visual_elements if "checkbox" in x.type]
    math_symbols = [x for x in visual_elements if x.type == "math_formula"]

    if checkboxes:
        print(f"    {len(checkboxes)} checkboxes detected:")
        print(f"        First checkbox: {repr(checkboxes[0].type)}")
        print(f"        Last checkbox: {repr(checkboxes[-1].type)}")

    if math_symbols:
        print(f"    {len(math_symbols)} math symbols detected:")
        first_math_symbol_text = layout_to_text(math_symbols[0].layout, text)
        print(f"        First math symbol: {repr(first_math_symbol_text)}")




def process_document(
    project_id: str,
    location: str,
    processor_id: str,
    processor_version: str,
    file_path: str,
    mime_type: str,
    process_options: Optional[documentai.ProcessOptions] = None,
) -> documentai.Document:
    # You must set the `api_endpoint` if you use a location other than "us".
    client = documentai.DocumentProcessorServiceClient(
        client_options=ClientOptions(
            api_endpoint=f"{location}-documentai.googleapis.com"
        )
    )

    # The full resource name of the processor version, e.g.:
    # `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}`
    # You must create a processor before running this sample.
    name = client.processor_version_path(
        project_id, location, processor_id, processor_version
    )

    # Read the file into memory
    with open(file_path, "rb") as image:
        image_content = image.read()

    # Configure the process request
    request = documentai.ProcessRequest(
        name=name,
        raw_document=documentai.RawDocument(content=image_content, mime_type=mime_type),
        # Only supported for Document OCR processor
        process_options=process_options,
    )

    result = client.process_document(request=request)

    # For a full list of `Document` object attributes, reference this page:
    # https://cloud.google.com/document-ai/docs/reference/rest/v1/Document
    return result.document




def layout_to_text(layout: documentai.Document.Page.Layout, text: str) -> str:
    """
    Document AI identifies text in different parts of the document by their
    offsets in the entirety of the document"s text. This function converts
    offsets to a string.
    """
    # If a text segment spans several lines, it will
    # be stored in different text segments.
    return "".join(
        text[int(segment.start_index) : int(segment.end_index)]
        for segment in layout.text_anchor.text_segments
    )

次のステップ