实验设置说明和要求
保护您的账号和进度。请务必在无痕浏览器窗口中,使用实验凭证运行此实验。

使用 Document AI 进行光学字符识别 (OCR) (Python)

实验 1 小时 universal_currency_alt 5 个点数 show_chart 中级
info 此实验可能会提供 AI 工具来支持您学习。
此内容尚未针对移动设备进行优化。
为获得最佳体验,请在桌面设备上访问通过电子邮件发送的链接。

GSP1138

Google Cloud 自学实验的徽标

概览

Document AI 是一款文档智能解析解决方案,能够处理非结构化数据(如文档、邮件、账单、表单等),让数据更易于理解、分析和使用。Document AI API 通过内容分类、实体提取、高级搜索等功能,实现对数据的结构化处理。

在本实验中,您将使用 Document AI 和 Python 对 PDF 文档执行光学字符识别 (OCR) 操作,并探索如何发出在线(同步)和批量(异步)处理请求。

我们将使用 A.A. Milne 的经典小说《小熊维尼》的 PDF 文件,该书近期已在美国进入公共领域。此文件由 Google 图书扫描并数字化处理。

目标

在本实验中,您将学习如何执行以下任务:

  • 启用 Document AI API
  • 对 API 请求进行身份验证
  • 安装 Python 版客户端库
  • 使用在线处理 API 和批处理 API
  • 解析 PDF 文件中的文本

设置和要求

点击“开始实验”按钮前的注意事项

请阅读以下说明。实验是计时的,并且您无法暂停实验。计时器在您点击开始实验后即开始计时,显示 Google Cloud 资源可供您使用多长时间。

此实操实验可让您在真实的云环境中开展实验活动,免受模拟或演示环境的局限。为此,我们会向您提供新的临时凭据,您可以在该实验的规定时间内通过此凭据登录和访问 Google Cloud。

为完成此实验,您需要:

  • 能够使用标准的互联网浏览器(建议使用 Chrome 浏览器)。
注意:请使用无痕模式(推荐)或无痕浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。
  • 完成实验的时间 - 请注意,实验开始后无法暂停。
注意:请仅使用学生账号完成本实验。如果您使用其他 Google Cloud 账号,则可能会向该账号收取费用。

如何开始实验并登录 Google Cloud 控制台

  1. 点击开始实验按钮。如果该实验需要付费,系统会打开一个对话框供您选择支付方式。左侧是“实验详细信息”窗格,其中包含以下各项:

    • “打开 Google Cloud 控制台”按钮
    • 剩余时间
    • 进行该实验时必须使用的临时凭据
    • 帮助您逐步完成本实验所需的其他信息(如果需要)
  2. 点击打开 Google Cloud 控制台(如果您使用的是 Chrome 浏览器,请右键点击并选择在无痕式窗口中打开链接)。

    该实验会启动资源并打开另一个标签页,显示“登录”页面。

    提示:将这些标签页安排在不同的窗口中,并排显示。

    注意:如果您看见选择账号对话框,请点击使用其他账号
  3. 如有必要,请复制下方的用户名,然后将其粘贴到登录对话框中。

    {{{user_0.username | "<用户名>"}}}

    您也可以在“实验详细信息”窗格中找到“用户名”。

  4. 点击下一步

  5. 复制下面的密码,然后将其粘贴到欢迎对话框中。

    {{{user_0.password | "<密码>"}}}

    您也可以在“实验详细信息”窗格中找到“密码”。

  6. 点击下一步

    重要提示:您必须使用实验提供的凭据。请勿使用您的 Google Cloud 账号凭据。 注意:在本实验中使用您自己的 Google Cloud 账号可能会产生额外费用。
  7. 继续在后续页面中点击以完成相应操作:

    • 接受条款及条件。
    • 由于这是临时账号,请勿添加账号恢复选项或双重验证。
    • 请勿注册免费试用。

片刻之后,系统会在此标签页中打开 Google Cloud 控制台。

注意:如需访问 Google Cloud 产品和服务,请点击导航菜单,或在搜索字段中输入服务或产品的名称。 “导航菜单”图标和“搜索”字段

激活 Cloud Shell

Cloud Shell 是一种装有开发者工具的虚拟机。它提供了一个永久性的 5GB 主目录,并且在 Google Cloud 上运行。Cloud Shell 提供可用于访问您的 Google Cloud 资源的命令行工具。

  1. 点击 Google Cloud 控制台顶部的激活 Cloud Shell “激活 Cloud Shell”图标

  2. 在弹出的窗口中执行以下操作:

    • 继续完成 Cloud Shell 信息窗口中的设置。
    • 授权 Cloud Shell 使用您的凭据进行 Google Cloud API 调用。

如果您连接成功,即表示您已通过身份验证,且项目 ID 会被设为您的 Project_ID 。输出内容中有一行说明了此会话的 Project_ID

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud 是 Google Cloud 的命令行工具。它已预先安装在 Cloud Shell 上,且支持 Tab 自动补全功能。

  1. (可选)您可以通过此命令列出活跃账号名称:
gcloud auth list
  1. 点击授权

输出:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (可选)您可以通过此命令列出项目 ID:
gcloud config list project

输出:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} 注意:如需查看在 Google Cloud 中使用 gcloud 的完整文档,请参阅 gcloud CLI 概览指南

任务 1. 启用 Document AI API

您必须先启用 Document AI API,然后才能开始使用 Document AI。

  1. 通过控制台顶部的搜索栏搜索“Document AI API”,然后点击启用,以便在您的 Google Cloud 项目中使用该 API。

搜索 API

  1. 使用搜索栏搜索“Cloud Storage API”,如果该 API 尚未启用,请点击启用

  2. 或者,您也可以使用以下 gcloud 命令启用这些 API。

gcloud services enable documentai.googleapis.com gcloud services enable storage.googleapis.com

您应会看到类似下图的界面:

Operation "operations/..." finished successfully.

现在,您可以使用 Document AI 了!

点击检查我的进度以验证是否完成了以下目标: 启用 Document AI API

任务 2. 创建并测试处理器

您需要先创建一个 Document OCR 处理器实例,用于执行文本提取操作。这可以通过 Cloud 控制台或 Processor Management API 完成。

  1. 在导航菜单中,点击查看所有产品。在人工智能下,选择 Document AI

Document AI 概览控制台

  1. 点击探索处理器,然后点击 Document OCR

处理器

  1. 将处理器命名为 lab-ocr,并从列表中选择距离最近的区域。

  2. 点击创建以创建处理器。

  3. 复制处理器 ID。您稍后在代码中会用到该 ID。

处理器 ID

  1. 下载下面的 PDF 文件,该文件包含 A.A. Milne 的小说《小熊维尼》的前 3 页。

现在,您可以在控制台中上传文档来测试处理器。

  1. 点击上传测试文档,然后选择您下载的 PDF 文件。

输出应如下所示:

解析后的图书内容

点击检查我的进度以验证是否完成了以下目标: 创建并测试处理器

任务 3. 对 API 请求进行身份验证

如需向 Document AI API 发出请求,您必须使用服务账号服务账号属于您的项目,Python 客户端库会使用它来发出 API 请求。与其他用户账号一样,服务账号也通过邮箱表示。在本部分中,您将使用 Cloud SDK 创建服务账号,然后创建该服务账号进行身份验证所需的凭证。

  1. 首先,打开一个新的 Cloud Shell 窗口,然后运行以下命令,将环境变量设置为您的项目 ID:
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)
  1. 接下来,使用以下命令创建一个新的服务账号来访问 Document AI API:
gcloud iam service-accounts create my-docai-sa \ --display-name "my-docai-service-account"
  1. 使用以下命令向您的服务账号授予访问 Document AI、Cloud Storage 和 Service Usage 的权限:
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"
  1. 创建 Python 代码以新服务账号身份登录所用的凭证。请使用以下命令创建这些凭证并将其保存为 JSON 文件 ~/key.json
gcloud iam service-accounts keys create ~/key.json \ --iam-account my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com
  1. 最后,设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量,供库用来查找您的凭证。该环境变量应设为您之前创建的 JSON 凭证文件的完整路径,具体命令如下:
export GOOGLE_APPLICATION_CREDENTIALS=$(realpath key.json)

如需详细了解此身份验证形式,请参阅指南

点击检查我的进度以验证是否完成了以下目标: 对 API 请求进行身份验证

任务 4. 安装客户端库

  1. 在 Cloud Shell 中运行以下命令,以安装 Document AI 和 Cloud Storage 的 Python 客户端库。
pip3 install --upgrade google-cloud-documentai pip3 install --upgrade google-cloud-storage

您应会看到类似下图的界面:

... Installing collected packages: google-cloud-documentai Successfully installed google-cloud-documentai-1.4.1 . . Installing collected packages: google-cloud-storage Successfully installed google-cloud-storage-1.43.0

现在,您可以使用 Document AI API 了!

注意:如果您要设置自己的 Python 开发环境,可以遵循这些准则

将示例 PDF 上传到 Cloud Shell

  1. 在 Cloud Shell 工具栏中,点击三点状图标,然后选择上传

  2. 依次选择文件 > 选择文件,然后选择您之前下载的 3 页 PDF 文件。

  3. 点击上传

  4. 或者,您也可以使用 gcloud storage cp 从公共 Google Cloud Storage 存储桶下载该 PDF。

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

任务 5. 发出在线处理请求

在此步骤中,您将使用在线处理(同步)API 处理上述小说的前 3 页。此方法最适用于本地存储的小型文档。如需了解每种处理器类型支持的最大页数和文件大小,请参阅完整处理器列表

  1. 在 Cloud Shell 中,创建一个名为 online_processing.py 的文件,并将以下代码粘贴到其中:
from google.api_core.client_options import ClientOptions from google.cloud import documentai_v1 as 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}")
  1. 根据您的环境,将 YOUR_PROJECT_IDYOUR_PROJECT_LOCATIONYOUR_PROCESSOR_IDFILE_PATH 替换为相应值。
注意:FILE_PATH 是您在上一步中上传到 Cloud Shell 的文件的名称。如果您未重命名该文件,则文件名称应为 Winnie_the_Pooh_3_Pages.pdf,这是默认值,无需更改。
  1. 运行代码,系统会提取文本并将其输出到控制台。
python3 online_processing.py

您应该会看到以下输出内容:

Document processing complete. Text: IN WHICH We Are Introduced to CHAPTER I 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--" ...

任务 6. 发出批处理请求

现在,假设您想要读取上述整部小说中的文本。

  • 在线处理功能对可以发送的页面数和文件大小有限制,并且每次 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,详细了解对象结构。

  1. 运行以下命令,创建一个 Google Cloud Storage 存储桶来存储 PDF 文件,并将该 PDF 文件上传到该存储桶:
gcloud storage buckets create gs://$GOOGLE_CLOUD_PROJECT gcloud storage cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf gs://$GOOGLE_CLOUD_PROJECT/

使用 batch_process_documents() 方法

  1. 创建一个名为 batch_processing.py 的文件,并粘贴以下代码:
import re from typing import List from google.api_core.client_options import ClientOptions from google.cloud import documentai_v1 as documentai from google.cloud import storage PROJECT_ID = "YOUR_PROJECT_ID" LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu' PROCESSOR_ID = "YOUR_PROCESSOR_ID" # Create processor in Cloud Console # Format 'gs://input_bucket/directory/file.pdf' GCS_INPUT_URI = "gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf" INPUT_MIME_TYPE = "application/pdf" # Format 'gs://output_bucket/directory' GCS_OUTPUT_URI = "YOUR_OUTPUT_BUCKET_URI" # 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) # Cloud Storage URI for the Input Document input_document = documentai.GcsDocument( gcs_uri=GCS_INPUT_URI, mime_type=INPUT_MIME_TYPE ) # Load GCS Input URI into a List of document files input_config = documentai.BatchDocumentsInputConfig( gcs_documents=documentai.GcsDocuments(documents=[input_document]) ) # Cloud Storage URI for Output directory gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig( gcs_uri=GCS_OUTPUT_URI ) # Load GCS Output URI into OutputConfig object output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config) # Configure Process Request request = documentai.BatchProcessRequest( name=RESOURCE_NAME, input_documents=input_config, document_output_config=output_config, ) # Batch Process returns a Long Running Operation (LRO) operation = docai_client.batch_process_documents(request) # Continually polls the operation until it is complete. # This could take some time for larger files # Format: projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID print(f"Waiting for operation {operation.operation.name} to complete...") operation.result() # NOTE: Can also use callbacks for asynchronous processing # # def my_callback(future): # result = future.result() # # operation.add_done_callback(my_callback) print("Document processing complete.") # 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}") documents: List[documentai.Document] = [] # Storage Client to retrieve the output files from GCS storage_client = storage.Client() # One process per Input Document for process in metadata.individual_process_statuses: # output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/0 # The GCS API requires the bucket name and URI prefix separately output_bucket, output_prefix = re.match( r"gs://(.*?)/(.*)", process.output_gcs_destination ).groups() # Get List of Document Objects from the Output Bucket output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix) # DocAI may output multiple JSON files per source file for blob in output_blobs: # Document AI should only output JSON files to GCS if ".json" not in blob.name: print(f"Skipping non-supported file type {blob.name}") continue print(f"Fetching {blob.name}") # Download JSON File and Convert to Document Object document = documentai.Document.from_json( blob.download_as_bytes(), ignore_unknown_fields=True ) documents.append(document) # Print Text from all documents # Truncated at 100 characters for brevity for document in documents: print(document.text[:100])
  1. 根据您的环境,将 YOUR_PROJECT_IDYOUR_PROJECT_LOCATIONYOUR_PROCESSOR_IDGCS_INPUT_URIGCS_OUTPUT_URI 替换为相应值。

    • 对于 GCS_INPUT_URI,请使用您在上一步中上传到存储桶的文件的 URI,即 gs:///Winnie_the_Pooh.pdf
    • 对于 GCS_OUTPUT_URI,请使用您在上一步中创建的存储桶的 URI,即 gs://
  2. 运行代码,您应该会在控制台中看到提取和输出的完整小说文本。

python3 batch_processing.py 注意:由于该文件比上一个示例大得多,因此可能需要一段时间才能完成。不过,借助 Batch Processing API,您将收到一个操作 ID,该 ID 可用于在任务完成后从 Cloud Storage 获取输出。

输出应如下所示:

Document processing complete. Fetching 16218185426403815298/0/Winnie_the_Pooh-0.json Fetching 16218185426403815298/0/Winnie_the_Pooh-1.json Fetching 16218185426403815298/0/Winnie_the_Pooh-10.json Fetching 16218185426403815298/0/Winnie_the_Pooh-11.json Fetching 16218185426403815298/0/Winnie_the_Pooh-12.json Fetching 16218185426403815298/0/Winnie_the_Pooh-13.json Fetching 16218185426403815298/0/Winnie_the_Pooh-14.json Fetching 16218185426403815298/0/Winnie_the_Pooh-15.json .. This is a reproduction of a library book that was digitized by Google as part of an ongoing effort t 0 TAM MTAA Digitized by Google Introduction (I₂ F YOU happen to have read another book about Christo 84 Eeyore took down his right hoof from his right ear, turned round, and with great difficulty put u 94 ..

太棒了!现在,您已成功使用 Document AI Batch Processing API 从 PDF 文件中提取了文本。

点击检查我的进度以验证是否完成了以下目标: 发出批处理请求

任务 7. 对目录发出批处理请求

有时,您可能希望处理整个文档目录,而无需逐个列出每个文档。batch_process_documents() 方法支持输入特定文档列表或目录路径。

在本部分中,您将了解如何处理包含文档文件的完整目录。大部分代码与上一步中的代码相同,唯一的区别是随 BatchProcessRequest 发送的 GCS URI。

  1. 运行以下命令,将示例目录(其中包含上述小说的多个页面,每个页面为单独的文件)复制到您的 Cloud Storage 存储桶。
gsutil -m cp -r gs://cloud-samples-data/documentai/codelabs/ocr/multi-document/* gs://$GOOGLE_CLOUD_PROJECT/multi-document/

您可以直接读取这些文件,也可以将它们复制到自己的 Cloud Storage 存储桶中。

  1. 创建一个名为 batch_processing_directory.py 的文件,并粘贴以下代码:
import re from typing import List from google.api_core.client_options import ClientOptions from google.cloud import documentai_v1 as documentai from google.cloud import storage PROJECT_ID = "YOUR_PROJECT_ID" LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu' PROCESSOR_ID = "YOUR_PROCESSOR_ID" # Create processor in Cloud Console # Format 'gs://input_bucket/directory' GCS_INPUT_PREFIX = "gs://cloud-samples-data/documentai/codelabs/ocr/multi-document" # Format 'gs://output_bucket/directory' GCS_OUTPUT_URI = "YOUR_OUTPUT_BUCKET_URI" # 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) # Cloud Storage URI for the Input Directory gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=GCS_INPUT_PREFIX) # Load GCS Input URI into Batch Input Config input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix) # Cloud Storage URI for Output directory gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig( gcs_uri=GCS_OUTPUT_URI ) # Load GCS Output URI into OutputConfig object output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config) # Configure Process Request request = documentai.BatchProcessRequest( name=RESOURCE_NAME, input_documents=input_config, document_output_config=output_config, ) # Batch Process returns a Long Running Operation (LRO) operation = docai_client.batch_process_documents(request) # Continually polls the operation until it is complete. # This could take some time for larger files # Format: projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID print(f"Waiting for operation {operation.operation.name} to complete...") operation.result() # NOTE: Can also use callbacks for asynchronous processing # # def my_callback(future): # result = future.result() # # operation.add_done_callback(my_callback) print("Document processing complete.") # 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}") documents: List[documentai.Document] = [] # Storage Client to retrieve the output files from GCS storage_client = storage.Client() # One process per Input Document for process in metadata.individual_process_statuses: # output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/0 # The GCS API requires the bucket name and URI prefix separately output_bucket, output_prefix = re.match( r"gs://(.*?)/(.*)", process.output_gcs_destination ).groups() # Get List of Document Objects from the Output Bucket output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix) # DocAI may output multiple JSON files per source file for blob in output_blobs: # Document AI should only output JSON files to GCS if ".json" not in blob.name: print(f"Skipping non-supported file type {blob.name}") continue print(f"Fetching {blob.name}") # Download JSON File and Convert to Document Object document = documentai.Document.from_json( blob.download_as_bytes(), ignore_unknown_fields=True ) documents.append(document) # Print Text from all documents # Truncated at 100 characters for brevity for document in documents: print(document.text[:100])
  1. 根据您的环境,将 PROJECT_IDLOCATIONPROCESSOR_IDGCS_INPUT_PREFIXGCS_OUTPUT_URI 替换为相应值。

    • 对于 GCS_INPUT_PREFIX,请使用您在上一部分中上传到存储桶的目录的 URI,即 gs:///multi-document
    • 对于 GCS_OUTPUT_URI,请使用您在上一部分中创建的存储桶的 URI,即 gs://
  2. 使用以下命令运行代码,您应该会看到从 Cloud Storage 目录中的所有文档文件中提取的文本。

python3 batch_processing_directory.py

输出应如下所示:

Document processing complete. Fetching 16354972755137859334/0/Winnie_the_Pooh_Page_0-0.json Fetching 16354972755137859334/1/Winnie_the_Pooh_Page_1-0.json Fetching 16354972755137859334/2/Winnie_the_Pooh_Page_10-0.json .. Introduction (I₂ F YOU happen to have read another book about Christopher Robin, you may remember th IN WHICH We Are Introduced to CHAPTER I Winnie-the-Pooh and Some Bees, and the Stories Begin HERE is ..

太棒了!您已成功借助 Document AI Python 客户端库,通过 Document AI 处理器处理文档目录,并将结果输出到 Cloud Storage。

点击检查我的进度以验证是否完成了以下目标: 对目录发出批处理请求

恭喜!

恭喜!在本实验中,您学习了如何借助 Document AI Python 客户端库,通过 Document AI 处理器处理文档目录,并将结果输出到 Cloud Storage。您还了解了如何使用服务账号密钥文件对 API 请求进行身份验证、安装 Document AI Python 客户端库,以及使用在线处理(同步)和批处理(异步)API 来处理请求。

后续步骤/了解详情

请查看以下资源,详细了解 Document AI 和 Python 客户端库:

Google Cloud 培训和认证

…可帮助您充分利用 Google Cloud 技术。我们的课程会讲解各项技能与最佳实践,可帮助您迅速上手使用并继续学习更深入的知识。我们提供从基础到高级的全方位培训,并有点播、直播和虚拟三种方式选择,让您可以按照自己的日程安排学习时间。各项认证可以帮助您核实并证明您在 Google Cloud 技术方面的技能与专业知识。

上次更新手册的时间:2024 年 6 月 13 日

上次测试实验的时间:2024 年 6 月 13 日

版权所有 2025 Google LLC 保留所有权利。Google 和 Google 徽标是 Google LLC 的商标。其他所有公司名和产品名可能是其各自相关公司的商标。

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

使用无痕浏览模式

  1. 复制系统为实验提供的用户名密码
  2. 在无痕浏览模式下,点击打开控制台

登录控制台

  1. 使用您的实验凭证登录。使用其他凭证可能会导致错误或产生费用。
  2. 接受条款,并跳过恢复资源页面
  3. 除非您已完成此实验或想要重新开始,否则请勿点击结束实验,因为点击后系统会清除您的工作并移除该项目

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。