Enterprise Document OCR

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

概要

Enterprise Document OCR は、アルゴリズムや ML に基づくデータ入力、データ精度の向上と検証などのタスクに使用できます。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(非推奨) GKE Enterprise を使用して任意の GKE クラスタにコンテナとしてデプロイできる Google Cloud Marketplace アプリケーション。 データ所在地またはコンプライアンスの要件を満たすため。

検出と抽出

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 バージョンで利用できます。

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

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

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

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

Enterprise Document OCR は、同期で最大 15 ページ、非同期で最大 30 ページの DocX ファイルもサポートしています。DocX のサポートは限定公開プレビュー版です。アクセスをリクエストするには、DocX サポート リクエスト フォームを送信してください。

高度なバージョニング

高度なバージョニングはプレビュー版です。基盤となる AI/ML OCR モデルのアップグレードにより、OCR の動作が変更されることがあります。厳密な整合性が必要な場合は、フリーズされたモデル バージョンを使用して、動作を最大 18 か月間、以前の OCR モデルに固定します。これにより、同じ画像から 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 と同様で、USEUasia-southeast1 を除くすべてのリージョンで利用できます。

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

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

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Document AI API.

    Enable the API

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

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Document AI API.

    Enable the API

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

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

    OCR 構成

    すべての OCR 構成は、ProcessDocumentRequest または BatchProcessDocumentsRequestProcessOptions.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.enableImageQualityScorestrue に設定して有効にします。この追加機能により、処理のコールへの 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.enableSymboltrue に設定することで有効になります。

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

    出力

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

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

    組み込みの PDF 解析

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

    入力

    処理リクエストで ProcessOptions.ocrConfig.enableNativePdfParsingtrue に設定することで有効になります。

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

    文字の境界ボックス検出

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

    enterprise-document-ocr-1

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

    入力

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

      {
        "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

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

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

    • 画像が検出されました

      enterprise-document-ocr-2

    • LaTeX への変換

      enterprise-document-ocr-3

    入力

    処理リクエストで ProcessOptions.ocrConfig.premiumFeatures.enableMathOcrtrue に設定することで有効になります。

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

    出力

    数式 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.enableSelectionMarkDetectiontrue に設定することで有効になります。

      {
        "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.computeStyleInfotrue に設定することで有効になります。

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

    出力

    font-style 出力は、タイプ StyleInfoDocument.pages[].tokens[].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 のレスポンスとコンバータは、verticesnormalized_vertices の両方に値を入力します。
    • Vision AI API レスポンスは、単語の最後の記号の detected_break を入力します。Document AI API レスポンスとコンバータは、単語と単語の最後の記号の detected_break を入力します。
    • Vision AI API のレスポンスでは、常にシンボル フィールドが入力されます。デフォルトでは、Document AI のレスポンスにシンボル フィールドは入力されません。Document AI のレスポンスとコンバータでシンボル フィールドが入力されるようにするには、enable_symbol 機能を詳細に設定します。

    コードサンプル

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

    REST

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

    • 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
    • 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
        )
    
    

    次のステップ