1. Giới thiệu
Trong lớp học lập trình này, bạn sẽ tìm hiểu cách sử dụng Bộ xử lý chuyên biệt của Document AI để phân loại và phân tích cú pháp các tài liệu chuyên biệt bằng Python. Để phân loại và tách, chúng ta sẽ sử dụng một tệp PDF mẫu chứa hoá đơn, biên nhận và bảng sao kê của công ty điện lực. Sau đó, để phân tích cú pháp và trích xuất thực thể, chúng ta sẽ sử dụng hoá đơn làm ví dụ.
Quy trình và mã ví dụ này sẽ hoạt động với mọi tài liệu chuyên biệt mà Document AI hỗ trợ.
Điều kiện tiên quyết
Lớp học lập trình này dựa trên nội dung được trình bày trong các Lớp học lập trình khác về Document AI.
Bạn nên hoàn thành các lớp học lập trình sau đây trước khi tiếp tục:
- Nhận dạng ký tự quang học (OCR) bằng Document AI và Python
- Phân tích cú pháp biểu mẫu bằng Document AI (Python)
Kiến thức bạn sẽ học được
- Cách phân loại và xác định điểm phân chia cho các tài liệu chuyên biệt.
- Cách trích xuất các thực thể được sơ đồ hoá bằng cách sử dụng các bộ xử lý chuyên dụng.
Bạn cần có
2. Thiết lập
Lớp học lập trình này giả định rằng bạn đã hoàn thành các bước Thiết lập Document AI được liệt kê trong Lớp học lập trình giới thiệu.
Vui lòng hoàn tất các bước sau trước khi tiếp tục:
Bạn cũng cần cài đặt Pandas, một thư viện Phân tích dữ liệu phổ biến cho Python.
pip3 install --upgrade pandas
3. Tạo bộ xử lý chuyên dụng
Trước tiên, bạn phải tạo các thực thể của bộ xử lý mà bạn sẽ sử dụng cho hướng dẫn này.
- Trong bảng điều khiển, hãy chuyển đến phần Tổng quan về Document AI
- Nhấp vào Tạo bộ xử lý, di chuyển xuống Chuyên biệt rồi chọn Bộ tách tài liệu mua sắm.
- Đặt tên cho ứng dụng là "codelab-procurement-splitter" (hoặc một tên khác mà bạn sẽ nhớ) rồi chọn khu vực gần nhất trong danh sách.
- Nhấp vào Tạo để tạo bộ xử lý
- Sao chép mã nhận dạng bộ xử lý. Sau này, bạn phải sử dụng chỉ mục này trong mã của mình.
- Lặp lại các bước từ 2 đến 6 với Trình phân tích cú pháp hoá đơn (bạn có thể đặt tên là "codelab-invoice-parser")
Bộ xử lý kiểm thử trong Bảng điều khiển
Bạn có thể kiểm thử Trình phân tích cú pháp hoá đơn trong bảng điều khiển bằng cách tải một tài liệu lên.
Nhấp vào Tải chứng từ lên rồi chọn một hoá đơn để phân tích cú pháp. Bạn có thể tải xuống và sử dụng hoá đơn mẫu này nếu không có hoá đơn nào để sử dụng.

Đầu ra của bạn sẽ có dạng như sau:

4. Tải tài liệu mẫu xuống
Chúng ta có một vài tài liệu mẫu để sử dụng cho lớp học này.
Bạn có thể tải tệp PDF xuống bằng các đường liên kết sau. Sau đó, hãy tải các tệp đó lên phiên bản Cloud Shell.
Ngoài ra, bạn có thể tải các tệp này xuống từ Bộ chứa Cloud Storage công khai của chúng tôi bằng cách sử dụng gsutil.
gsutil cp gs://cloud-samples-data/documentai/codelabs/specialized-processors/procurement_multi_document.pdf .
gsutil cp gs://cloud-samples-data/documentai/codelabs/specialized-processors/google_invoice.pdf .
5. Phân loại và tách tài liệu
Trong bước này, bạn sẽ sử dụng API xử lý trực tuyến để phân loại và phát hiện các điểm phân chia logic cho một tài liệu có nhiều trang.
Bạn cũng có thể sử dụng API xử lý hàng loạt nếu muốn gửi nhiều tệp hoặc nếu kích thước tệp vượt quá số trang tối đa để xử lý trực tuyến. Bạn có thể xem cách thực hiện việc này trong Lớp học lập trình về OCR bằng Document AI.
Mã để thực hiện yêu cầu API giống hệt với mã của bộ xử lý chung, ngoại trừ Mã nhận dạng bộ xử lý.
Bộ phân loại/Bộ chia tách quy trình mua sắm
Tạo một tệp có tên là classification.py và sử dụng mã dưới đây.
Thay thế PROCUREMENT_SPLITTER_ID bằng mã nhận dạng của Procurement Splitter Processor mà bạn đã tạo trước đó. Thay thế YOUR_PROJECT_ID và YOUR_PROJECT_LOCATION bằng Mã dự án trên đám mây và Vị trí của bộ xử lý tương ứng.
classification.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 file:
file_content = file.read()
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(content=file_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
PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu'
PROCESSOR_ID = "PROCUREMENT_SPLITTER_ID" # Create processor in Cloud Console
# The local file in your current working directory
FILE_PATH = "procurement_multi_document.pdf"
# Refer to https://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,
)
print("Document processing complete.")
types = []
confidence = []
pages = []
# Each Document.entity is a classification
for entity in document.entities:
classification = entity.type_
types.append(classification)
confidence.append(f"{entity.confidence:.0%}")
# entity.page_ref contains the pages that match the classification
pages_list = []
for page_ref in entity.page_anchor.page_refs:
pages_list.append(page_ref.page)
pages.append(pages_list)
# Create a Pandas Dataframe to print the values in tabular format.
df = pd.DataFrame({"Classification": types, "Confidence": confidence, "Pages": pages})
print(df)
Đầu ra của bạn sẽ có dạng như sau:
$ python3 classification.py
Document processing complete.
Classification Confidence Pages
0 invoice_statement 100% [0]
1 receipt_statement 98% [1]
2 other 81% [2]
3 utility_statement 100% [3]
4 restaurant_statement 100% [4]
Lưu ý rằng Bộ phân chia/Phân loại quy trình mua sắm đã xác định chính xác các loại tài liệu trên trang 0-1 và 3-4.
Trang 2 chứa một biểu mẫu chung về thông tin y tế, vì vậy, trình phân loại đã xác định chính xác trang này là other.
6. Trích xuất các thực thể
Giờ đây, bạn có thể trích xuất các thực thể được lập sơ đồ từ các tệp, bao gồm cả điểm số độ tin cậy, thuộc tính và giá trị được chuẩn hoá.
Mã để đưa ra yêu cầu API giống với bước trước và bạn có thể thực hiện bằng yêu cầu trực tuyến hoặc yêu cầu hàng loạt.
Chúng tôi sẽ truy cập vào những thông tin sau đây của các thực thể:
- Loại pháp nhân
- (ví dụ:
invoice_date,receiver_name,total_amount)
- (ví dụ:
- Giá trị thô
- Giá trị dữ liệu như trong tệp tài liệu gốc.
- Giá trị được chuẩn hoá
- Giá trị dữ liệu ở định dạng chuẩn hoá và tiêu chuẩn (nếu có).
- Cũng có thể bao gồm thông tin bổ sung từ Sơ đồ tri thức Enterprise
- Giá trị độ tin cậy
- Mức độ "chắc chắn" của mô hình về độ chính xác của các giá trị.
Một số loại thực thể, chẳng hạn như line_item cũng có thể bao gồm các thuộc tính là các thực thể lồng nhau, chẳng hạn như line_item/unit_price và line_item/description.
Ví dụ này làm phẳng cấu trúc lồng nhau để dễ xem.
Trình phân tích cú pháp hoá đơn
Tạo một tệp có tên là extraction.py và sử dụng mã dưới đây.
Thay thế INVOICE_PARSER_ID bằng mã nhận dạng cho Trình xử lý trình phân tích cú pháp hoá đơn mà bạn đã tạo trước đó và sử dụng tệp google_invoice.pdf
extraction.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 file:
file_content = file.read()
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(content=file_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
PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu'
PROCESSOR_ID = "INVOICE_PARSER_ID" # Create processor in Cloud Console
# The local file in your current working directory
FILE_PATH = "google_invoice.pdf"
# Refer to https://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,
)
types = []
raw_values = []
normalized_values = []
confidence = []
# Grab each key/value pair and their corresponding confidence scores.
for entity in document.entities:
types.append(entity.type_)
raw_values.append(entity.mention_text)
normalized_values.append(entity.normalized_value.text)
confidence.append(f"{entity.confidence:.0%}")
# Get Properties (Sub-Entities) with confidence scores
for prop in entity.properties:
types.append(prop.type_)
raw_values.append(prop.mention_text)
normalized_values.append(prop.normalized_value.text)
confidence.append(f"{prop.confidence:.0%}")
# Create a Pandas Dataframe to print the values in tabular format.
df = pd.DataFrame(
{
"Type": types,
"Raw Value": raw_values,
"Normalized Value": normalized_values,
"Confidence": confidence,
}
)
print(df)
Đầu ra của bạn sẽ có dạng như sau:
$ python3 extraction.py
Type Raw Value Normalized Value Confidence
0 vat $1,767.97 100%
1 vat/tax_amount $1,767.97 1767.97 USD 0%
2 invoice_date Sep 24, 2019 2019-09-24 99%
3 due_date Sep 30, 2019 2019-09-30 99%
4 total_amount 19,647.68 19647.68 97%
5 total_tax_amount $1,767.97 1767.97 USD 92%
6 net_amount 22,379.39 22379.39 91%
7 receiver_name Jane Smith, 83%
8 invoice_id 23413561D 67%
9 receiver_address 1600 Amphitheatre Pkway\nMountain View, CA 94043 66%
10 freight_amount $199.99 199.99 USD 56%
11 currency $ USD 53%
12 supplier_name John Smith 19%
13 purchase_order 23413561D 1%
14 receiver_tax_id 23413561D 0%
15 supplier_iban 23413561D 0%
16 line_item 9.99 12 12 ft HDMI cable 119.88 100%
17 line_item/unit_price 9.99 9.99 90%
18 line_item/quantity 12 12 77%
19 line_item/description 12 ft HDMI cable 39%
20 line_item/amount 119.88 119.88 92%
21 line_item 12 399.99 27" Computer Monitor 4,799.88 100%
22 line_item/quantity 12 12 80%
23 line_item/unit_price 399.99 399.99 91%
24 line_item/description 27" Computer Monitor 15%
25 line_item/amount 4,799.88 4799.88 94%
26 line_item Ergonomic Keyboard 12 59.99 719.88 100%
27 line_item/description Ergonomic Keyboard 32%
28 line_item/quantity 12 12 76%
29 line_item/unit_price 59.99 59.99 92%
30 line_item/amount 719.88 719.88 94%
31 line_item Optical mouse 12 19.99 239.88 100%
32 line_item/description Optical mouse 26%
33 line_item/quantity 12 12 78%
34 line_item/unit_price 19.99 19.99 91%
35 line_item/amount 239.88 239.88 94%
36 line_item Laptop 12 1,299.99 15,599.88 100%
37 line_item/description Laptop 83%
38 line_item/quantity 12 12 76%
39 line_item/unit_price 1,299.99 1299.99 90%
40 line_item/amount 15,599.88 15599.88 94%
41 line_item Misc processing fees 899.99 899.99 1 100%
42 line_item/description Misc processing fees 22%
43 line_item/unit_price 899.99 899.99 91%
44 line_item/amount 899.99 899.99 94%
45 line_item/quantity 1 1 63%
7. Không bắt buộc: Thử các bộ xử lý chuyên dụng khác
Bạn đã sử dụng thành công Document AI for Procurement để phân loại tài liệu và phân tích cú pháp hoá đơn. Document AI cũng hỗ trợ các giải pháp chuyên biệt khác được liệt kê tại đây:
Bạn có thể làm theo quy trình tương tự và sử dụng cùng một mã để xử lý mọi bộ xử lý chuyên dụng.
Nếu muốn dùng thử các giải pháp chuyên biệt khác, bạn có thể chạy lại phòng thí nghiệm với các loại bộ xử lý khác và các tài liệu mẫu chuyên biệt.
Tài liệu mẫu
Sau đây là một số tài liệu mẫu mà bạn có thể dùng để dùng thử các bộ xử lý chuyên biệt khác.
Giải pháp | Loại bộ xử lý | Tài liệu |
của bản thân | ||
Cho vay | ||
Cho vay | ||
Hợp đồng |
Bạn có thể tìm thấy các tài liệu mẫu và đầu ra của bộ xử lý khác trong tài liệu.
8. Xin chúc mừng
Chúc mừng bạn đã sử dụng thành công Document AI để phân loại và trích xuất dữ liệu từ các tài liệu chuyên biệt. Bạn nên thử nghiệm các loại tài liệu chuyên biệt khác.
Dọn dẹp
Để tránh phát sinh phí cho tài khoản Google Cloud của bạn đối với các tài nguyên được dùng trong hướng dẫn này, hãy làm như sau:
- Trong Cloud Console, hãy chuyển đến trang Quản lý tài nguyên.
- Trong danh sách dự án, hãy chọn dự án của bạn rồi nhấp vào Xoá.
- Trong hộp thoại, hãy nhập mã dự án rồi nhấp vào Tắt để xoá dự án.
Tìm hiểu thêm
Tiếp tục tìm hiểu về Document AI thông qua các lớp học lập trình tiếp theo này.
- Quản lý các bộ xử lý Document AI bằng Python
- Document AI: Sự tham gia của con người vào quy trình
- Document AI Workbench: Đào tạo thêm
- Document AI Workbench: Bộ xử lý tuỳ chỉnh
Tài nguyên
- The Future of Documents – YouTube Playlist
- Tài liệu về Document AI
- Thư viện ứng dụng Document AI Python
- Mẫu Document AI
Giấy phép
Tác phẩm này được cấp phép theo giấy phép Ghi công theo Creative Commons 2.0 Chung.