Document AI (Python)를 사용하는 특수 프로세서

1. 소개

이 Codelab에서는 Document AI 특수 프로세서를 사용하여 Python으로 특수 문서를 분류하고 파싱하는 방법을 알아봅니다. 분류 및 분할에는 인보이스, 영수증, 공과금 명세서가 포함된 예시 PDF 파일을 사용합니다. 그런 다음 파싱 및 항목 추출의 경우 인보이스를 예시로 사용합니다.

이 절차와 예시 코드는 Document AI에서 지원하는 모든 특수 문서에 적용됩니다.

기본 요건

이 Codelab은 다른 Document AI Codelabs에서 다룬 콘텐츠를 기반으로 합니다.

다음 Codelab을 먼저 완료한 후에 진행하는 것이 좋습니다.

학습할 내용

  • 전문 문서를 분류하고 분할 지점을 식별하는 방법
  • 특수 프로세서를 사용하여 스키마가 적용된 항목을 추출하는 방법

필요한 항목

  • Google Cloud 프로젝트
  • 브라우저(Chrome, Firefox 등)
  • Python 3에 관한 지식

2. 설정

이 Codelab에서는 Codelab 소개에 있는 Document AI 설정 단계를 완료했다고 가정합니다.

다음 단계를 완료한 후에 진행하세요.

Python용 인기 데이터 분석 라이브러리인 Pandas도 설치해야 합니다.

pip3 install --upgrade pandas

3. 전문 프로세서 만들기

먼저 이 튜토리얼에서 사용할 프로세서의 인스턴스를 만들어야 합니다.

  1. 콘솔에서 Document AI Platform 개요로 이동합니다.
  2. 프로세서 만들기를 클릭하고 특수로 스크롤한 다음 조달 문서 추출기를 선택합니다.
  3. 이름을 'codelab-procurement-splitter'로 지정하고(또는 다른 기억하기 쉬운 이름) 목록에서 가장 가까운 리전을 선택합니다.
  4. 만들기를 클릭하여 프로세서를 만듭니다.
  5. 프로세서 ID를 복사합니다. 나중에 코드에서 이 ID를 사용해야 합니다.
  6. 인보이스 파서('codelab-invoice-parser'라고 이름을 지정할 수 있음)를 사용하여 2~6단계를 반복합니다.

콘솔에서 프로세서 테스트

콘솔에서 문서를 업로드하여 인보이스 파서를 테스트할 수 있습니다.

문서 업로드를 클릭하고 파싱할 인보이스를 선택합니다. 사용할 수 있는 인보이스가 없는 경우 이 샘플 인보이스를 다운로드하여 사용할 수 있습니다.

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 Codelab에서 방법을 확인할 수 있습니다.

API 요청을 만드는 코드는 프로세서 ID를 제외하고 일반 프로세서에서 동일합니다.

조달 분할기/분류 기준

classification.py라는 파일을 만들고 아래 코드를 사용합니다.

PROCUREMENT_SPLITTER_ID를 이전에 만든 조달 스플리터 프로세서의 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 요청을 만드는 코드는 이전 단계와 동일하며 온라인 또는 일괄 요청으로 실행할 수 있습니다.

Google은 항목에서 다음 정보에 액세스합니다.

  • 항목 유형
    • (예: invoice_date, receiver_name, total_amount)
  • 원시 값
    • 원본 문서 파일에 표시된 데이터 값입니다.
  • 정규화된 값
    • 정규화된 표준 형식의 데이터 값입니다(해당하는 경우).
    • Enterprise Knowledge Graph의 보강도 포함될 수 있습니다.
  • 신뢰값
    • 값이 정확하다고 모델이 '확신'하는 정도입니다.

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를 사용하여 문서를 분류하고 인보이스를 파싱했습니다. Document AI는 여기에 나열된 다른 특수 솔루션도 지원합니다.

동일한 절차를 따르고 동일한 코드를 사용하여 모든 특수 프로세서를 처리할 수 있습니다.

다른 특수 솔루션을 사용해 보려면 다른 프로세서 유형과 특수 샘플 문서를 사용하여 실습을 다시 실행하면 됩니다.

샘플 문서

다음은 다른 특수 프로세서를 사용해 볼 수 있는 샘플 문서입니다.

솔루션

프로세서 유형

문서

ID

미국 운전면허증 파서

대출

대출 분할기 및 분류기

대출

W9 파서

계약

계약 파서

문서에서 다른 샘플 문서와 프로세서 출력을 확인할 수 있습니다.

8. 축하합니다

수고하셨습니다. Document AI를 사용하여 특수 문서에서 데이터를 분류하고 추출했습니다. 다른 특수 문서 유형으로도 실험해 보시기 바랍니다.

삭제하기

이 튜토리얼에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 다음 안내를 따르세요.

  • Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.
  • 프로젝트 목록에서 해당 프로젝트를 선택한 후 삭제를 클릭합니다.
  • 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

자세히 알아보기

다음과 같은 후속 Codelab에서 Document AI 학습을 계속하세요.

리소스

라이선스

이 작업물은 Creative Commons Attribution 2.0 일반 라이선스에 따라 사용이 허가되었습니다.