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。
在這項工作中,您將啟用 Document AI API,然後建立及測試一般表單處理器。一般表單處理器能處理任何類型的文件,並將文件中可辨識的所有文字內容擷取出來。這類處理器支援數種語言,不僅能處理印刷、手寫和以任意方向書寫的文字,還可解讀各項表單資料元素間的關係,協助您針對加上文字標籤的表單欄位擷取鍵/值組合。
啟用 Cloud Document AI API
您必須先啟用 API,才能使用 Document AI。
前往 Cloud 控制台,依序點按「導覽選單」圖示 >「API 和服務」>「程式庫」。
搜尋「Cloud Document AI API」,然後點按「啟用」按鈕,即可在 Google Cloud 專案中使用這個 API。
如果先前已啟用 Cloud Document AI API,畫面上會顯示「管理」按鈕,表示您可繼續完成後續的實驗室活動。
「Process Document Function」程式碼儲存格會定義 process_document 函式,用來對 Document AI 處理器發出同步呼叫。這個函式會建立 Document AI API 用戶端物件。
您可以使用 project_id、locations 和 processor_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
document=process_document()
# print all detected text.
# All document processors will display the text content
print("Document processing complete.")
print("Text: {}".format(document.text))
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 發出同步呼叫。
在第二個「Set your Processor ID」程式碼儲存格中,將 PROCESSOR_ID 預留位置文字換成您在前述步驟建立的 form-parser 處理器 ID。
選取第一個儲存格,依序點按「Run」選單和「Run Selected Cell and All Below」,即可執行筆記本中的所有程式碼。
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
「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 批次處理要求,以非同步方式處理文件。
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 呼叫。