Document AI (Python) ile Optik Karakter Tanıma (OCR)

1. Genel Bakış

Document AI nedir?

Document AI, yapılandırılmamış verileri (ör. belgeler, e-postalar, faturalar, formlar) alıp verilerin anlaşılmasını, analiz edilmesini ve kullanılmasını kolaylaştıran bir belge anlama çözümüdür. API; içerik sınıflandırma, varlık çıkarma, gelişmiş arama ve daha fazlasıyla yapı sağlar.

Bu laboratuvarda, Python ile Document AI API'yi kullanarak optik karakter tanıma işlemi gerçekleştirmeyi öğreneceksiniz.

"Winnie the Pooh" adlı klasik romanın PDF dosyasını kullanırız Oluşturan: A.A. Kısa süre önce ABD'de Kamu Alanı kapsamına giren Milne. Bu dosya Google Kitaplar tarafından tarandı ve dijitalleştirildi.

Neler öğreneceksiniz?

  • Document AI API'yi etkinleştirme
  • API isteklerinin kimliğini doğrulama
  • Python için istemci kitaplığını yükleme
  • Online ve toplu işlem API'lerinin nasıl kullanılacağı
  • PDF dosyasındaki metin nasıl ayrıştırılır?

Gerekenler

  • Bir Google Cloud projesi
  • Chrome veya Firefox gibi bir tarayıcı
  • Python (3.9+) kullanımı hakkında bilgi

Anket

Bu eğiticiden nasıl yararlanacaksınız?

Yalnızca okuma Okuyun ve alıştırmaları tamamlayın

Python deneyiminizi nasıl değerlendirirsiniz?

Acemi Orta Yeterli

Google Cloud hizmetlerini kullanma deneyiminizi nasıl değerlendirirsiniz?

Acemi Orta Yeterli

2. Kurulum ve Gereksinimler

Kendi hızınızda ortam kurulumu

  1. Cloud Console'da oturum açıp yeni bir proje oluşturun veya mevcut bir projeyi yeniden kullanın. (Gmail veya Google Workspace hesabınız yoksa hesap oluşturmanız gerekir.)

Proje Seç

Yeni Proje

Proje Kimliği Alma

Tüm Google Cloud projelerinin benzersiz bir adı olan Proje Kimliği'ni unutmayın. (Yukarıdaki proje kimliği daha önce alınmış ve maalesef sizin için uygun olmayacaktır!). Bu kimliği daha sonra PROJECT_ID olarak sağlamanız gerekir.

  1. Ardından, Google Cloud kaynaklarını kullanmak için Cloud Console'da faturalandırmayı etkinleştirmeniz gerekir.

"Temizleme" bölümündeki talimatları izlediğinizden emin olun. bölümüne bakın. Bu bölümde, bu eğitim haricinde faturalandırmayla karşılaşmamanız için kaynakları nasıl kapatacağınız açıklanmaktadır. Yeni Google Cloud kullanıcıları 300 ABD doları ücretsiz deneme programından yararlanabilir.

Cloud Shell'i başlatma

Google Cloud'u dizüstü bilgisayarınızdan uzaktan çalıştırabilirsiniz. Bu codelab'de ise Cloud'da çalışan bir komut satırı ortamı olan Google Cloud Shell kullanılır.

Cloud Shell'i etkinleştirme

  1. Cloud Console'da, Cloud Shell'i etkinleştir 'i Cloud Shell'i etkinleştirme tıklayın.

Cloud Shell'i etkinleştirme

Cloud Shell'i daha önce hiç başlatmadıysanız ne olduğunu açıklayan bir ara ekran (ekranın alt kısmı) gösterilir. Bu durumda Devam'ı tıklayın (bunu bir daha görmezsiniz). Tek seferlik ekran şöyle görünür:

Cloud Shell'e Giriş

Temel hazırlık ve Cloud Shell'e bağlanmak yalnızca birkaç dakika sürer. Cloud Shell.

Cloud Shell, bulutta barındırılan bir sanal makineye terminal erişimi sağlar. Sanal makine, ihtiyacınız olan tüm geliştirme araçlarını içerir. 5 GB boyutunda kalıcı bir ana dizin sunar ve Google Cloud'da çalışarak ağ performansını ve kimlik doğrulamasını büyük ölçüde iyileştirir. Bu codelab'deki çalışmalarınızın tamamı olmasa da büyük bir kısmı yalnızca bir tarayıcıyla yapılabilir.

Cloud Shell'e bağlandıktan sonra kimliğinizin doğrulandığını ve projenin proje kimliğinize ayarlandığını görürsünüz.

  1. Kimlik doğrulamanızın tamamlandığını onaylamak için Cloud Shell'de aşağıdaki komutu çalıştırın:
gcloud auth list

Komut çıkışı

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

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

Komut çıkışı

[core]
project = <PROJECT_ID>

Doğru değilse aşağıdaki komutla ayarlayabilirsiniz:

gcloud config set project <PROJECT_ID>

Komut çıkışı

Updated property [core/project].

3. Document AI API'yi etkinleştirme

Document AI'yı kullanmaya başlamadan önce API'yi etkinleştirmeniz gerekir. Bu işlemi gcloud komut satırı arayüzünü veya Cloud Console'u kullanarak yapabilirsiniz.

gcloud KSA'yı kullan

  1. Cloud Shell kullanmıyorsanız yerel makinenize gcloud KSA'yı yükleme bölümündeki adımları uygulayın.
  2. API'ler aşağıdaki gcloud komutları kullanılarak etkinleştirilebilir.
gcloud services enable documentai.googleapis.com storage.googleapis.com

Aşağıdakine benzer bir tablo görürsünüz:

Operation "operations/..." finished successfully.

Cloud Console'u kullanma

Tarayıcınızda Cloud Console'u açın.

  1. Konsolun üst kısmındaki arama çubuğunu kullanarak "Document AI API"yi aratın, ardından Etkinleştir'i tıklayarak API'yi Google Cloud projenizde kullanın

Search API

  1. Google Cloud Storage API için önceki adımı tekrarlayın.

Artık Document AI'ı kullanabilirsiniz.

4. İşleyen Oluşturma ve Test Etme

Öncelikle ayıklama işlemini gerçekleştirecek olan Document OCR işlemcisinin bir örneğini oluşturmanız gerekir. Bu işlem, Cloud Console veya Processor Management API kullanılarak tamamlanabilir.

Cloud Console

  1. Konsolda Document AI Platformuna Genel Bakış'a gidinDocument AI Genel Bakış Konsolu
  2. İşlemcileri Keşfet'i tıklayın ve Belge OCR'yi seçin.İşlemciler
  3. Hedefe codelab-ocr adını (veya hatırlayacağınız başka bir ad) verin ve listeden en yakın bölgeyi seçin.
  4. İşleyicinizi oluşturmak için Oluştur'u tıklayın.
  5. İşlemci kimliğinizi kopyalayın. Bunu daha sonra kodunuzda kullanmanız gerekir. İşlemci Kimliği.

Bir belge yükleyerek konsolda işlemcinizi test edebilirsiniz. Test Dokümanı Yükle'yi tıklayın ve ayrıştırılacak bir doküman seçin.

Romanımızın ilk 3 sayfasını içeren PDF dosyasını aşağıdan indirebilirsiniz.

Başlık Sayfası

Çıkışınız şu şekilde görünmelidir: Ayrıştırılmış Kitap

Python İstemci Kitaplığı

Document AI işlemcilerini Python İstemci Kitaplığı ile nasıl yöneteceğinizi öğrenmek için şu codelab'i takip edin:

Python ile Document AI işlemcilerini yönetme - Codelab

5. API isteklerinin kimliğini doğrulama

Document AI API'ye istek göndermek için Hizmet Hesabı kullanmanız gerekir. Hizmet Hesabı projenize aittir ve Python istemci kitaplığı tarafından API istekleri yapmak için kullanılır. Diğer tüm kullanıcı hesapları gibi hizmet hesabı da e-posta adresiyle temsil edilir. Bu bölümde Google Cloud SDK'yı kullanarak bir hizmet hesabı oluşturacaksınız. Ardından, hizmet hesabı olarak kimliğinizi doğrulamak için ihtiyacınız olan kimlik bilgilerini oluşturacaksınız.

Öncelikle Cloud Shell'i açın ve bu codelab boyunca kullanacağınız PROJECT_ID ile bir ortam değişkeni ayarlayın:

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

Ardından, aşağıdakileri kullanarak Document AI API'ye erişmek için yeni bir hizmet hesabı oluşturun:

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

Ardından, hizmet hesabınıza projenizdeki Document AI ve Cloud Storage'a erişim izni verin.

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"

Ardından, Python kodunuzun yeni hizmet hesabınız olarak giriş yapmak için kullandığı kimlik bilgilerini oluşturun. Bu kimlik bilgilerini oluşturun ve aşağıdaki komutu kullanarak JSON dosyası olarak ~/key.json kaydedin:

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

Son olarak, kitaplık tarafından kimlik bilgilerinizi bulmak için kullanılan GOOGLE_APPLICATION_CREDENTIALS ortam değişkenini ayarlayın. Bu kimlik doğrulama biçimi hakkında daha fazla bilgi edinmek için kılavuza bakın. Ortam değişkeninin, oluşturduğunuz kimlik bilgisi JSON dosyasının tam yoluna şu şekilde ayarlanması gerekir:

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

6. İstemci kitaplığını yükleme

Document AI, Cloud Storage ve Document AI Araç Kutusu için Python istemci kitaplıklarını yükleyin:

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

Aşağıdakine benzer bir tablo görürsünüz:

...
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

Artık Document AI API'yi kullanmaya hazırsınız.

7. Örnek PDF'yi İndirin

Romanın ilk 3 sayfasını içeren örnek bir belgemiz var.

PDF dosyasını aşağıdaki bağlantıyı kullanarak indirebilirsiniz. Daha sonra, bunu Cloud Shell örneğine yükleyin.

Ayrıca, gsutil kullanarak herkese açık Google Cloud Storage paketimizden de indirebilirsiniz.

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

8. Online İşleme İsteğinde Bulunma

Bu adımda online transaction (eşzamanlı) API'sini kullanarak romanın ilk 3 sayfasını işleyeceksiniz. Bu yöntem, yerel olarak depolanan daha küçük dokümanlar için uygundur. Her işlemci türü için maksimum sayfa sayısı ve dosya boyutu hakkında bilgi edinmek için tam işlemci listesine göz atın.

online_processing.py adlı bir dosya oluşturmak için Cloud Shell Düzenleyici'yi veya yerel makinenizdeki bir metin düzenleyiciyi kullanın ve aşağıdaki kodu kullanın.

YOUR_PROJECT_ID, YOUR_PROJECT_LOCATION, YOUR_PROCESSOR_ID ve FILE_PATH değerlerini ortamınıza uygun değerlerle değiştirin.

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}")

Kodu çalıştırarak metni ayıklayın ve konsola yazdırın.

Örnek dokümanımızı kullandığınızda aşağıdaki çıkışı görürsünüz:

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. Toplu İşleme İsteğinde Bulunma

Şimdi, romanın tamamının metnini okumak istediğinizi varsayalım.

  • Online İşleme, gönderilebilecek sayfa sayısı ve dosya boyutuyla ilgili sınırlara sahiptir ve API çağrısı başına yalnızca bir belge dosyasına izin verir.
  • Toplu İşleme, daha büyük/birden çok dosyanın eşzamansız bir yöntemle işlenmesine olanak tanır.

Bu adımda, "Winnie the Pooh" reklam öğesinin tamamını işleyeceğiz. Document AI Batch Processing API ile yenilendi ve metni bir Google Cloud Storage Paketine dönüştürdü.

Toplu işlem, istekleri eşzamansız bir şekilde yönetmek için Uzun Süreli İşlemler'i kullanır. Bu nedenle, istekte bulunmamız ve sonucu, online işlemeden farklı bir şekilde almamız gerekir. Ancak, online veya toplu işlem kullanılırken çıkış aynı Document nesne biçiminde olur.

Bu adımda, Document AI'ın işlemesi için belirli belgelerin nasıl sağlanacağı gösterilmektedir. Daha sonraki bir adımda, bir doküman dizininin tamamının nasıl işleneceği gösterilecektir.

PDF'yi Cloud Storage'a yükleyin

batch_process_documents() yöntemi şu anda Google Cloud Storage'daki dosyaları kabul etmektedir. Nesne yapısı hakkında daha fazla bilgi için documentai_v1.types.BatchProcessRequest sayfasına başvurabilirsiniz.

Bu örnekte, dosyayı doğrudan örnek paketimizden okuyabilirsiniz.

Dosyayı gsutil kullanarak da kendi paketinize kopyalayabilirsiniz...

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

...veya aşağıdaki bağlantıdan romanın örnek dosyasını indirip kendi paketinize yükleyebilirsiniz.

Ayrıca, API çıkışını depolamak için bir GCS Paketine ihtiyacınız olacaktır.

Depolama alanı paketleri oluşturmayı öğrenmek için Cloud Storage belgelerini inceleyebilirsiniz.

batch_process_documents() yöntemini kullanma

batch_processing.py adında bir dosya oluşturun ve aşağıdaki kodu kullanın.

YOUR_PROJECT_ID, YOUR_PROCESSOR_LOCATION, YOUR_PROCESSOR_ID, YOUR_INPUT_URI ve YOUR_OUTPUT_URI değerlerini ortamınıza uygun değerlerle değiştirin.

YOUR_INPUT_URI değerinin doğrudan PDF dosyasına yönlendirdiğinden emin olun (örneğin, 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,
    )

Kodu çalıştırdığınızda, yeni metnin tam olarak çıkarılıp konsolunuzda yazdırıldığını görürsünüz.

Dosya önceki örnekten çok daha büyük olduğundan bu işlemin tamamlanması biraz zaman alabilir. (Yok artık...)

Ancak Batch Processing API ile GCS'den çıktı almak için kullanabileceğiniz bir İşlem Kimliği alırsınız.

Çıkışınız aşağıdaki gibi görünecektir:

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. Bir dizin için Toplu İşleme İsteği yapma

Bazen, her bir dokümanı ayrı ayrı listelemeden, bir doküman dizininin tamamını işlemek isteyebilirsiniz. batch_process_documents() yöntemi, belirli dokümanlar listesinin veya dizin yolunun girişini destekler.

Bu adımda, belge dosyalarının tam dizininin nasıl işleneceği gösterilir. Kodun çoğu, önceki adımla aynı şekilde çalışır. Tek fark, BatchProcessRequest ile birlikte gönderilen GCS URI'sidir.

Örnek paketimizde romanın birden çok sayfasını ayrı dosyalarda içeren bir dizin var.

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

Dosyaları doğrudan okuyabilir veya kendi Cloud Storage paketinize kopyalayabilirsiniz.

Önceki adımdaki kodu (YOUR_INPUT_URI) Cloud Storage'daki bir dizinle değiştirerek tekrar çalıştırın.

Kodu çalıştırdığınızda, ayıklanan metni Cloud Storage dizininde tüm belge dosyalarından görürsünüz.

Çıkışınız aşağıdaki gibi görünecektir:

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 Araç Kutusu ile Toplu İşleme Yanıtını İşleme

Cloud Storage ile entegrasyon nedeniyle, toplu işlem için birkaç adımın tamamlanması gerekir. Document çıkışı da "parçalanmış" olabilir giriş dokümanının boyutuna bağlı olarak birden çok .json dosyasına gönderebilirsiniz.

Document AI Araç Kutusu Python SDK'sı, Document AI ile işleme sonunu ve diğer yaygın görevleri basitleştirmek için oluşturulmuştur. Bu kitaplık, Document AI istemci kitaplığının yerini alması değil, ek olarak kullanılması amaçlanmıştır. Tüm özellikler için referans belgelerine göz atın.

Bu adımda, toplu işleme isteğinin nasıl yapılacağı ve Document AI Araç Kutusu'nu kullanarak sonucun nasıl alınacağı gösterilmektedir.

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. Tebrikler

Online İşleme, Toplu İşleme ve Document AI Araç Kutusu'ndan yararlanarak bir romandan metin çıkarmak için Document AI'ı başarıyla kullandınız.

Diğer belgelerle denemeler yapmanızı ve platformdaki diğer işleyenleri keşfetmenizi öneririz.

Temizleme

Bu eğiticide kullanılan kaynaklar için Google Cloud hesabınızın ücretlendirilmesini önlemek amacıyla:

  • Cloud Console'da Kaynakları yönetin sayfasına gidin.
  • Proje listesinden projenizi seçin ve ardından Sil'i tıklayın.
  • İletişim kutusuna proje kimliğini yazın ve projeyi silmek için Kapat'ı tıklayın.

Daha Fazla Bilgi

Takip eden Codelab uygulamaları ile Document AI hakkında bilgi edinmeye devam edin.

Kaynaklar

Lisans

Bu çalışma, Creative Commons Attribution 2.0 Genel Amaçlı Lisans ile lisans altına alınmıştır.