Document AI(Python)를 사용한 광학 문자 인식(OCR)

1. 개요

Document AI란?

Document AI는 문서, 이메일, 청구서, 양식과 같이 구조화되지 않은 데이터를 가져와 데이터의 이해, 분석, 사용을 쉽게 만들어 주는 문서 이해 솔루션입니다. 이 API는 콘텐츠 분류, 항목 추출, 고급 검색 등을 통해 구조를 제공합니다.

이 실습에서는 Python으로 Document AI API를 사용하여 광학 문자 인식을 수행하는 방법을 알아봅니다.

최근에 미국에서 공개 도메인에 속하게 된 A.A. 밀른의 명작 소설인 '곰돌이 푸' PDF 파일을 활용하려고 합니다. 이 파일은 Google 도서에서 스캔하고 디지털화했습니다.

학습할 내용

  • Document AI API를 사용 설정하는 방법
  • API 요청을 인증하는 방법
  • Python용 클라이언트 라이브러리를 설치하는 방법
  • 온라인 및 일괄 처리 API를 사용하는 방법
  • PDF 파일에서 텍스트를 파싱하는 방법

필요한 항목

  • Google Cloud 프로젝트
  • 브라우저(Chrome 또는 Firefox 등)
  • Python 사용에 관한 지식(3.9+)

설문조사

이 튜토리얼을 어떻게 사용하실 계획인가요?

읽기만 할 계획입니다 읽은 다음 연습 활동을 완료할 계획입니다

귀하의 Python 사용 경험이 어떤지 평가해 주세요.

초급 중급 고급

귀하의 Google Cloud 서비스 사용 경험을 평가해 주세요.

<ph type="x-smartling-placeholder"></ph> 초보자 중급 숙련도

2. 설정 및 요구사항

자습형 환경 설정

  1. Cloud 콘솔에 로그인하고 새 프로젝트를 만들거나 기존 프로젝트를 다시 사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.

프로젝트 선택

새 프로젝트

프로젝트 ID 획득

모든 Google Cloud 프로젝트에서 고유한 이름인 프로젝트 ID를 기억해 두세요. 위 프로젝트 ID는 이미 사용되었으므로 사용할 수 없습니다. 나중에 이 ID를 PROJECT_ID로 제공해야 합니다.

  1. 그런 후 Google Cloud 리소스를 사용할 수 있도록 Cloud 콘솔에서 결제를 사용 설정해야 합니다.

'삭제' 섹션의 안내를 따르세요. 이 섹션에서는 이 튜토리얼을 마친 후 비용이 결제되지 않도록 리소스를 종료하는 방법을 알려줍니다 Google Cloud 새 사용자에게는 미화 $300 상당의 무료 체험판 프로그램에 참여할 수 있는 자격이 부여됩니다.

Cloud Shell 시작

노트북에서 Google를 원격으로 운영할 수도 있지만, 이 Codelab에서는 클라우드에서 실행되는 명령줄 환경인 Google Cloud Shell을 사용합니다.

Cloud Shell 활성화

  1. Cloud 콘솔에서 Cloud Shell 활성화를 클릭합니다.Cloud Shell 활성화

Cloud Shell 활성화

이전에 Cloud Shell을 시작하지 않았으면 설명이 포함된 중간 화면(스크롤해야 볼 수 있는 부분)이 제공됩니다. 이 경우 계속을 클릭합니다(이후 다시 표시되지 않음). 이 일회성 화면은 다음과 같습니다.

Cloud Shell 소개

Cloud Shell을 프로비저닝하고 연결하는 데 몇 분 정도만 걸립니다. Cloud Shell

Cloud Shell은 클라우드에 호스팅된 가상 머신에 대한 터미널 액세스를 제공합니다. 필요한 모든 개발 도구는 가상 머신에 포함되어 있습니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 크게 개선됩니다. 이 Codelab에서 대부분의 작업은 브라우저만으로도 수행할 수 있습니다.

Cloud Shell에 연결되면 인증이 완료되었고 프로젝트가 해당 프로젝트 ID로 이미 설정된 것을 확인할 수 있습니다.

  1. Cloud Shell에서 다음 명령어를 실행하여 인증되었는지 확인합니다.
gcloud auth list

명령어 결과

 Credentialed Accounts
ACTIVE  ACCOUNT
*      <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
gcloud config list project

명령어 결과

[core]
project = <PROJECT_ID>

또는 다음 명령어로 설정할 수 있습니다.

gcloud config set project <PROJECT_ID>

명령어 결과

Updated property [core/project].

3. Document AI API 사용 설정

Document AI 사용을 시작하려면 우선 API를 사용 설정해야 합니다. 이 작업은 gcloud 명령줄 인터페이스 또는 Cloud 콘솔을 사용하여 수행할 수 있습니다.

gcloud CLI 사용

  1. Cloud Shell을 사용하지 않는 경우 로컬 머신에 gcloud CLI 설치의 단계를 따릅니다.
  2. API는 다음 gcloud 명령어를 사용하여 사용 설정할 수 있습니다.
gcloud services enable documentai.googleapis.com storage.googleapis.com

다음과 같은 결과를 확인할 수 있습니다.

Operation "operations/..." finished successfully.

Cloud Console 사용

브라우저에서 Cloud 콘솔을 엽니다.

  1. 콘솔 상단의 검색창에서 'Document AI API'를 검색한 후 사용 설정을 클릭하여 Google Cloud 프로젝트에서 API를 사용합니다.

API 검색

  1. Google Cloud Storage API에 대해 앞 단계를 반복합니다.

이제 Document AI를 사용할 수 있습니다.

4. 프로세서 만들기 및 테스트

먼저 추출을 수행할 문서 OCR 프로세서의 인스턴스를 만들어야 합니다. Cloud 콘솔 또는 Processor Management API를 사용하여 이 작업을 완료할 수 있습니다.

Cloud 콘솔

  1. 콘솔에서 Document AI Platform 개요로 이동합니다.Document AI 개요 콘솔
  2. 프로세서 살펴보기를 클릭하고 문서 OCR을 선택합니다.프로세서
  3. 이름을 codelab-ocr로 지정하고(또는 다른 기억하기 쉬운 이름) 목록에서 가장 가까운 리전을 선택합니다.
  4. 만들기를 클릭하여 프로세서를 만듭니다.
  5. 프로세서 ID를 복사합니다. 나중에 코드에서 이 ID를 사용해야 합니다. 프로세서 ID

콘솔에서 문서를 업로드하여 프로세서를 테스트할 수 있습니다. 테스트 문서 업로드를 클릭하고 파싱할 문서를 선택합니다.

아래에서 소설의 처음 세 페이지를 포함하는 PDF 파일을 다운로드할 수 있습니다.

제목 페이지

출력은 다음과 같이 표시됩니다. 파싱된 책

Python 클라이언트 라이브러리

이 Codelab에 따라 Python 클라이언트 라이브러리로 Document AI 프로세서를 관리하는 방법을 알아봅니다.

Python으로 Document AI 프로세서 관리 - Codelab

5. API 요청 인증

Document AI API에 요청을 수행하려면 서비스 계정을 사용해야 합니다. 서비스 계정은 프로젝트에 속하며 Python 클라이언트 라이브러리에서 API 요청을 수행하는 데 사용합니다. 다른 사용자 계정과 마찬가지로 서비스 계정은 이메일 주소로 표현됩니다. 이 섹션에서는 Cloud SDK를 사용하여 서비스 계정을 만든 후 서비스 계정으로 인증하는 데 필요한 사용자 인증 정보를 만듭니다.

먼저 Cloud Shell을 열고 PROJECT_ID를 사용하여 이 Codelab 전체에서 사용할 환경 변수를 설정합니다.

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)

그런 후, 다음을 사용하여 Document AI API에 액세스할 새 서비스 계정을 만듭니다.

gcloud iam service-accounts create my-docai-sa \
  --display-name "my-docai-service-account"

다음으로, 프로젝트에서 Document AI 및 Cloud Storage에 액세스할 권한을 서비스 계정에 부여합니다.

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/documentai.admin"

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/storage.admin"

gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
    --member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
    --role="roles/serviceusage.serviceUsageConsumer"

다음으로, Python 코드가 새 서비스 계정으로 로그인할 때 사용하는 사용자 인증 정보를 만듭니다. 이러한 사용자 인증 정보를 만들고 다음 명령어를 사용하여 ~/key.json이라는 JSON 파일로 저장합니다.

gcloud iam service-accounts keys create ~/key.json \
  --iam-account  my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com

마지막으로, 라이브러리에서 사용자 인증 정보를 찾는 데 사용하는 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정합니다. 이러한 인증 형식에 대한 자세한 내용은 가이드를 참조하세요. 다음과 같이 앞에서 만든 사용자 인증 정보 JSON 파일의 전체 경로로 환경 변수를 설정해야 합니다.

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"

6. 클라이언트 라이브러리 설치

Document AI, Cloud Storage, Document AI 도구 상자용 Python 클라이언트 라이브러리를 설치합니다.

pip3 install --upgrade google-cloud-documentai
pip3 install --upgrade google-cloud-storage
pip3 install --upgrade google-cloud-documentai-toolbox

다음과 같은 결과를 확인할 수 있습니다.

...
Installing collected packages: google-cloud-documentai
Successfully installed google-cloud-documentai-2.15.0
.
.
Installing collected packages: google-cloud-storage
Successfully installed google-cloud-storage-2.9.0
.
.
Installing collected packages: google-cloud-documentai-toolbox
Successfully installed google-cloud-documentai-toolbox-0.6.0a0

이제 Document AI API를 사용할 준비가 되었습니다.

7. 샘플 PDF 다운로드

소설의 처음 세 페이지를 포함하는 샘플 문서가 준비되어 있습니다.

다음 링크를 사용하여 PDF를 다운로드할 수 있습니다. 그런 다음 cloudshell 인스턴스에 업로드합니다.

gsutil을 사용하여 공개 Google Cloud Storage 버킷에서 다운로드할 수도 있습니다.

gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh_3_Pages.pdf .

8. 온라인 처리 요청

이 단계에서는 온라인 처리(동기식) API를 사용하여 소설의 처음 세 페이지를 처리합니다. 이 방법은 로컬에 저장된 소규모 문서에 가장 적합합니다. 각 프로세서 유형의 최대 페이지 수와 파일 크기는 전체 프로세서 목록을 참조하세요.

Cloud Shell 편집기 또는 로컬 머신의 텍스트 편집기를 사용하여 online_processing.py 파일을 만들고 아래 코드를 사용합니다.

YOUR_PROJECT_ID, YOUR_PROJECT_LOCATION, YOUR_PROCESSOR_ID, FILE_PATH를 사용자 환경에 맞는 값으로 바꿉니다.

online_processing.py

from google.api_core.client_options import ClientOptions
from google.cloud import documentai


PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION"  # Format is 'us' or 'eu'
PROCESSOR_ID = "YOUR_PROCESSOR_ID"  # Create processor in Cloud Console

# The local file in your current working directory
FILE_PATH = "Winnie_the_Pooh_3_Pages.pdf"
# Refer to https://cloud.google.com/document-ai/docs/file-types
# for supported file types
MIME_TYPE = "application/pdf"

# Instantiates a client
docai_client = documentai.DocumentProcessorServiceClient(
    client_options=ClientOptions(api_endpoint=f"{LOCATION}-documentai.googleapis.com")
)

# 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 = docai_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 = docai_client.process_document(request=request)

document_object = result.document
print("Document processing complete.")
print(f"Text: {document_object.text}")

코드를 실행하여 텍스트를 추출하고 콘솔에 출력합니다.

샘플 문서를 사용하는 경우 다음과 같이 출력됩니다.

Document processing complete.
Text: CHAPTER I
IN WHICH We Are Introduced to
Winnie-the-Pooh and Some
Bees, and the Stories Begin
Here is Edward Bear, coming
downstairs now, bump, bump, bump, on the back
of his head, behind Christopher Robin. It is, as far
as he knows, the only way of coming downstairs,
but sometimes he feels that there really is another
way, if only he could stop bumping for a moment
and think of it. And then he feels that perhaps there
isn't. Anyhow, here he is at the bottom, and ready
to be introduced to you. Winnie-the-Pooh.
When I first heard his name, I said, just as you
are going to say, "But I thought he was a boy?"
"So did I," said Christopher Robin.
"Then you can't call him Winnie?"
"I don't."
"But you said "

...

Digitized by
Google

9. 일괄 처리 요청

이번에는 소설 전체의 텍스트를 읽고 싶다고 가정해 보겠습니다.

  • 온라인 처리에는 전송 가능한 페이지 수와 파일 크기에 제한이 있으며 API 호출당 문서 파일 하나만 허용됩니다.
  • 일괄 처리를 사용하면 큰 파일이나 여러 파일을 비동기식으로 처리할 수 있습니다.

이 단계에서는 Document AI Batch Processing API를 사용하여 '곰돌이 푸' 소설 전체를 처리하고 텍스트를 Google Cloud Storage 버킷으로 출력합니다.

일괄 처리에서는 장기 실행 작업을 사용하여 비동기식으로 요청을 관리하므로, 온라인 처리와는 다른 방식으로 요청을 수행하고 출력을 검색해야 합니다. 그러나 온라인 처리를 사용하거나 일괄 처리를 사용하거나 출력은 동일한 Document 객체 형식입니다.

이 단계에서는 Document AI에서 처리할 특정 문서를 제공하는 방법을 보여줍니다. 이후 단계에서는 전체 문서 디렉터리를 처리하는 방법을 보여줍니다.

Cloud Storage에 PDF 업로드

현재 batch_process_documents() 메서드는 Google Cloud Storage의 파일을 수용합니다. 객체 구조에 대한 자세한 내용은 documentai_v1.types.BatchProcessRequest를 참조하세요.

이 예시에서는 샘플 버킷에서 파일을 직접 읽을 수 있습니다.

gsutil을 사용하여 자체 버킷으로 파일을 복사할 수도 있습니다.

gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf gs://YOUR_BUCKET_NAME/

또는 아래 링크에서 소설의 샘플 파일을 다운로드하고 자체 버킷에 업로드할 수 있습니다.

API의 출력을 저장할 GCS 버킷도 필요합니다.

저장소 버킷을 만드는 방법은 Cloud Storage 문서를 참조하세요.

batch_process_documents() 메서드 사용

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

YOUR_PROJECT_ID, YOUR_PROCESSOR_LOCATION, YOUR_PROCESSOR_ID, YOUR_INPUT_URI, YOUR_OUTPUT_URI를 사용자 환경에 맞는 값으로 바꿉니다.

YOUR_INPUT_URI이 PDF 파일을 직접 가리키는지 확인합니다(예: gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf).

batch_processing.py

"""
Makes a Batch Processing Request to Document AI
"""

import re

from google.api_core.client_options import ClientOptions
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import RetryError
from google.cloud import documentai
from google.cloud import storage

# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID"  # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI"  # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
    "YOUR_PROCESSOR_VERSION_ID"  # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)

# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI"  # Format: `gs://bucket/directory/file.pdf` or `gs://bucket/directory/`
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber"  # Optional. The fields to return in the Document object.


def batch_process_documents(
    project_id: str,
    location: str,
    processor_id: str,
    gcs_input_uri: str,
    gcs_output_uri: str,
    processor_version_id: str = None,
    input_mime_type: str = None,
    field_mask: str = None,
    timeout: int = 400,
):
    # You must set the api_endpoint if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")

    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
        # Specify specific GCS URIs to process individual documents
        gcs_document = documentai.GcsDocument(
            gcs_uri=gcs_input_uri, mime_type=input_mime_type
        )
        # Load GCS Input URI into a List of document files
        gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
        input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
    else:
        # Specify a GCS URI Prefix to process an entire directory
        gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
        input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)

    # Cloud Storage URI for the Output Directory
    gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
        gcs_uri=gcs_output_uri, field_mask=field_mask
    )

    # Where to write results
    output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)

    if processor_version_id:
        # The full resource name of the processor version, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
        name = client.processor_version_path(
            project_id, location, processor_id, processor_version_id
        )
    else:
        # The full resource name of the processor, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}
        name = client.processor_path(project_id, location, processor_id)

    request = documentai.BatchProcessRequest(
        name=name,
        input_documents=input_config,
        document_output_config=output_config,
    )

    # BatchProcess returns a Long Running Operation (LRO)
    operation = client.batch_process_documents(request)

    # Continually polls the operation until it is complete.
    # This could take some time for larger files
    # Format: projects/{project_id}/locations/{location}/operations/{operation_id}
    try:
        print(f"Waiting for operation {operation.operation.name} to complete...")
        operation.result(timeout=timeout)
    # Catch exception when operation doesn"t finish before timeout
    except (RetryError, InternalServerError) as e:
        print(e.message)

    # NOTE: Can also use callbacks for asynchronous processing
    #
    # def my_callback(future):
    #   result = future.result()
    #
    # operation.add_done_callback(my_callback)

    # Once the operation is complete,
    # get output document information from operation metadata
    metadata = documentai.BatchProcessMetadata(operation.metadata)

    if metadata.state != documentai.BatchProcessMetadata.State.SUCCEEDED:
        raise ValueError(f"Batch Process Failed: {metadata.state_message}")

    storage_client = storage.Client()

    print("Output files:")
    # One process per Input Document
    for process in list(metadata.individual_process_statuses):
        # output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/INPUT_FILE_NUMBER/
        # The Cloud Storage API requires the bucket name and URI prefix separately
        matches = re.match(r"gs://(.*?)/(.*)", process.output_gcs_destination)
        if not matches:
            print(
                "Could not parse output GCS destination:",
                process.output_gcs_destination,
            )
            continue

        output_bucket, output_prefix = matches.groups()

        # Get List of Document Objects from the Output Bucket
        output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix)

        # Document AI may output multiple JSON files per source file
        for blob in output_blobs:
            # Document AI should only output JSON files to GCS
            if blob.content_type != "application/json":
                print(
                    f"Skipping non-supported file: {blob.name} - Mimetype: {blob.content_type}"
                )
                continue

            # Download JSON File as bytes object and convert to Document Object
            print(f"Fetching {blob.name}")
            document = documentai.Document.from_json(
                blob.download_as_bytes(), ignore_unknown_fields=True
            )

            # For a full list of Document object attributes, please reference this page:
            # https://cloud.google.com/python/docs/reference/documentai/latest/google.cloud.documentai_v1.types.Document

            # Read the text recognition output from the processor
            print("The document contains the following text:")
            print(document.text)


if __name__ == "__main__":
    batch_process_documents(
        project_id=project_id,
        location=location,
        processor_id=processor_id,
        gcs_input_uri=gcs_input_uri,
        gcs_output_uri=gcs_output_uri,
        input_mime_type=input_mime_type,
        field_mask=field_mask,
    )

코드를 실행하면 전체 소설 텍스트가 추출되어 콘솔에 출력되어야 합니다.

이전 샘플보다 파일이 훨씬 크므로 완료되는 데 다소 시간이 걸릴 수 있습니다. 잠시 기다려 주세요.

그러나 Batch Processing API는 작업이 완료된 후 GCS에서 출력을 가져오는 데 사용할 수 있는 작업 ID를 제공합니다.

다음과 비슷한 결과가 표시됩니다.

Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete...
Document processing complete.
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-0.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-1.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-10.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-11.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-12.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-13.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-14.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-15.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-16.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-17.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-18.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-2.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-3.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-4.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-5.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-6.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-7.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-8.json
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-9.json

This is a reproduction of a library book that was digitized
by Google as part of an ongoing effort to preserve the
information in books and make it universally accessible.
TM
Google books
https://books.google.com

.....

He nodded and went
out ... and in a moment
I heard Winnie-the-Pooh
-bump, bump, bump-go-ing up the stairs behind
him.
Digitized by
Google

10. 디렉터리 일괄 처리 요청

각 문서를 개별적으로 나열하지 않고 문서 디렉터리 전체를 처리해야 하는 경우도 있습니다. batch_process_documents() 메서드는 특정 문서 목록이나 디렉터리 경로를 입력하는 방법을 지원합니다.

이 단계에서는 문서 파일의 전체 디렉터리를 처리하는 방법을 보여줍니다. 대부분의 코드는 이전 단계와 동일하게 작동하며 BatchProcessRequest와 함께 전송되는 GCS URI만 다릅니다.

샘플 버킷에는 소설의 여러 페이지를 별도의 파일로 포함하는 디렉터리가 있습니다.

  • gs://cloud-samples-data/documentai/codelabs/ocr/multi-document/

파일을 직접 읽을 수도 있고 자체 Cloud Storage 버킷으로 복사할 수도 있습니다.

이전 단계의 코드를 다시 실행하여 YOUR_INPUT_URI을 Cloud Storage의 디렉터리로 바꿉니다.

코드를 실행하면 Cloud Storage 디렉터리의 모든 문서 파일에서 추출한 텍스트가 표시되어야 합니다.

다음과 비슷한 결과가 표시됩니다.

Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete...
Document processing complete.
Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh_Page_0-0.json
Fetching docai-output/OPERATION_NUMBER/1/Winnie_the_Pooh_Page_1-0.json
Fetching docai-output/OPERATION_NUMBER/2/Winnie_the_Pooh_Page_10-0.json
Fetching docai-output/OPERATION_NUMBER/3/Winnie_the_Pooh_Page_12-0.json
Fetching docai-output/OPERATION_NUMBER/4/Winnie_the_Pooh_Page_16-0.json
Fetching docai-output/OPERATION_NUMBER/5/Winnie_the_Pooh_Page_7-0.json

Introduction
(I₂
F YOU happen to have read another
book about Christopher Robin, you may remember
th
CHAPTER I
IN WHICH We Are Introduced to
Winnie-the-Pooh and Some
Bees, and the Stories Begin
HERE is
10
WINNIE-THE-POOH
"I wonder if you've got such a thing as a balloon
about you?"
"A balloon?"
"Yes, 
12
WINNIE-THE-POOH
and you took your gun with you, just in case, as
you always did, and Winnie-the-P
16
WINNIE-THE-POOH
this song, and one bee sat down on the nose of the
cloud for a moment, and then g
WE ARE INTRODUCED
7
"Oh, help!" said Pooh, as he dropped ten feet on
the branch below him.
"If only 

11. Document AI 도구 상자로 일괄 처리 응답 처리

일괄 처리는 Cloud Storage와의 통합으로 인해 꽤 많은 단계를 거쳐야 합니다. Document 출력은 '샤딩'될 수도 있습니다. 여러 .json 파일로 변환합니다.

Document AI 도구 상자 Python SDK는 Document AI를 사용한 후처리 및 기타 일반적인 작업을 간소화하기 위해 만들어졌습니다. 이 라이브러리는 Document AI 클라이언트 라이브러리를 대체하기 위한 것이 아니라 보완하기 위한 것입니다. 전체 사양은 참조 문서에서 확인하세요.

이 단계에서는 Document AI 도구 상자를 사용하여 일괄 처리 요청을 하고 출력을 검색하는 방법을 보여줍니다.

batch_processing_toolbox.py

"""
Makes a Batch Processing Request to Document AI using Document AI Toolbox
"""

from google.api_core.client_options import ClientOptions
from google.cloud import documentai
from google.cloud import documentai_toolbox

# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID"  # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI"  # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
    "YOUR_PROCESSOR_VERSION_ID"  # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)

# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI"  # Format: `gs://bucket/directory/file.pdf`` or `gs://bucket/directory/``
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber"  # Optional. The fields to return in the Document object.


def batch_process_toolbox(
    project_id: str,
    location: str,
    processor_id: str,
    gcs_input_uri: str,
    gcs_output_uri: str,
    processor_version_id: str = None,
    input_mime_type: str = None,
    field_mask: str = None,
):
    # You must set the api_endpoint if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")

    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
        # Specify specific GCS URIs to process individual documents
        gcs_document = documentai.GcsDocument(
            gcs_uri=gcs_input_uri, mime_type=input_mime_type
        )
        # Load GCS Input URI into a List of document files
        gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
        input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
    else:
        # Specify a GCS URI Prefix to process an entire directory
        gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
        input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)

    # Cloud Storage URI for the Output Directory
    gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
        gcs_uri=gcs_output_uri, field_mask=field_mask
    )

    # Where to write results
    output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)

    if processor_version_id:
        # The full resource name of the processor version, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
        name = client.processor_version_path(
            project_id, location, processor_id, processor_version_id
        )
    else:
        # The full resource name of the processor, e.g.:
        # projects/{project_id}/locations/{location}/processors/{processor_id}
        name = client.processor_path(project_id, location, processor_id)

    request = documentai.BatchProcessRequest(
        name=name,
        input_documents=input_config,
        document_output_config=output_config,
    )

    # BatchProcess returns a Long Running Operation (LRO)
    operation = client.batch_process_documents(request)

    # Operation Name Format: projects/{project_id}/locations/{location}/operations/{operation_id}
    documents = documentai_toolbox.document.Document.from_batch_process_operation(
        location=location, operation_name=operation.operation.name
    )

    for document in documents:
        # Read the text recognition output from the processor
        print("The document contains the following text:")
        # Truncated at 100 characters for brevity
        print(document.text[:100])


if __name__ == "__main__":
    batch_process_toolbox(
        project_id=project_id,
        location=location,
        processor_id=processor_id,
        gcs_input_uri=gcs_input_uri,
        gcs_output_uri=gcs_output_uri,
        input_mime_type=input_mime_type,
        field_mask=field_mask,
    )

12. 축하합니다

Document AI를 사용하여 온라인 처리, 일괄 처리, Document AI 도구 상자를 사용하여 소설에서 텍스트를 추출했습니다.

다른 문서로도 실험해 보고 플랫폼에서 제공하는 다른 프로세서도 사용해 보시기 바랍니다.

삭제

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

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

자세히 알아보기

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

리소스

라이선스

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