Оптическое распознавание символов (OCR) с помощью Document AI (Python)

1. Обзор

Что такое Document AI?

Document AI – это решение для распознавания документов, которое принимает неструктурированные данные (например, документы, электронные письма, счета, формы и т. д.) и упрощает их понимание, анализ и использование. API позволяет структурировать данные с помощью классификации контента, извлечения объектов, расширенного поиска и других функций.

На этой лабораторной работе вы узнаете, как выполнять оптическое распознавание символов с помощью Document AI API и Python.

Мы будем использовать PDF-файл классического романа "Винни-Пух" А.А. Милна, который недавно стал частью общественного достояния в США. Этот файл был отсканирован и оцифрован Google Книгами.

Что вы узнаете

  • Как включить Document AI API
  • Как выполнять аутентификацию запросов к API
  • Как установить клиентскую библиотеку для Python
  • Как использовать API для онлайн- и пакетной обработки
  • Как извлечь текст из PDF-файла

Что вам понадобится

  • Проект Google Cloud.
  • Браузер, например Chrome или Firefox.
  • Знание Python (3.9+).

Опрос

Как вы будете использовать это руководство?

Прочитаю Прочитаю и выполню упражнения

Как бы вы оценили свой опыт работы с Python?

Новичок Средний уровень Профессионал

Как бы вы оценили свой опыт использования сервисов Google Cloud?

Начинающий Средний Продвинутый

2. Настройка и требования

Самостоятельная настройка среды

  1. Войдите в Cloud Console и создайте новый проект или используйте существующий. Если у вас нет аккаунта Gmail или Google Workspace, создайте его.

Выбрать проект

Новый проект

Как получить идентификатор проекта

Запомните идентификатор проекта, уникальный для всех облачных проектов Google Cloud. (Идентификатор проекта, указанный выше, уже занят и не будет работать у вас). Этот идентификатор нужно будет указать в качестве значения параметра PROJECT_ID.

  1. Затем включите платежи в Cloud Console, чтобы использовать ресурсы Google Cloud.

Обязательно следуйте инструкциям в разделе "Очистка". В этом разделе рассказывается, как отключить ресурсы, чтобы не платить за них после завершения работы с руководством. Новые пользователи Google Cloud могут воспользоваться бесплатной пробной версией с бонусом в размере 300 долларов США.

Запустите Cloud Shell

Хотя вы можете управлять Google Cloud удаленно со своего ноутбука, в этой практической работе используется Google Cloud Shell – среда командной строки, работающая в облаке.

Активировать Cloud Shell

  1. В Cloud Console нажмите Activate Cloud Shell (Активировать Cloud Shell) Активировать Cloud Shell.

Активировать Cloud Shell

Если вы никогда не запускали Cloud Shell, то увидите промежуточный экран с описанием этого инструмента (в нижней части страницы). Нажмите Continue (Продолжить) (и вы больше никогда его не увидите). Вот как выглядит этот экран:

Общие сведения о Cloud Shell

Инициализация и подключение к Cloud Shell займет всего несколько минут. Cloud Shell

Cloud Shell предоставляет доступ к терминалу виртуальной машины, размещенной в облаке. На виртуальной машине есть все необходимые инструменты разработки. Она предлагает постоянный домашний каталог объемом 5 ГБ и работает в Google Cloud, что значительно повышает производительность сети и аутентификацию. Большую часть работы, если не всю, в этой практической работе можно выполнить в браузере.

После подключения к Cloud Shell вы увидите, что аутентификация уже выполнена и для проекта задан ваш идентификатор проекта.

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

Как использовать интерфейс командной строки gcloud

  1. Если вы не используете Cloud Shell, следуйте инструкциям в статье Как установить gcloud CLI на локальном компьютере.
  2. API можно включить с помощью следующих команд gcloud.
gcloud services enable documentai.googleapis.com storage.googleapis.com

Вы увидите примерно следующее:

Operation "operations/..." finished successfully.

Как использовать Cloud Console

Откройте Cloud Console в браузере.

  1. В строке поиска в верхней части консоли введите "Document AI API" и нажмите Включить, чтобы использовать API в облачном проекте Google Cloud.

Search API

  1. Повторите предыдущий шаг для Google Cloud Storage API.

Теперь вы можете использовать Document AI.

4. Создание и тестирование процессора

Сначала необходимо создать экземпляр процессора Document OCR, который будет выполнять извлечение. Это можно сделать в Cloud Console или с помощью Processor Management API.

Cloud Console

  1. В консоли перейдите на страницу Document AI Platform Overview (Обзор платформы Document AI).Консоль обзора Document AI
  2. Нажмите Explore Processors (Посмотреть процессоры) и выберите Document OCR (Оптическое распознавание символов в документах).Процессоры
  3. Укажите название codelab-ocr (или другое, которое вы запомните) и выберите ближайший регион из списка.
  4. Нажмите Create (Создать).
  5. Скопируйте идентификатор обработчика. Его нужно будет добавить в код. Идентификатор обработчика

Вы можете протестировать процессор в консоли, загрузив документ. Нажмите Upload Test Document (Загрузить тестовый документ) и выберите документ для анализа.

Вы можете скачать PDF-файл ниже, в котором содержатся первые три страницы нашего романа.

Титульный лист

Выходные данные должны выглядеть так: Обработанная книга

Клиентская библиотека Python

Пройдите практическую работу, чтобы узнать, как управлять обработчиками Document AI с помощью клиентской библиотеки Python.

Управление обработчиками Document AI с помощью Python – практическая работа

5. Аутентификация запросов к API

Чтобы отправлять запросы к Document AI API, необходимо использовать сервисный аккаунт. Сервисный аккаунт принадлежит вашему проекту и используется клиентской библиотекой Python для отправки запросов к API. Как и у любого другого аккаунта пользователя, у сервисного аккаунта есть адрес электронной почты. В этом разделе вы будете использовать Cloud SDK, чтобы создать сервисный аккаунт, а затем создать учетные данные, необходимые для аутентификации в качестве сервисного аккаунта.

Сначала откройте Cloud Shell и задайте переменную среды с вашим PROJECT_ID, которую вы будете использовать в этой практической работе:

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 будет использовать для входа в новый сервисный аккаунт. Создайте эти учетные данные и сохраните их в виде файла JSON ~/key.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. Установите клиентскую библиотеку

Установите клиентские библиотеки Python для Document AI, Cloud Storage и Document AI Toolbox:

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-файл по ссылке ниже. Затем загрузите его в экземпляр Cloud Shell.

Вы также можете скачать его из нашего общедоступного сегмента Google Cloud Storage с помощью gsutil.

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

8. Как отправить онлайн-запрос на обработку данных

На этом шаге вы обработаете первые три страницы романа с помощью API для онлайн-обработки (синхронного). Этот способ лучше всего подходит для небольших документов, хранящихся локально. Ознакомьтесь с полным списком процессоров, чтобы узнать максимальное количество страниц и размер файла для каждого типа процессора.

Создайте файл с названием online_processing.py в редакторе Cloud Shell или текстовом редакторе на локальном компьютере и добавьте в него код, приведенный ниже.

Замените 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 /_p/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 определенные документы для обработки. На следующем шаге будет показано, как обработать весь каталог документов.

Загрузка PDF-файла в Cloud Storage

В настоящее время метод 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/

или скачайте образец файла романа по ссылке ниже и загрузите его в свой сегмент.

Вам также понадобится сегмент GCS для хранения выходных данных API.

Инструкции по созданию сегментов хранилища приведены в документации по 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:
            # /_p/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 после завершения задачи.

Выходные данные должны выглядеть примерно так:

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
/_p/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() поддерживает ввод списка определенных документов или пути к каталогу.

На этом шаге мы покажем, как обработать целый каталог файлов документов. Большая часть кода работает так же, как и на предыдущем шаге. Единственное отличие – URI GCS, отправленный с помощью BatchProcessRequest.

В нашем примере корзины есть каталог, содержащий несколько страниц романа в отдельных файлах.

  • 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 Toolbox

Пакетная обработка требует выполнения нескольких шагов из-за интеграции с Cloud Storage. Выходные данные Document также могут быть разделены на несколько файлов .json в зависимости от размера входного документа.

Document AI Toolbox – это Python SDK, созданный для упрощения постобработки и других распространенных задач в Document AI. Эта библиотека предназначена для дополнения клиентской библиотеки Document AI, а не для ее замены. Полная спецификация приведена в справочной документации.

В этом разделе рассказывается, как создать запрос на пакетную обработку и получить выходные данные с помощью Document AI Toolbox.

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

Рекомендуем вам поэкспериментировать с другими документами и изучить другие процессоры, доступные на платформе.

Очистить

Чтобы избежать списания средств с вашего аккаунта Google Cloud за ресурсы, используемые в этом руководстве:

  • В Cloud Console перейдите на страницу Manage resources (Управление ресурсами).
  • В списке проектов выберите нужный и нажмите "Удалить".
  • В диалоговом окне введите идентификатор проекта и нажмите "Отключить", чтобы удалить проект.

Подробнее…

Продолжайте изучать Document AI с помощью этих практических работ.

Полезные ресурсы

Лицензия

Эта работа лицензирована в соответствии с лицензией Creative Commons Attribution 2.0 Generic.