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 AI của tài liệu để phân tích cú pháp một biểu mẫu viết tay bằng Python.

Chúng tôi sẽ lấy một biểu mẫu nhập thông tin y tế đơn giản làm ví dụ, nhưng quy trình này sẽ hoạt động với bất kỳ biểu mẫu phổ biến nào do DocsAI 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ó trong các Lớp học lập trình khác về AI tạo tài liệu.

Bạn nên hoàn tất 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ừ một biểu mẫu đã quét bằng Trình phân tích cú pháp biểu mẫu AI tài liệu.

Bạn cần có

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

Khảo sát

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

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

Bạn đánh giá thế nào về trải nghiệm sử dụng Python?

Người mới tập 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?

Người mới tập 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 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ề AI OCR của tài liệu.

Vui lòng hoàn tất các bước sau đây trước khi tiếp tục:

Bạn cũng sẽ cần cài đặt Pandas, một thư viện Phân tích dữ liệu nguồn mở dành cho Python.

pip3 install --upgrade pandas

3. Tạo trình 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 thực thể trình xử lý Trình phân tích cú pháp biểu mẫu để dùng trong Nền tảng AI của tài liệu 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 AI cho tài liệu
  2. Nhấp vào Tạo trình xử lý rồi chọn Trình phân tích cú pháp biểu mẫuBộ xử lý
  3. Chỉ định tên đơn vị xử lý rồi chọn khu vực của bạn trong danh sách.
  4. Nhấp vào Tạo để tạo bộ xử lý
  5. Sao chép mã nhận dạng đơn vị xử lý. Bạn phải sử dụng mã này sau này.

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

Bạn có thể kiểm tra 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 và 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 không có sẵn biểu mẫu để sử dụng.

Biểu mẫu sức khoẻ

Kết quả của bạn sẽ có dạng như sau: Dạng được 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 một tờ khai đơn giản để nhập thông tin y tế.

Bạn có thể tải bản PDF xuống qua đường liên kết sau. Sau đó, hãy 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 công khai của Google Cloud Storage bằng gsutil.

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

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

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 xử lý 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.

Quy trình xử lý trực tuyến tức là gửi một tài liệu duy nhất 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 được 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 OCR.

Mã để đưa ra yêu cầu về quy trình là giống nhau cho mọi kiểu bộ xử lý, trừ Mã nhận dạng đơn vị xử lý.

Đối tượng phản hồi Document (Tài liệu) 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.

Mã sau đây sẽ 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ể được lưu trữ dễ dàng hơn trong cơ sở dữ liệu hoặc được dùng trong các ứng dụng khác.

Tạo một tệp có tên là form_parser.py rồi sử dụng mã dưới đây.

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 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,
)

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)

Chạy mã ngay và bạn sẽ thấy văn bản được trích xuất và in trong bảng điều khiển của mình.

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 ta:

$ 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. Ở 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 chỉ bằng một lệnh gọi phương thức.

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 biểu mẫu mẫu và bảng.

Bạn có thể tải bản PDF xuống qua đường liên kết sau. Sau đó, hãy 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 công khai của Google Cloud Storage bằng gsutil.

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

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

ls -ltr form_with_tables.pdf

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

Yêu cầu xử lý dữ liệu trong bảng giống hoàn toàn như việc trích xuất cặp khoá-giá trị. Điểm khác biệt là những trường mà chúng tôi trích xuất dữ liệu trong câu trả lời. Dữ liệu trong bảng được lưu trữ trong trường pages[].tables[].

Ví dụ này trích xuất thông tin về từ các hàng tiêu đề và hàng nội dung của bảng cho mỗi 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 rồi sử dụng mã dưới đây.

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 https://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)

Chạy mã ngay và bạn sẽ thấy văn bản được trích xuất và in trong bảng điều khiển của mình.

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 ta:

$ 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 phải có hai tệp CSV mới trong thư mục 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 API Document AI để trích xuất dữ liệu từ mộ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 bị tính phí vào tài khoản Google Cloud của bạn cho các tài nguyên được sử dụng trong hướng dẫn này:

  • 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 rồi nhấp vào Xoá.
  • Trong hộp thoại, nhập ID dự án rồi nhấp vào Tắt để xoá dự án.

Tìm hiểu thêm

Hãy tiếp tục tìm hiểu về AI cho tài liệu qua các Lớp học lập trình tiếp theo này.

Tài nguyên

Giấy phép

Tác phẩm này được cấp phép theo Giấy phép chung Ghi nhận tác giả Creative Commons 2.0.