1. บทนำ
ใน Codelab นี้ คุณจะได้เรียนรู้วิธีใช้โปรแกรมแยกวิเคราะห์แบบฟอร์ม Document AI เพื่อแยกวิเคราะห์แบบฟอร์มที่เขียนด้วยลายมือด้วย Python
เราจะใช้แบบฟอร์มการรับผู้ป่วยง่ายๆ เป็นตัวอย่าง แต่ขั้นตอนนี้จะใช้ได้กับแบบฟอร์มทั่วไปที่ DocAI รองรับ
ข้อกำหนดเบื้องต้น
Codelab นี้สร้างขึ้นจากเนื้อหาที่นำเสนอใน Codelab อื่นๆ ของ Document AI
เราขอแนะนำให้คุณทำ Codelab ต่อไปนี้ให้เสร็จก่อนดำเนินการต่อ
สิ่งที่คุณจะได้เรียนรู้
- วิธีแยกวิเคราะห์และดึงข้อมูลจากแบบฟอร์มที่สแกนโดยใช้เครื่องมือแยกวิเคราะห์แบบฟอร์มของ Document AI
สิ่งที่ต้องมี
แบบสำรวจ
คุณจะใช้บทแนะนำนี้อย่างไร
คุณจะให้คะแนนประสบการณ์การใช้งาน Python เท่าใด
คุณจะให้คะแนนประสบการณ์การใช้บริการ Google Cloud เท่าใด
2. การตั้งค่าและข้อกำหนด
Codelab นี้ถือว่าคุณได้ทำตามขั้นตอนการตั้งค่า Document AI ที่ระบุไว้ใน Codelab ของ Document AI OCR แล้ว
โปรดทำตามขั้นตอนต่อไปนี้ก่อนดำเนินการต่อ
นอกจากนี้ คุณจะต้องติดตั้ง Pandas ซึ่งเป็นไลบรารีการวิเคราะห์ข้อมูลแบบโอเพนซอร์สสำหรับ Python ด้วย
pip3 install --upgrade pandas
3. สร้างโปรเซสเซอร์เครื่องมือแยกวิเคราะห์แบบฟอร์ม
คุณต้องสร้างอินสแตนซ์โปรเซสเซอร์ Form Parser ก่อนเพื่อใช้ใน Document AI Platform สำหรับบทแนะนำนี้
- ในคอนโซล ให้ไปที่ภาพรวมแพลตฟอร์ม Document AI
- คลิกสร้างโปรเซสเซอร์ แล้วเลือกโปรแกรมแยกวิเคราะห์แบบฟอร์ม

- ระบุชื่อโปรเซสเซอร์และเลือกภูมิภาคของคุณจากรายการ
- คลิกสร้างเพื่อสร้างโปรเซสเซอร์
- คัดลอกรหัสกระบวนการ คุณต้องใช้รหัสนี้ในโค้ดในภายหลัง
ทดสอบโปรเซสเซอร์ใน Cloud Console
คุณสามารถทดสอบโปรเซสเซอร์ในคอนโซลได้โดยการอัปโหลดเอกสาร คลิกอัปโหลดเอกสาร แล้วเลือกแบบฟอร์มที่จะแยกวิเคราะห์ คุณดาวน์โหลดและใช้แบบฟอร์มตัวอย่างนี้ได้หากไม่มีแบบฟอร์มที่พร้อมใช้งาน

เอาต์พุตควรมีลักษณะดังนี้ 
4. ดาวน์โหลดแบบฟอร์มตัวอย่าง
เรามีเอกสารตัวอย่างซึ่งมีแบบฟอร์มการรับผู้ป่วยทางการแพทย์แบบง่าย
คุณดาวน์โหลด PDF ได้โดยใช้ลิงก์ต่อไปนี้ จากนั้นอัปโหลดไปยังอินสแตนซ์ Cloud Shell
หรือจะดาวน์โหลดจากที่เก็บข้อมูล Google Cloud Storage สาธารณะของเราโดยใช้ gsutil ก็ได้
gsutil cp gs://cloud-samples-data/documentai/codelabs/form-parser/intake-form.pdf .
ยืนยันว่าระบบดาวน์โหลดไฟล์ไปยัง Cloud Shell แล้วโดยใช้คำสั่งด้านล่าง
ls -ltr intake-form.pdf
5. แยกคู่คีย์/ค่าของแบบฟอร์ม
ในขั้นตอนนี้ คุณจะใช้ API การประมวลผลออนไลน์เพื่อเรียกใช้โปรเซสเซอร์โปรแกรมแยกวิเคราะห์แบบฟอร์มที่คุณสร้างไว้ก่อนหน้านี้ จากนั้นคุณจะดึงข้อมูลคู่คีย์-ค่าที่พบในเอกสาร
การประมวลผลออนไลน์ใช้สำหรับการส่งเอกสารรายการเดียวและรอการตอบกลับ นอกจากนี้ คุณยังใช้การประมวลผลแบบกลุ่มได้หากต้องการส่งไฟล์หลายไฟล์ หรือหากขนาดไฟล์เกินจำนวนหน้าสูงสุดสำหรับการประมวลผลออนไลน์ คุณสามารถดูวิธีดำเนินการนี้ได้ใน OCR Codelab
โค้ดสำหรับการส่งคำขอประมวลผลจะเหมือนกันสำหรับโปรเซสเซอร์ทุกประเภท ยกเว้นรหัสกระบวนการ
ออบเจ็กต์การตอบกลับ Document มีรายการหน้าจากเอกสารอินพุต
ออบเจ็กต์ page แต่ละรายการประกอบด้วยรายการช่องแบบฟอร์มและตำแหน่งของช่องในข้อความ
โค้ดต่อไปนี้จะวนซ้ำในแต่ละหน้าและดึงข้อมูลคีย์ ค่า และคะแนนความเชื่อมั่นแต่ละรายการ ซึ่งเป็น Structured Data ที่จัดเก็บในฐานข้อมูลหรือใช้ในแอปพลิเคชันอื่นๆ ได้ง่ายขึ้น
สร้างไฟล์ชื่อ form_parser.py และใช้โค้ดด้านล่าง
form_parser.py
import pandas as pd
from google.cloud import documentai_v1 as documentai
def online_process(
project_id: str,
location: str,
processor_id: str,
file_path: str,
mime_type: str,
) -> documentai.Document:
"""
Processes a document using the Document AI Online Processing API.
"""
opts = {"api_endpoint": f"{location}-documentai.googleapis.com"}
# Instantiates a client
documentai_client = documentai.DocumentProcessorServiceClient(client_options=opts)
# 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
resource_name = documentai_client.processor_path(project_id, location, processor_id)
# Read the file into memory
with open(file_path, "rb") as image:
image_content = image.read()
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(
content=image_content, mime_type=mime_type
)
# Configure the process request
request = documentai.ProcessRequest(
name=resource_name, raw_document=raw_document
)
# Use the Document AI client to process the sample form
result = documentai_client.process_document(request=request)
return result.document
def trim_text(text: str):
"""
Remove extra space characters from text (blank, newline, tab, etc.)
"""
return text.strip().replace("\n", " ")
PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu'
PROCESSOR_ID = "FORM_PARSER_ID" # Create processor in Cloud Console
# The local file in your current working directory
FILE_PATH = "intake-form.pdf"
# Refer to /_p/cloud.google.com/document-ai/docs/processors-list
# for supported file types
MIME_TYPE = "application/pdf"
document = online_process(
project_id=PROJECT_ID,
location=LOCATION,
processor_id=PROCESSOR_ID,
file_path=FILE_PATH,
mime_type=MIME_TYPE,
)
names = []
name_confidence = []
values = []
value_confidence = []
for page in document.pages:
for field in page.form_fields:
# Get the extracted field names
names.append(trim_text(field.field_name.text_anchor.content))
# Confidence - How "sure" the Model is that the text is correct
name_confidence.append(field.field_name.confidence)
values.append(trim_text(field.field_value.text_anchor.content))
value_confidence.append(field.field_value.confidence)
# Create a Pandas Dataframe to print the values in tabular format.
df = pd.DataFrame(
{
"Field Name": names,
"Field Name Confidence": name_confidence,
"Field Value": values,
"Field Value Confidence": value_confidence,
}
)
print(df)
เรียกใช้โค้ดตอนนี้ แล้วคุณจะเห็นข้อความที่แยกออกมาและพิมพ์ในคอนโซล
คุณควรเห็นเอาต์พุตต่อไปนี้หากใช้เอกสารตัวอย่างของเรา
$ python3 form_parser.py
Field Name Field Name Confidence Field Value Field Value Confidence
0 Phone #: 0.999982 (906) 917-3486 0.999982
1 Emergency Contact: 0.999972 Eva Walker 0.999972
2 Marital Status: 0.999951 Single 0.999951
3 Gender: 0.999933 F 0.999933
4 Occupation: 0.999914 Software Engineer 0.999914
5 Referred By: 0.999862 None 0.999862
6 Date: 0.999858 9/14/19 0.999858
7 DOB: 0.999716 09/04/1986 0.999716
8 Address: 0.999147 24 Barney Lane 0.999147
9 City: 0.997718 Towaco 0.997718
10 Name: 0.997345 Sally Walker 0.997345
11 State: 0.996944 NJ 0.996944
...
6. แยกวิเคราะห์ตาราง
นอกจากนี้ Form Parser ยังดึงข้อมูลจากตารางภายในเอกสารได้ด้วย ในขั้นตอนนี้ เราจะดาวน์โหลดเอกสารตัวอย่างใหม่และดึงข้อมูลจากตาราง เนื่องจากเรากำลังโหลดข้อมูลลงใน Pandas ข้อมูลนี้จึงสามารถส่งออกเป็นไฟล์ CSV และรูปแบบอื่นๆ อีกมากมายได้ด้วยการเรียกใช้เมธอดเดียว
ดาวน์โหลดแบบฟอร์มตัวอย่างที่มีตาราง
เรามีเอกสารตัวอย่างซึ่งมีแบบฟอร์มและตารางตัวอย่าง
คุณดาวน์โหลด PDF ได้โดยใช้ลิงก์ต่อไปนี้ จากนั้นอัปโหลดไปยังอินสแตนซ์ Cloud Shell
หรือจะดาวน์โหลดจากที่เก็บข้อมูล Google Cloud Storage สาธารณะของเราโดยใช้ gsutil ก็ได้
gsutil cp gs://cloud-samples-data/documentai/codelabs/form-parser/form_with_tables.pdf .
ยืนยันว่าระบบดาวน์โหลดไฟล์ไปยัง Cloud Shell แล้วโดยใช้คำสั่งด้านล่าง
ls -ltr form_with_tables.pdf
ดึงข้อมูลตาราง
คำขอประมวลผลข้อมูลตารางจะเหมือนกับการดึงข้อมูลคู่คีย์-ค่าทุกประการ ความแตกต่างคือฟิลด์ที่เราดึงข้อมูลจากการตอบกลับ ข้อมูลตารางจะจัดเก็บไว้ในช่อง pages[].tables[]
ตัวอย่างนี้จะดึงข้อมูลเกี่ยวกับแถวส่วนหัวและแถวเนื้อหาของตารางสำหรับแต่ละตารางและหน้า จากนั้นพิมพ์ตารางและบันทึกตารางเป็นไฟล์ CSV
สร้างไฟล์ชื่อ table_parsing.py และใช้โค้ดด้านล่าง
table_parsing.py
# type: ignore[1]
"""
Uses Document AI online processing to call a form parser processor
Extracts the tables and data in the document.
"""
from os.path import splitext
from typing import List, Sequence
import pandas as pd
from google.cloud import documentai
def online_process(
project_id: str,
location: str,
processor_id: str,
file_path: str,
mime_type: str,
) -> documentai.Document:
"""
Processes a document using the Document AI Online Processing API.
"""
opts = {"api_endpoint": f"{location}-documentai.googleapis.com"}
# Instantiates a client
documentai_client = documentai.DocumentProcessorServiceClient(client_options=opts)
# 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
resource_name = documentai_client.processor_path(project_id, location, processor_id)
# Read the file into memory
with open(file_path, "rb") as image:
image_content = image.read()
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(
content=image_content, mime_type=mime_type
)
# Configure the process request
request = documentai.ProcessRequest(
name=resource_name, raw_document=raw_document
)
# Use the Document AI client to process the sample form
result = documentai_client.process_document(request=request)
return result.document
def get_table_data(
rows: Sequence[documentai.Document.Page.Table.TableRow], text: str
) -> List[List[str]]:
"""
Get Text data from table rows
"""
all_values: List[List[str]] = []
for row in rows:
current_row_values: List[str] = []
for cell in row.cells:
current_row_values.append(
text_anchor_to_text(cell.layout.text_anchor, text)
)
all_values.append(current_row_values)
return all_values
def text_anchor_to_text(text_anchor: documentai.Document.TextAnchor, text: str) -> str:
"""
Document AI identifies table data by their offsets in the entirety of the
document's text. This function converts offsets to a string.
"""
response = ""
# If a text segment spans several lines, it will
# be stored in different text segments.
for segment in text_anchor.text_segments:
start_index = int(segment.start_index)
end_index = int(segment.end_index)
response += text[start_index:end_index]
return response.strip().replace("\n", " ")
PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu'
PROCESSOR_ID = "FORM_PARSER_ID" # Create processor before running sample
# The local file in your current working directory
FILE_PATH = "form_with_tables.pdf"
# Refer to /_p/cloud.google.com/document-ai/docs/file-types
# for supported file types
MIME_TYPE = "application/pdf"
document = online_process(
project_id=PROJECT_ID,
location=LOCATION,
processor_id=PROCESSOR_ID,
file_path=FILE_PATH,
mime_type=MIME_TYPE,
)
header_row_values: List[List[str]] = []
body_row_values: List[List[str]] = []
# Input Filename without extension
output_file_prefix = splitext(FILE_PATH)[0]
for page in document.pages:
for index, table in enumerate(page.tables):
header_row_values = get_table_data(table.header_rows, document.text)
body_row_values = get_table_data(table.body_rows, document.text)
# Create a Pandas Dataframe to print the values in tabular format.
df = pd.DataFrame(
data=body_row_values,
columns=pd.MultiIndex.from_arrays(header_row_values),
)
print(f"Page {page.page_number} - Table {index}")
print(df)
# Save each table as a CSV file
output_filename = f"{output_file_prefix}_pg{page.page_number}_tb{index}.csv"
df.to_csv(output_filename, index=False)
เรียกใช้โค้ดตอนนี้ แล้วคุณจะเห็นข้อความที่แยกออกมาและพิมพ์ในคอนโซล
คุณควรเห็นเอาต์พุตต่อไปนี้หากใช้เอกสารตัวอย่างของเรา
$ python3 table_parsing.py
Page 1 - Table 0
Item Description
0 Item 1 Description 1
1 Item 2 Description 2
2 Item 3 Description 3
Page 1 - Table 1
Form Number: 12345678
0 Form Date: 2020/10/01
1 Name: First Last
2 Address: 123 Fake St
นอกจากนี้ คุณควรมีไฟล์ CSV ใหม่ 2 ไฟล์ในไดเรกทอรีที่คุณเรียกใช้โค้ด
$ ls form_with_tables_pg1_tb0.csv form_with_tables_pg1_tb1.csv table_parsing.py
7. ขอแสดงความยินดี
ยินดีด้วย คุณใช้ Document AI API เพื่อดึงข้อมูลจากแบบฟอร์มที่เขียนด้วยลายมือได้สำเร็จแล้ว เราขอแนะนำให้คุณทดลองใช้เอกสารแบบฟอร์มอื่นๆ
ล้างข้อมูล
วิธีหลีกเลี่ยงการเรียกเก็บเงินจากบัญชี Google Cloud สำหรับทรัพยากรที่ใช้ในบทแนะนำนี้มีดังนี้
- ใน Cloud Console ให้ไปที่หน้าจัดการทรัพยากร
- ในรายการโปรเจ็กต์ ให้เลือกโปรเจ็กต์ แล้วคลิกลบ
- ในกล่องโต้ตอบ ให้พิมพ์รหัสโปรเจ็กต์ แล้วคลิกปิดเพื่อลบโปรเจ็กต์
ดูข้อมูลเพิ่มเติม
เรียนรู้เกี่ยวกับ Document AI ต่อด้วย Codelab ที่ติดตามผลเหล่านี้
- เครื่องมือประมวลผลเฉพาะทางพร้อม Document AI (Python)
- การจัดการโปรเซสเซอร์ของ Document AI ด้วย Python
- Document AI: แบบมีมนุษย์ร่วม
แหล่งข้อมูล
- เอกสารประกอบเกี่ยวกับ Document AI
- ไลบรารีของไคลเอ็นต์ Python สำหรับ Document AI
- ตัวอย่าง Document AI
ใบอนุญาต
งานนี้ได้รับอนุญาตภายใต้สัญญาอนุญาตครีเอทีฟคอมมอนส์สำหรับยอมรับสิทธิของผู้สร้าง (Creative Commons Attribution License) 2.0 แบบทั่วไป