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 文字偵測 全球可用的 REST API,以 Google Cloud 標準 OCR 模型為基礎。預設配額為每分鐘 1,800 項要求。 需要低延遲和高容量的一般文字擷取用途。
Cloud Vision OCR Google Distributed Cloud (已淘汰) Google Cloud Marketplace 應用程式,可使用 GKE Enterprise 部署至任何 GKE 叢集,並當做容器使用。 符合資料落地或法規遵循要求。

偵測和擷取

Enterprise Document OCR 可偵測 PDF 和圖片中的區塊、段落、行、字詞和符號,並修正文件的傾斜角度,提高準確度。

支援的版面配置偵測和擷取屬性:

印刷文字 手寫 段落 封鎖 Line Word 符號層級 頁碼
預設 預設 預設 預設 預設 預設 可自行設定 預設

可設定的 Enterprise Document OCR 功能包括:

  • 從數位 PDF 檔案中擷取內嵌或原生文字:這項功能會依照原始文件中的文字和符號擷取文字和符號,即使是旋轉的文字、極端的字型大小或樣式,以及部分隱藏的文字,也能正常擷取。

  • 旋轉修正:使用 Enterprise Document OCR 對文件圖片進行預處理,修正可能影響擷取品質或處理作業的旋轉問題。

  • 圖片品質分數:接收可協助文件轉送的品質指標。圖片品質分數會提供八個面向的網頁層級品質指標,包括模糊、字型比平常小和眩光。

  • 指定頁面範圍:指定輸入文件中供光學字元辨識使用的頁面範圍。這樣一來,您就能節省在不需要的頁面上花費的時間和處理時間。

  • 語言偵測:偵測擷取文字所使用的語言。

  • 語言和手寫提示:根據資料集已知特徵,為 OCR 模型提供語言或手寫提示,以提升準確度。

如要瞭解如何啟用光學字元辨識設定,請參閱「啟用光學字元辨識設定」。

OCR 附加元件

Enterprise Document OCR 提供選用的分析功能,可視需要為個別處理要求啟用。

下列外掛程式功能適用於穩定版 pretrained-ocr-v2.0-2023-06-02pretrained-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 也支援 DocX 檔案,同步時最多可處理 15 頁,非同步時則可處理 30 頁。DocX 支援功能目前為不公開預先發布版。如要申請存取權,請提交 DocX 支援要求表單

進階版本管理

進階版本管理功能目前為預先發布版。升級基礎 AI/ML OCR 模型可能會導致 OCR 行為有所變更。如果需要嚴格一致性,請使用已凍結的模型版本,將行為固定為最多 18 個月的舊版 OCR 模型。這可確保相同的圖片與 OCR 函式結果。請參閱處理器版本相關表格。

處理器版本

下列處理器版本與這項功能相容。詳情請參閱「管理處理器版本」。

版本 ID 發布版本 說明
pretrained-ocr-v1.2-2022-11-10 穩定 已凍結的 v1.0 模型版本:容器映像檔中凍結的版本快照模型檔案、設定和二進位檔,最多可保留 18 個月。
pretrained-ocr-v2.0-2023-06-02 穩定 專為文件用途設計的實際工作環境模型。包含所有 OCR 外掛程式的存取權。
pretrained-ocr-v2.1-2024-08-07 穩定 2.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 設定,請在 ProcessDocumentRequestBatchProcessDocumentsRequestProcessOptions.ocrConfig 中設定相應欄位。

    詳情請參閱「傳送處理要求」。

    圖片品質分析

    智慧型文件品質分析功能會運用機器學習技術,根據內容的可讀性評估文件品質。系統會以品質分數 [0, 1] 傳回這項品質評估結果,其中 1 代表完美品質。如果偵測到的品質分數低於 0.5,系統也會傳回品質不佳的原因清單 (按可能性排序)。大於 0.5 的可能性會視為偵測到陽性。

    如果系統判定文件有瑕疵,API 會傳回下列八種文件瑕疵類型:

    • 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 模型。如果有非數位文字,系統會自動使用光學字元辨識模型。使用者會收到合併後的文字結果。

    輸入

    如要啟用,請在處理要求中將 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
          }
        }
      }
    

    舊版版面配置

    如果您需要採用啟發式版面配置偵測演算法,可以啟用舊版版面配置,做為目前以機器學習為基礎的版面配置偵測演算法的替代方案。這不是建議的設定。客戶可以根據文件工作流程選擇最合適的版面配置演算法。

    輸入

    如要啟用,請在處理要求中將 ProcessOptions.ocrConfig.advancedOcrOptions 設為 ["legacy_layout"]

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

    指定頁面範圍

    根據預設,OCR 會從文件的所有頁面中擷取文字和版面配置資訊。您可以選取特定頁碼或頁面範圍,只擷取這些頁面的文字。

    您可以透過三種方式在 ProcessOptions 中設定這項功能:

    • 如要只處理第二和第五頁,請按照下列步驟操作:
      {
        "individualPageSelector": {"pages": [2, 5]}
      }
    
    • 如要只處理前三個網頁,請按照下列步驟操作:
      {
        "fromStart": 3
      }
    
    • 如要只處理最後四頁:
      {
        "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.enableMathOcr 設為 true

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

    輸出

    數學 OCR 輸出內容會顯示在 Document.pages[].visualElements[] 中,並以 "type": "math_formula" 為單位。

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

    輸出

    勾選方塊輸出內容會顯示在 Document.pages[].visualElements[] 中,並搭配 "type": "unfilled_checkbox""type": "filled_checkbox"

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

    輸出

    字型樣式輸出內容會以 StyleInfo 類型的 Document.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 工具箱包含可將 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:光學字元辨識功能使用的 BCP-47 語言代碼清單。
      • ADVANCED_OCR_OPTIONS:進階 OCR 選項清單,可進一步微調 OCR 行為。目前有效的值如下:
        • legacy_layout:啟發式版面配置偵測演算法,可取代目前的機器學習版面配置偵測演算法。
    • 付費 OCR 外掛程式
      • ENABLE_SELECTION_MARK_DETECTION:(布林值) 啟用 OCR 引擎的選取標記偵測工具。
      • COMPUTE_STYLE_INFO (布林值) 啟用字型識別模型,並傳回字型樣式資訊。
      • ENABLE_MATH_OCR:(布林值) 啟用可擷取 LaTeX 數學公式的模型。
    • INDIVIDUAL_PAGES:要處理的個別網頁清單。
      • 或者,您也可以提供 fromStartfromEnd 欄位,從文件開頭或結尾處處理特定數量的頁面。

    † 您也可以在 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",
      "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
        )
    
    

    後續步驟