arrow_back

透過 Document AI API 使用 Python 處理文件

登录 加入
Get access to 700+ labs and courses

透過 Document AI API 使用 Python 處理文件

实验 1 小时 universal_currency_alt 1 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
Get access to 700+ labs and courses

GSP925

總覽

Document AI API 是一項文件解讀解決方案,可擷取文件和電子郵件等非結構化資料,讓您更輕鬆地解讀、分析和使用這些資料。

在本實驗室中,您將結合 Document AI API 和 Python 來建立各種處理器 (包括一般表單處理器和文件 OCR 處理器),然後透過 Python 對 API 發出同步或非同步呼叫。本實驗室已為您建立 Vertex AI Workbench 執行個體,供您搭配 JupyterLab 筆記本使用 Document AI Python 用戶端模組。

目標

本實驗室的學習內容包括:

  • 啟用 Document AI API 並建立處理器。
  • 在 Vertex AI Workbench 執行個體安裝 Python 用戶端程式庫。
  • 使用 Python 剖析表單掃描檔中的資料,以便發出同步 API 呼叫。
  • 使用 Python 剖析表單掃描檔中的資料,以便發出非同步 API 呼叫。

設定和需求

瞭解以下事項後,再點選「Start Lab」按鈕

請詳閱以下操作說明。實驗室活動會計時,且中途無法暫停。點選「Start Lab」後就會開始計時,顯示可使用 Google Cloud 資源的時間。

您將在真正的雲端環境完成實作實驗室活動,而不是模擬或示範環境。為此,我們會提供新的暫時憑證,供您在實驗室活動期間登入及存取 Google Cloud。

為了順利完成這個實驗室,請先確認:

  • 可以使用標準的網際網路瀏覽器 (Chrome 瀏覽器為佳)。
注意事項:請使用無痕模式 (建議選項) 或私密瀏覽視窗執行此實驗室,這可以防止個人帳戶和學員帳戶之間的衝突,避免個人帳戶產生額外費用。
  • 是時候完成實驗室活動了!別忘了,活動一旦開始將無法暫停。
注意事項:務必使用實驗室專用的學員帳戶。如果使用其他 Google Cloud 帳戶,可能會產生額外費用。

啟動 Cloud Shell

Cloud Shell 是搭載多項開發工具的虛擬機器,提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作。Cloud Shell 提供指令列存取權,方便您使用 Google Cloud 資源。

  1. 點按 Google Cloud 控制台頂端的「啟用 Cloud Shell」圖示

  2. 系統顯示視窗時,請按照下列步驟操作:

    • 繼續操作 Cloud Shell 視窗。
    • 授權 Cloud Shell 使用您的憑證發出 Google Cloud API 呼叫。

連線建立完成即代表已通過驗證,而且專案已設為您的 Project_ID。輸出內容中有一行文字,宣告本工作階段的 Project_ID

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud 是 Google Cloud 的指令列工具,已預先安裝於 Cloud Shell,並支援 Tab 鍵自動完成功能。

  1. (選用) 您可以執行下列指令來列出使用中的帳戶:
gcloud auth list
  1. 點按「授權」

輸出內容:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (選用) 您可以使用下列指令來列出專案 ID:
gcloud config list project

輸出內容:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} 注意:如需 gcloud 的完整說明,請前往 Google Cloud 參閱 gcloud CLI 總覽指南

工作 1:建立及測試一般表單處理器

在這項工作中,您將啟用 Document AI API,然後建立及測試一般表單處理器。一般表單處理器能處理任何類型的文件,並將文件中可辨識的所有文字內容擷取出來。這類處理器支援數種語言,不僅能處理印刷、手寫和以任意方向書寫的文字,還可解讀各項表單資料元素間的關係,協助您針對加上文字標籤的表單欄位擷取鍵/值組合。

啟用 Cloud Document AI API

您必須先啟用 API,才能使用 Document AI。

  1. 前往 Cloud 控制台,依序點按「導覽選單」圖示 >「API 和服務」>「程式庫」

  2. 搜尋「Cloud Document AI API」,然後點按「啟用」按鈕,即可在 Google Cloud 專案中使用這個 API。

如果先前已啟用 Cloud Document AI API,畫面上會顯示「管理」按鈕,表示您可繼續完成後續的實驗室活動。

確認 Cloud Document AI API 已啟用。

建立一般表單處理器

請使用 Document AI 表單剖析器建立 Document AI 處理器。

  1. 前往控制台,依序點按「導覽選單」圖示 >「Document AI」>「總覽」

  2. 點按「Explore processor」並選取「Form Parser」,這屬於一般處理器的一種。

  3. 將處理器名稱設為 form-parser,然後從清單中選取「US (美國)」

  4. 點按「建立」,即可建立 form-parser 處理器。

系統隨即會建立處理器,並傳回處理器詳細資料頁面,當中會顯示處理器 ID、狀態和預測端點。

  1. 記下處理器 ID,後續工作需使用這個 ID 來更新 JupyterLab 筆記本中的變數。

工作 2:設定 Vertex AI Workbench 執行個體,以便執行 Document AI API 呼叫

接下來,您會連線至 Vertex AI Workbench 執行個體 (已在實驗室啟動時自動建立) 中運作的 JupyterLab,然後設定環境,方便進行其餘的實驗室工作。

  1. 前往 Google Cloud 控制台,依序點按「導覽選單」圖示 >「Vertex AI」>「Workbench」

  2. 找出 執行個體,點按「Open JupyterLab」按鈕。

Workbench 執行個體的 JupyterLab 介面會在新瀏覽器分頁中開啟。

  1. 點按「終端機」,在 Vertex AI Workbench 執行個體中開啟終端機殼層。

  2. 在終端機殼層輸入下列指令,將實驗室檔案匯入 Vertex AI Workbench 執行個體:

gsutil cp {{{project_0.startup_script.notebook_files_path|notebook_files_path}}} .
  1. 在終端機殼層輸入下列指令,安裝 Document AI 需要用到的 Python 用戶端程式庫和其他必要程式庫:
python -m pip install --upgrade google-cloud-core google-cloud-documentai google-cloud-storage prettytable

輸出內容應該會指出程式庫已安裝成功。

注意:如果發生權限相關錯誤,請重新執行指令,確保程式庫安裝成功。權限會在幾分鐘內套用完成。
  1. 在終端機殼層輸入下列指令,匯入範例健康資料登記表:
gsutil cp {{{project_0.startup_script.health_intake_form_path|form_path}}} form.pdf
  1. 在筆記本介面中,開啟 JupyterLab 筆記本

  2. 出現「Select Kernel」對話方塊時,從可用核心清單中選取「Python 3」

確認 Vertex AI 執行個體已準備就緒,可執行同步 Document AI API 呼叫。

工作 3:發出同步處理文件要求

您需要透過同步 Document AI API 呼叫,發出處理文件的要求。如要一次處理大量文件,也可使用非同步 API,後續工作也會用到這個 API。

檢查用來發出同步 Document AI API 呼叫的 Python 程式碼

請花點時間檢查 筆記本中的 Python 程式碼。

第一個程式碼區塊會匯出必要的程式庫,並初始化某些變數。

from google.cloud import documentai_v1beta3 as documentai from google.cloud import storage from prettytable import PrettyTable project_id = %system gcloud config get-value core/project project_id = project_id[0] location = 'us' file_path = 'form.pdf'

「Set your Processor ID」程式碼儲存格的作用是設定處理器 ID。您必須先手動完成這項設定,才能使用筆記本處理文件。

processor_id = 'PROCESSOR_ID' # TODO: Replace with a valid Processor ID

在這個步驟中,請使用工作 1 建立的 Document AI 處理器 ID。

提示:若未記下處理器 ID,請前往 Cloud 控制台分頁,依序點按「導覽選單」圖示 >「Document AI」>「我的處理器」,然後按一下處理器名稱來開啟詳細資料頁面。您可以在隨即顯示的頁面中複製處理器 ID。

「Process Document Function」程式碼儲存格會定義 process_document 函式,用來對 Document AI 處理器發出同步呼叫。這個函式會建立 Document AI API 用戶端物件。

您可以使用 project_idlocationsprocessor_id 參數建立 API 呼叫需要的處理器名稱,並以 mime_type 結構來讀取和儲存範例 PDF 文件。

這個函式會建立含有完整文件處理器名稱的要求物件,並將這個物件做為參數,對 Document AI API 用戶端發出同步呼叫。成功送出要求後,處理器將傳回文件物件,當中提供的屬性包含表單內偵測到的實體。

def process_document( project_id=project_id, location=location, processor_id=processor_id, file_path=file_path ): # Instantiates a client client = documentai.DocumentProcessorServiceClient() # 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 name = f"projects/{project_id}/locations/{location}/processors/{processor_id}" with open(file_path, "rb") as image: image_content = image.read() # Read the file into memory document = {"content": image_content, "mime_type": "application/pdf"} # Configure the process request request = {"name": name, "document": document} # Use the Document AI client to process the sample form result = client.process_document(request=request) return result.document

「Process Document」程式碼儲存格會呼叫 process_document 函式,將回應儲存在 document 變數中,然後顯示偵測到的原始文字。所有處理器都會傳回 document.text 屬性的部分資料。

document=process_document() # print all detected text. # All document processors will display the text content print("Document processing complete.") print("Text: {}".format(document.text))

「Get Text Function」程式碼儲存格會定義 get_text() 函式,使用具名元素 text_segmentstext_anchorstart_indexend_index 屬性,擷取具名元素的文字。如果處理器傳回表單資料,就能使用這個函式來擷取這類資料的表單名稱和值。

def get_text(doc_element: dict, document: dict): """ Document AI identifies form fields by their offsets in document text. This function converts offsets to text snippets. """ response = "" # If a text segment spans several lines, it will # be stored in different text segments. for segment in doc_element.text_anchor.text_segments: start_index = ( int(segment.start_index) if segment in doc_element.text_anchor.text_segments else 0 ) end_index = int(segment.end_index) response += document.text[start_index:end_index] return response

「Display Form Data」儲存格會逐一分析偵測到的所有頁面,並對偵測到的每個 form_field 使用 get_text() 函式,用來擷取欄位名稱和值。接著,處理器會顯示這些值和對應的可信度分數。如果處理器是使用一般表單剖析器或專用剖析器,就會傳回表單資料,而透過文件 OCR 剖析器建立的處理器則不會。

document_pages = document.pages print("Form data detected:\n") # For each page fetch each form field and display fieldname, value and confidence scores for page in document_pages: print("Page Number:{}".format(page.page_number)) for form_field in page.form_fields: fieldName=get_text(form_field.field_name,document) nameConfidence = round(form_field.field_name.confidence,4) fieldValue = get_text(form_field.field_value,document) valueConfidence = round(form_field.field_value.confidence,4) print(fieldName+fieldValue +" (Confidence Scores: (Name) "+str(nameConfidence)+", (Value) "+str(valueConfidence)+")\n")

「Display Entity Data」儲存格會擷取文件物件中的實體資料,然後分析偵測到的每個實體,並顯示實體類型、值和可信度屬性。請注意,「只有」使用專用 Document AI 剖析器 (例如採購費用剖析器) 的處理器,才會傳回實體資料。一般表單剖析器和文件 OCR 剖析器不會傳回實體資料。

if 'entities' in dir(document): entities = document.entities # Grab each key/value pair and their confidence scores. table = PrettyTable(['Type', 'Value', 'Confidence']) for entity in entities: entity_type = entity.type_ value = entity.mention_text confience = round(entity.confidence,4) table.add_row([entity_type, value, confience]) print(table) else: print("Document does not contain entity data.")

工作 4:執行同步 Document AI Python 程式碼

請在 JupyterLab 筆記本中執行程式碼,對 Document AI API 發出同步呼叫。

  1. 在第二個「Set your Processor ID」程式碼儲存格中,將 PROCESSOR_ID 預留位置文字換成您在前述步驟建立的 form-parser 處理器 ID。

  2. 選取第一個儲存格,依序點按「Run」選單和「Run Selected Cell and All Below」,即可執行筆記本中的所有程式碼。

如果您已使用範例健康資料登記表,就會在輸出內容儲存格中,看見類似下方的表單資料:

Form data detected: Page Number:1 Phone #: (906) 917-3486 (Confidence Scores: (Name) 1.0, (Value) 1.0) ... Date: 9/14/19 (Confidence Scores: (Name) 0.9999, (Value) 0.9999) ... Name: Sally Walker (Confidence Scores: (Name) 0.9973, (Value) 0.9973) ...

若您能建立專用處理器,最後一個儲存格會顯示實體資料,否則儲存格將顯示空白資料表。

  1. 在 JupyterLab 選單中,依序點按「File」和「Save Notebook」,儲存目前工作進度。
確認已使用同步 Cloud Document API 處理文件。

工作 5:建立採用文件 OCR 的 Document AI 處理器

在這項工作中,您將使用一般文件 OCR 剖析器,建立 Document AI 處理器。

  1. 在「導覽選單」中,依序點按「Document AI」和「總覽」

  2. 點按「Explore processor」後,找到「Document OCR」並點按「建立處理器」,這屬於一般處理器的一種。

  3. 將處理器名稱設為 ocr-processor,然後從清單中選取「US (美國)」

  4. 點按「建立」即可建立處理器。

  5. 記下處理器 ID,後續工作需要指定這個值。

工作 6:準備非同步 Document AI API 呼叫的使用環境

在這項工作中,您會上傳範例 JupyterLab 筆記本,以便測試非同步 Document AI API 呼叫,並將實驗室的部分範例表單複製到 Cloud Storage,開始進行非同步處理作業。

  1. 點按「終端機」分頁標籤,在 Vertex AI Workbench 執行個體中重新開啟終端機殼層。

  2. 建立輸入文件專用的 Cloud Storage bucket,然後將範例 W2 表單複製到該 bucket:

export PROJECT_ID="$(gcloud config get-value core/project)" export BUCKET="${PROJECT_ID}"_doc_ai_async gsutil mb gs://${BUCKET} gsutil -m cp {{{project_0.startup_script.async_files_path|async_files_path}}} gs://${BUCKET}/input
  1. 在筆記本介面中,開啟 JupyterLab 筆記本

  2. 出現「Select Kernel」對話方塊時,從可用核心清單中選取「Python 3」

確認 Vertex AI 執行個體已準備就緒,可執行非同步 Document AI API 呼叫。

工作 7:發出非同步處理文件要求

檢查用來發出非同步 Document AI API 呼叫的 Python 程式碼

請花點時間檢查 筆記本中的 Python 程式碼。

第一個程式碼儲存格會匯出必要的程式庫。

from google.cloud import documentai_v1beta3 as documentai from google.cloud import storage import re import os import pandas as pd import simplejson as json

「Set your Processor ID」程式碼儲存格的作用是設定處理器 ID。您必須先手動完成這項設定,才能使用筆記本處理文件。

processor_id = "PROCESSOR_ID" # TODO: Replace with a valid Processor ID

「Set your variables」程式碼儲存格會定義用來發出非同步呼叫的參數,包括輸入/輸出內容 Cloud Storage bucket 的位置,這些 bucket 將用於來源資料和輸出檔案。執行程式碼前,請先更新這個儲存格中的 PROJECT_ID 預留位置值,並在實驗室的下一個部分,更改 PROCESSOR_ID 的預留位置值。其他變數包含處理器位置和輸出/輸入內容 Cloud Storage bucket 的預設值,對此您不需要進行任何調整。

project_id = %system gcloud config get-value core/project project_id = project_id[0] location = 'us' # Replace with 'eu' if processor does not use 'us' location gcs_input_bucket = project_id+"_doc_ai_async" # Bucket name only, no gs:// prefix gcs_input_prefix = "input/" # Input bucket folder e.g. input/ gcs_output_bucket = project_id+"_doc_ai_async" # Bucket name only, no gs:// prefix gcs_output_prefix = "output/" # Input bucket folder e.g. output/ timeout = 300

「Define Google Cloud client objects」程式碼儲存格會初始化 Document AI 和 Cloud Storage 用戶端。

client_options = {"api_endpoint": "{}-documentai.googleapis.com".format(location)} client = documentai.DocumentProcessorServiceClient(client_options=client_options) storage_client = storage.Client()

「Create input configuration」程式碼儲存格會建立來源資料的輸入設定陣列參數,並將這項參數傳遞至非同步 Document AI 要求,做為輸入設定。處理器會找出輸入內容 Cloud Storage 位置中的檔案,然後將個別檔案的 Cloud Storage 來源位置和 MIME 類型儲存至這個陣列。

blobs = storage_client.list_blobs(gcs_input_bucket, prefix=gcs_input_prefix) input_configs = [] print("Input Files:") for blob in blobs: if ".pdf" in blob.name: source = "gs://{bucket}/{name}".format(bucket = gcs_input_bucket, name = blob.name) print(source) input_config = documentai.types.document_processor_service.BatchProcessRequest.BatchInputConfig( gcs_source=source, mime_type="application/pdf" ) input_configs.append(input_config)

「Create output configuration」程式碼儲存格會建立非同步要求的輸出參數 (當中包含輸出內容 Cloud Storage bucket 位置),然後將這項參數儲存為 Document AI 批次輸出設定。

destination_uri = f"gs://{gcs_output_bucket}/{gcs_output_prefix}" output_config = documentai.types.document_processor_service.BatchProcessRequest.BatchOutputConfig( gcs_destination=destination_uri )

「Create the Document AI API request」程式碼儲存格會使用輸入和輸出設定物件,建立非同步 Document AI 批次處理要求物件。

name = f"projects/{project_id}/locations/{location}/processors/{processor_id}" request = documentai.types.document_processor_service.BatchProcessRequest( name=name, input_configs=input_configs, output_config=output_config, )

「Start the batch (asynchronous) API operation」程式碼儲存格會將要求物件傳遞至 batch_process_documents() 方法,以便發出非同步文件處理要求。由於執行的是非同步呼叫,您需要使用 result() 方法,強制筆記本等待背景中的所有非同步工作完成。

operation = client.batch_process_documents(request) # Wait for the operation to finish operation.result(timeout=timeout) print ("Batch process completed.")

「Fetch list of output files」儲存格會根據 destination_uri 變數的定義,列舉輸出內容 bucket 位置中的物件。

「Display detected text from asynchronous output JSON files」儲存格的作用,是載入歸類為 Document AI 文件物件的每個輸出 JSON 檔案,並顯示文件 OCR 處理器偵測到的文字資料。

「Display entity data」儲存格會顯示找到的實體資料,但請注意,只有透過專用剖析器建立的處理器,才能顯示這類資料。這項工作採用一般 Document AI OCR 剖析器,因此不會顯示實體資料。

執行非同步 Document AI Python 程式碼

請使用 Jupyterlab 筆記本提供的程式碼範例,透過 Document AI 批次處理要求,以非同步方式處理文件。

  1. 在第二個程式碼儲存格中,將 PROCESSOR_ID 預留位置文字換成您在前述步驟建立的 form-parser 處理器 ID。

  2. 選取第一個儲存格,依序點按「Run」選單和「Run Selected Cell and All Below」,即可執行筆記本中的所有程式碼。

  3. 程式碼儲存格執行期間,您可以逐步檢查筆記本中的程式碼和註解,瞭解非同步要求物件的建立和使用方式。

根據「Start the batch (asynchronous) API operation」程式碼儲存格的定義,筆記本會等待一到兩分鐘,確定非同步批次處理作業已完成。批次處理 API 呼叫屬於非同步性質,因此筆記本會使用 result 方法,強制筆記本等到非同步呼叫完成,再列舉及顯示輸出資料。

如果非同步工作因耗費過多時間而逾時,您可以重新執行其餘的儲存格,也就是「Start the batch (asynchronous) API operation」儲存格後的所有儲存格,以便顯示輸出內容。

輸出內容會包含文字說明,列出每個檔案中偵測到的 Document AI 資料。由於文件 OCR 剖析器無法偵測表單或實體資料,處理器不會顯示這類內容。若您能建立專用處理器,最後一個儲存格也會顯示實體資料。

  1. 在 JupyterLab 選單中,依序點按「File」和「Save Notebook」,儲存目前工作進度。
Document processing complete. Text: FakeDoc M.D. HEALTH INTAKE FORM Please fill out the questionnaire carefully. The information you provide will be used to complete your health profile and will be kept confidential. Date: Sally Walker Name: 9/14/19 ... 確認已使用非同步 Cloud Document API 處理文件。

恭喜

您已成功對 Document AI API 發出同步和非同步呼叫。在本實驗室中,您學到許多實用知識,包括啟用 Document AI API 並建立處理器;在 Vertex AI Workbench 執行個體安裝 Python 用戶端程式庫;使用 Python 剖析表單掃描檔中的資料,以便發出同步 API 呼叫;使用 Python 剖析表單掃描檔中的資料,以便發出非同步 API 呼叫。

完成任務

這個自學實驗室屬於「Detect Manufacturing Defects using Visual Inspection AI」技能徽章任務的一部分。「任務」是指一系列相關的實驗室課程,這些課程構成完整的學習路徑。完成這項任務後即可獲得徽章,表彰您的成就。您可以在履歷表和社群平台張貼徽章,並加上 #GoogleCloudBadge 公開這項成就。徽章可公開展示,也能連結至您的線上履歷或社群媒體帳戶。如已參加過這個實驗室,歡迎報名任務並立即取得完成學分,或查看其他可開始進行的任務

後續步驟/瞭解詳情

  • 如要進一步瞭解如何使用 Document AI API,請參閱這份指南

Google Cloud 教育訓練與認證

協助您瞭解如何充分運用 Google Cloud 的技術。我們的課程會介紹專業技能和最佳做法,讓您可以快速掌握要領並持續進修。我們提供從基本到進階等級的訓練課程,並有隨選、線上和虛擬課程等選項,方便您抽空參加。認證可協助您驗證及證明自己在 Google Cloud 技術方面的技能和專業知識。

使用手冊上次更新日期:2024 年 10 月 8 日

實驗室上次測試日期:2024 年 10 月 8 日

Copyright 2025 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.