具備 Document AI 的專業處理器 (Python)

1. 簡介

在本程式碼研究室中,您將瞭解如何使用 Document AI 專用處理器,透過 Python 剖析專用文件並將其分類。我們會使用包含發票、收據和水電費單的 PDF 檔案做為範例,說明如何分類及分割檔案。接著,我們會以應付憑據為範例,說明如何剖析及擷取實體。

這項程序和範例程式碼適用於 Document AI 支援的任何專用文件

必要條件

本程式碼研究室以其他 Document AI 程式碼研究室的內容為基礎。

建議您先完成下列程式碼研究室,再繼續操作:

課程內容

  • 如何分類及識別專業文件的分割點。
  • 如何使用專用處理器擷取實體並加上結構定義。

軟硬體需求

  • Google Cloud 專案
  • ChromeFirefox 瀏覽器
  • Python 3 知識

2. 開始設定

本程式碼研究室假設您已完成入門程式碼研究室中列出的 Document AI 設定步驟。

請先完成下列步驟再繼續:

您也必須安裝 Pandas,這是 Python 的熱門資料分析程式庫。

pip3 install --upgrade pandas

3. 建立專用處理器

您必須先建立本教學課程中使用的處理器執行個體。

  1. 前往控制台的「Document AI Platform Overview」
  2. 點按「建立處理器」,捲動至「專用」,然後選取「採購文件分割器」
  3. 將名稱設為「codelab-procurement-splitter」(或您容易記的其他名稱),然後從清單中選取最接近的區域。
  4. 點按「建立」即可建立處理器
  5. 複製處理器 ID。您稍後必須在程式碼中使用此 ID。
  6. 使用「應付憑據剖析器」重複執行步驟 2 到 6 (您可以將其命名為「codelab-invoice-parser」)

在控制台中測試處理器

上傳文件即可在控制台測試應付憑據剖析器。

按一下「上傳文件」,然後選取要剖析的發票。如果沒有可用的帳單,可以下載並使用這個範本。

google_invoice.png

輸出內容應如下所示:

InvoiceParser.png

4. 下載範例文件

我們提供了幾個範例文件,可以用於這個實驗室。

你可以透過下列連結下載 PDF。然後將檔案上傳至 Cloud Shell 執行個體

或者,您也可以使用 gsutil 從我們的公開 Cloud Storage 值區下載這些檔案。

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. 分類及分割文件

在這個步驟中,您將使用線上處理 API,分類多頁文件並偵測邏輯分割點。

如要傳送多個檔案,或檔案大小超過線上處理功能的頁數上限,也能使用批次處理 API。如要瞭解如何執行這項操作,請參閱 Document AI OCR 程式碼實驗室

對於一般處理器,用於發出 API 要求的程式碼完全相同,唯一的差異是處理器 ID。

採購分割器/分類器

建立名為 classification.py 的檔案,並使用下列程式碼。

PROCUREMENT_SPLITTER_ID 替換為您先前建立的 Procurement Splitter 處理器 ID。將 YOUR_PROJECT_IDYOUR_PROJECT_LOCATION 分別替換為 Cloud 專案 ID 和處理器位置。

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)

輸出內容大致如下:

$ 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]

請注意,採購分割器/分類器已正確識別第 0-1 頁和第 3-4 頁的文件類型。

第 2 頁包含一般醫療入院表單,因此分類器正確地將其識別為 other

6. 擷取實體

您現在可以從檔案中擷取擷取實體並加上結構定義,包括信心分數、屬性和正規化值。

發出 API 要求的程式碼與上一步相同,可以透過線上或批次要求完成。

我們將從實體存取下列資訊:

  • 實體類型
    • (例如:invoice_datereceiver_nametotal_amount)
  • 原始值
    • 原始文件檔案內的資料值
  • 正規化值
  • 信心值
    • 模型認為值正確無誤的肯定程度

部分實體類型 (如 line_item) 也可能包含屬性,屬性是巢狀實體,例如 line_item/unit_priceline_item/description

這個範例會攤平巢狀結構的資料,方便查看。

應付憑據剖析器

建立名為 extraction.py 的檔案,並使用下列程式碼。

INVOICE_PARSER_ID 替換為先前建立的應付憑據剖析器處理器 ID,並使用 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)

輸出內容大致如下:

$ 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. 試用其他專用處理器 (如有需要)

您成功運用 Document AI for procurement 將文件分類,並剖析應付憑據。Document AI 也支援下列其他專用解決方案:

您可以按照同樣的程序、使用相同的程式碼,來操作任何專用處理器。

如要試用其他專用解決方案,您可以重新執行實驗室,改用其他處理器類型和專用範例文件。

範例文件

您可以利用下列範例文件,試用其他專用處理器。

解決方案

處理器類型

文件

身分識別

美國駕照剖析器

貸款文件

貸款文件分割器和分類器

貸款文件

W-9 表單剖析器

合約

合約剖析器

如需其他範例文件和處理器輸出內容,請參閱說明文件

8. 恭喜

恭喜!您已成功使用 Document AI,從專用文件中擷取資料並分類。建議您試用其他專用文件類型。

清除

如要避免系統向您的 Google Cloud 帳戶收取您在本教學課程中所用資源的相關費用:

  • 前往 Cloud Console 中的「管理資源」頁面。
  • 在專案清單中選取專案,然後按一下「刪除」。
  • 在對話方塊中輸入專案 ID,然後按一下「關閉」即可刪除專案。

瞭解詳情

歡迎透過下列後續程式碼研究室,進一步瞭解 Document AI。

資源

授權

這項內容採用的授權為 Creative Commons 姓名標示 2.0 通用授權。