Phân tích cú pháp biểu mẫu bằng AI tài liệu (Python)

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 Trình phân tích cú pháp biểu mẫu của Document AI để phân tích cú pháp biểu mẫu viết tay bằng Python.

Chúng ta sẽ sử dụng một biểu mẫu tiếp nhận y tế đơn giản làm ví dụ, nhưng quy trình này sẽ hoạt động với mọi biểu mẫu tổng quát được DocAI hỗ trợ.

Điều kiện tiên quyết

Lớp học lập trình này được xây dựng 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.

Kiến thức bạn sẽ học được

  • Cách phân tích cú pháp và trích xuất dữ liệu từ biểu mẫu đã quét bằng Trình phân tích cú pháp biểu mẫu của Document AI.

Bạn cần có

  • Dự án trên Google Cloud
  • Một trình duyệt, chẳng hạn như Chrome hoặc Firefox
  • Kiến thức về Python 3

Bản khảo sát

Bạn sẽ sử dụng hướng dẫn này như thế nào?

Chỉ đọc Đọc và hoàn thành bài tập

Bạn đánh giá thế nào về trải nghiệm của mình với Python?

Mới làm quen Trung cấp Thành thạo

Bạn đánh giá thế nào về trải nghiệm sử dụng các dịch vụ của Google Cloud?

Mới bắt đầu Trung cấp Thành thạo

2. Thiết lập và yêu cầu

Lớp học lập trình này giả định rằng bạn đã hoàn tất các bước thiết lập Document AI được liệt kê trong Lớp học lập trình về OCR của Document AI.

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 nguồn mở cho Python.

pip3 install --upgrade pandas

3. Tạo bộ xử lý Trình phân tích cú pháp biểu mẫu

Trước tiên, bạn phải tạo một phiên bản trình xử lý Trình phân tích cú pháp biểu mẫu để sử dụng trong Nền tảng Document AI cho hướng dẫn này.

  1. Trong bảng điều khiển, hãy chuyển đến phần Tổng quan về nền tảng Document AI
  2. Nhấp vào Create Processor (Tạo bộ xử lý) rồi chọn Form Parser (Trình phân tích cú pháp biểu mẫu)Bộ xử lý
  3. Chỉ định tên bộ xử lý và chọn khu vực của bạn trong danh sách.
  4. Nhấp vào Create (Tạo) để tạo bộ xử lý
  5. Sao chép mã định danh tiến trình của bạn. Bạn phải sử dụng mã này trong mã của mình sau này.

Kiểm thử bộ xử lý trong Cloud Console

Bạn có thể thử nghiệm bộ xử lý 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 tài liệu lên rồi chọn một biểu mẫu để phân tích cú pháp. Bạn có thể tải xuống và sử dụng biểu mẫu mẫu này nếu chưa có biểu mẫu nào để sử dụng.

Biểu mẫu sức khoẻ

Kết quả của bạn sẽ có dạng như sau: Biểu mẫu đã phân tích cú pháp

4. Tải biểu mẫu mẫu xuống

Chúng tôi có một tài liệu mẫu chứa biểu mẫu tiếp nhận thông tin y tế đơn giản.

Bạn có thể tải tệp PDF xuống bằng đường liên kết sau. Sau đó, tải tệp đó lên phiên bản Cloud Shell.

Ngoài ra, bạn có thể tải tệp này xuống từ Bộ chứa Google Cloud Storage công khai của chúng tôi bằng gsutil.

gsutil cp gs://cloud-samples-data/documentai/codelabs/form-parser/intake-form.pdf .

Xác nhận rằng tệp đã được tải xuống Cloud Shell bằng lệnh dưới đây:

ls -ltr intake-form.pdf

5. Trích xuất cặp khoá/giá trị của biểu mẫu

Trong bước này, bạn sẽ sử dụng API xử lý trực tuyến để gọi trình phân tích cú pháp biểu mẫu mà bạn đã tạo trước đó. Sau đó, bạn sẽ trích xuất các cặp khoá-giá trị có trong tài liệu.

Xử lý trực tuyến là gửi một tài liệu và chờ phản hồi. Bạn cũng có thể sử dụng tính năng 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 lại cách thực hiện việc này trong Lớp học lập trình về OCR.

Mã để tạo yêu cầu tiến trình là giống nhau cho mọi loại bộ xử lý, ngoại trừ Mã định danh tiến trình.

Đối tượng phản hồi Document chứa danh sách các trang trong tài liệu đầu vào.

Mỗi đối tượng page chứa một danh sách các trường biểu mẫu và vị trí của các trường đó trong văn bản.

Đoạn mã sau đây lặp lại qua từng trang và trích xuất từng khoá, giá trị và điểm tin cậy. Đây là dữ liệu có cấu trúc, có thể dễ dàng lưu trữ trong cơ sở dữ liệu hoặc dùng trong các ứng dụng khác.

Tạo một tệp có tên là form_parser.py và sử dụng mã bên dưới.

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)

Bây giờ, hãy chạy mã và bạn sẽ thấy văn bản được trích xuất và in trong bảng điều khiển.

Bạn sẽ thấy kết quả sau đây nếu sử dụng tài liệu mẫu của chúng tôi:

$ 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. Phân tích cú pháp bảng

Trình phân tích cú pháp biểu mẫu cũng có thể trích xuất dữ liệu từ các bảng trong tài liệu. Trong bước này, chúng ta sẽ tải một tài liệu mẫu mới xuống và trích xuất dữ liệu từ bảng. Vì chúng ta đang tải dữ liệu vào Pandas, nên dữ liệu này có thể được xuất ra tệp CSV và nhiều định dạng khác bằng một lệnh gọi phương thức duy nhất.

Tải Biểu mẫu mẫu có bảng xuống

Chúng tôi có một tài liệu mẫu chứa một biểu mẫu mẫu và một bảng.

Bạn có thể tải tệp PDF xuống bằng đường liên kết sau. Sau đó, tải tệp đó lên phiên bản Cloud Shell.

Ngoài ra, bạn có thể tải tệp này xuống từ Bộ chứa Google Cloud Storage công khai của chúng tôi bằng gsutil.

gsutil cp gs://cloud-samples-data/documentai/codelabs/form-parser/form_with_tables.pdf .

Xác nhận rằng tệp đã được tải xuống Cloud Shell bằng lệnh dưới đây:

ls -ltr form_with_tables.pdf

Trích xuất dữ liệu trong bảng

Yêu cầu xử lý dữ liệu bảng hoàn toàn giống với yêu cầu trích xuất cặp khoá-giá trị. Sự khác biệt nằm ở trường mà chúng ta trích xuất dữ liệu trong phản hồi. Dữ liệu bảng được lưu trữ trong trường pages[].tables[].

Ví dụ này trích xuất thông tin về hàng tiêu đề và hàng nội dung của bảng cho từng bảng và trang, sau đó in bảng và lưu bảng dưới dạng tệp CSV.

Tạo một tệp có tên là table_parsing.py và sử dụng mã bên dưới.

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)

Bây giờ, hãy chạy mã và bạn sẽ thấy văn bản được trích xuất và in trong bảng điều khiển.

Bạn sẽ thấy kết quả sau đây nếu sử dụng tài liệu mẫu của chúng tôi:

$ 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

Bạn cũng sẽ có hai tệp CSV mới trong thư mục mà bạn đang chạy mã.

$ ls
form_with_tables_pg1_tb0.csv form_with_tables_pg1_tb1.csv table_parsing.py

7. Xin chúc mừng

Xin chúc mừng, bạn đã sử dụng thành công Document AI API để trích xuất dữ liệu từ biểu mẫu viết tay. Bạn nên thử nghiệm với các tài liệu biểu mẫu 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 sử 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 qua các Lớp học lập trình tiếp theo.

Tài nguyên

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.