1. Обзор
Что такое ИИ документов?
Document AI — это решение для понимания документов, которое принимает неструктурированные данные (например, документы, электронные письма, счета, формы и т. д.) и упрощает понимание, анализ и использование данных. API обеспечивает структуру посредством классификации контента, извлечения сущностей, расширенного поиска и многого другого.
В этой лабораторной работе вы узнаете, как выполнять оптическое распознавание символов с помощью API Document AI с Python.
Мы будем использовать PDF-файл классического романа А. А. Милна «Винни-Пух», который недавно стал частью общественного достояния в США. Этот файл был отсканирован и оцифрован Google Books .
Что вы узнаете
- Как включить API документов AI
- Как аутентифицировать запросы API
- Как установить клиентскую библиотеку для Python
- Как использовать API онлайн- и пакетной обработки
- Как проанализировать текст из PDF-файла
Что вам понадобится
Опрос
Как вы будете использовать этот урок?
Как бы вы оценили свой опыт работы с Python?
Как бы вы оценили свой опыт использования сервисов Google Cloud?
2. Настройка и требования
Самостоятельная настройка среды
- Войдите в Cloud Console и создайте новый проект или повторно используйте существующий. (Если у вас еще нет учетной записи Gmail или Google Workspace, вам необходимо ее создать .)
Запомните идентификатор проекта — уникальное имя для всех проектов Google Cloud. (Идентификатор проекта, указанный выше, уже занят и не подойдет вам, извините!). Вы должны предоставить этот идентификатор позже как PROJECT_ID
.
- Затем вам необходимо включить биллинг в Cloud Console, чтобы использовать ресурсы Google Cloud.
Обязательно следуйте инструкциям в разделе «Очистка». В этом разделе рассказывается, как отключить ресурсы, чтобы вам не приходилось нести расходы за пределами этого руководства. Новые пользователи Google Cloud имеют право на участие в программе бесплатной пробной версии стоимостью 300 долларов США .
Запустить Cloud Shell
Хотя Google Cloud вы можете управлять Google Cloud удаленно со своего ноутбука, в этой лаборатории кода используется Google Cloud Shell , среда командной строки, работающая в облаке.
Активировать Cloud Shell
- В Cloud Console нажмите «Активировать Cloud Shell».
Если вы никогда раньше не запускали Cloud Shell, вам будет представлен промежуточный экран (ниже сгиба), описывающий, что это такое. В этом случае нажмите «Продолжить» (и вы больше никогда этого не увидите). Вот как выглядит этот одноразовый экран:
Подготовка и подключение к Cloud Shell займет всего несколько минут.
Cloud Shell предоставляет вам терминальный доступ к виртуальной машине, размещенной в облаке. Виртуальная машина включает в себя все необходимые инструменты разработки. Он предлагает постоянный домашний каталог объемом 5 ГБ и работает в Google Cloud, что значительно повышает производительность сети и аутентификацию. Большую часть, если не всю, работу в этой лаборатории кода можно выполнить с помощью простого браузера.
После подключения к Cloud Shell вы увидите, что вы уже прошли аутентификацию и что для проекта уже установлен ваш идентификатор проекта.
- Выполните следующую команду в 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. Включите API документа AI.
Прежде чем вы сможете начать использовать Document AI, вам необходимо включить API. Это можно сделать с помощью интерфейса командной строки gcloud
или облачной консоли.
Используйте интерфейс командной строки gcloud
- Если вы не используете Cloud Shell , выполните действия, описанные в разделе Установка интерфейса командной строки
gcloud
на локальный компьютер. - API можно включить с помощью следующих команд
gcloud
.
gcloud services enable documentai.googleapis.com storage.googleapis.com
Вы должны увидеть что-то вроде этого:
Operation "operations/..." finished successfully.
Используйте облачную консоль
Откройте облачную консоль в браузере.
- Используя панель поиска в верхней части консоли, найдите «Document AI API», затем нажмите « Включить», чтобы использовать API в своем проекте Google Cloud.
- Повторите предыдущий шаг для API Google Cloud Storage.
Теперь вы можете использовать Document AI!
4. Создайте и протестируйте процессор
Сначала необходимо создать экземпляр процессора распознавания документов, который будет выполнять извлечение. Это можно выполнить с помощью Cloud Console или API управления процессором .
Облачная консоль
- В консоли перейдите к обзору платформы Document AI Platform.
- Нажмите «Изучить процессоры» и выберите «Распознавание текста документа».
- Дайте ему имя
codelab-ocr
(или другое имя, которое вы запомните) и выберите ближайший регион в списке. - Нажмите «Создать» , чтобы создать свой процессор.
- Скопируйте идентификатор процессора. Вы должны будете использовать это в своем коде позже.
Вы можете протестировать свой процессор в консоли, загрузив документ. Нажмите «Загрузить тестовый документ» и выберите документ для анализа.
Ниже вы можете скачать PDF-файл, содержащий первые 3 страницы нашего романа.
Ваш вывод должен выглядеть так:
Клиентская библиотека Python
Следуйте этой кодовой лаборатории, чтобы узнать, как управлять процессорами Document AI с помощью клиентской библиотеки Python:
Управление процессорами искусственного интеллекта документов с помощью Python — Codelab
5. Аутентификация запросов API
Чтобы отправлять запросы к API Document AI, вы должны использовать учетную запись службы . Учетная запись службы принадлежит вашему проекту и используется клиентской библиотекой Python для выполнения запросов API. Как и любая другая учетная запись пользователя, учетная запись службы представлена адресом электронной почты. В этом разделе вы будете использовать Cloud SDK для создания учетной записи службы, а затем создадите учетные данные, необходимые для аутентификации в качестве учетной записи службы.
Сначала откройте Cloud Shell и установите переменную среды со своим PROJECT_ID
, которую вы будете использовать в этой лаборатории кода:
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)
Затем создайте новую учетную запись службы для доступа к API Document AI, используя:
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
Теперь вы готовы использовать API Document AI!
7. Загрузите образец PDF-файла.
У нас есть образец документа, который содержит первые 3 страницы романа.
Скачать PDF-файл можно по следующей ссылке. Затем загрузите его в экземпляр CloudShell .
Вы также можете загрузить его из нашей общедоступной корзины облачного хранилища Google с помощью gsutil
.
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.
- Пакетная обработка позволяет обрабатывать большие/множественные файлы асинхронным методом.
На этом этапе мы обработаем весь роман «Винни-Пух» с помощью API пакетной обработки документов AI и выведем текст в корзину облачного хранилища Google.
Пакетная обработка использует длительные операции для асинхронного управления запросами, поэтому нам приходится выполнять запрос и получать выходные данные другим способом, чем онлайн-обработка. Однако выходные данные будут в том же формате объекта Document
, независимо от того, используется ли онлайн-обработка или пакетная обработка.
На этом этапе показано, как предоставить конкретные документы для обработки Document AI. Следующий шаг покажет, как обрабатывать весь каталог документов.
Загрузить 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/
...или вы можете скачать образец файла романа по ссылке ниже и загрузить его в свою корзину .
Вам также понадобится сегмент GCS для хранения результатов API.
Вы можете ознакомиться с документацией по облачному хранилищу, чтобы узнать, как создавать сегменты хранилища .
Использование метода 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
.
пакетная_обработка.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,
)
Запустите код, и вы увидите полный текст романа, извлеченный и напечатанный в вашей консоли.
Это может занять некоторое время, поскольку файл намного больше, чем в предыдущем примере. (Ой, заморачивайтесь...)
Однако с помощью 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 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()
поддерживает ввод списка конкретных документов или пути к каталогу.
На этом шаге будет показано, как обработать полный каталог файлов документов. Большая часть кода работает так же, как и предыдущий шаг, с той лишь разницей, что 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
Пакетная обработка требует довольно много шагов из-за интеграции с облачным хранилищем. Вывод Document
также может быть «разделен» на несколько файлов .json
в зависимости от размера входного документа.
Document AI Toolbox Python SDK был создан для упрощения постобработки и других распространенных задач с Document AI. Эта библиотека предназначена для дополнения клиентской библиотеки Document AI, а не для ее замены. Полную спецификацию можно найти в справочной документации .
На этом шаге показано, как выполнить запрос на пакетную обработку и получить выходные данные с помощью Document AI Toolbox.
пакетная_обработка_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 Console перейдите на страницу «Управление ресурсами» .
- В списке проектов выберите свой проект и нажмите «Удалить».
- В диалоговом окне введите идентификатор проекта и нажмите «Завершить работу», чтобы удалить проект.
Узнать больше
Продолжайте изучать Document AI на следующих курсах Codelabs.
- Анализ формы с помощью Document AI (Python)
- Специализированные процессоры с искусственным интеллектом документов (Python)
- Управление процессорами искусственного интеллекта для документов с помощью Python
- Документ AI: Человек в курсе
Ресурсы
- Будущее документов – Плейлист YouTube
- Документация по ИИ
- Документ Клиентская библиотека AI Python
- Хранилище образцов документов AI
Лицензия
Эта работа распространяется под лицензией Creative Commons Attribution 2.0 Generic License.