如何通过Python客户端使用Document AI本地处理一批文件?

问题描述 投票:0回答:1

我正在尝试使用Python控制台使用文档OCR处理器在本地处理大量pdf文档(本机和扫描)以提取文本和一些元数据。文档存储在多个文件夹和子文件夹中。我目前有一个工作代码可以在本地同步地逐一处理文档,但由于存在 文档超过 15 页,我不得不切换到批处理。我希望使用批处理在本地上传批量文件,然后在本地处理并存储结果。这是我的进口:

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

我的documentai模块的版本是2.20.1。

我正在使用 Spyder IDE 5.4.3 和 Python 3.11.4。

总体思路是遍历一些列表(file_paths),其中包含各个文档的路径,然后将它们一一打开并创建对象,其中包含 pdf 和 mime_type。然后,根据某种逻辑,使用这些对象来构造批次。但我不确定它应该是哪个对象。 ChatGPT 建议如下:

batch_input_config = documentai.types.BatchProcessRequest.Types.BatchInputConfig(

代码的相关部分:

# Create a list to hold BatchInputConfig objects for each document
batch_input_configs = []

for file_path in file_paths:
    with open(file_path, 'rb') as image:
        content = image.read()

    # Create a BatchInputConfig object for each document
    batch_input_config = documentai.types.BatchProcessRequest.Types.BatchInputConfig(
        content=content,
        mime_type='application/pdf'
    )

    # Some logic for the batch construction is left out here
    # Add the ProcessRequest object to the batch_request list
        batch_input_configs.append(batch_input_config)

但这会引发错误:“AttributeError:模块‘google.cloud.documentai’没有属性‘类型’”

batch_input_config = documentai.types.BatchProcessRequest.Types.BatchInputConfig(
线。我检查了在线示例和文档,一切似乎都使用 Google Cloud Storage 来存储文档甚至结果。

我确信使用 GCS 有优势,但如果文件和结果可以存储在本地而不涉及 GCS,那就更好了。因为一切都是以本地化为基础的。具体来说,我需要将文件路径和文档名称附加到其相应的结果中。并且可以在本地使用同步代码,因此我希望批处理也能实现相同的效果...

所以我的问题是:是否可以使用documentai在本地处理批量文档? (如果是,如何?使用哪个对象或解决方法?)

请原谅任何明显的错误,我是第一次使用文档。任何帮助将不胜感激,谢谢!

我尝试过几个对象,例如:

documentai.types.Document
documentai.types.BatchProcessRequest.Types.BatchInputConfig
documentai.BatchDocumentsInputConfig

我尝试更新我的 documentai 模块并将导入指定为:

from google.cloud import documentai_v1beta3 as documentai

我也尝试过多次打扰ChatGPT,但到目前为止还没有成功。

即使解决方法是让代码将文件上传到 GCS,在那里处理它们,然后下载结果,我想也可以。

python google-cloud-platform google-cloud-storage ocr cloud-document-ai
1个回答
0
投票

ChatGPT 的代码不准确。要一次批量处理多个文件,您需要将文档上传到Google Cloud Storage,然后您可以使用此处的代码示例来执行批处理。

https://cloud.google.com/document-ai/docs/send-request#batch-process

© www.soinside.com 2019 - 2024. All rights reserved.