python DocumentAI Document对象的.proto文件

fruv7luv  于 2023-03-21  发布在  Python
关注(0)|答案(2)|浏览(133)

我正在使用DocumentAI API,并希望序列化/反序列化Document对象
https://cloud.google.com/python/docs/reference/documentai-toolbox/latest/google.cloud.documentai_toolbox.wrappers.document.Document
在开发时保存API调用。我想我应该使用Protocol Buffers,但我必须自己编写.proto文件吗?它不是在某个地方可用吗?我使用Python。

oo7oh9g9

oo7oh9g91#

Google为其支持REST/gRPC的服务发布了interface definitions(protos):

在这个仓库中,Google的服务库合并一个更高级别的REST抽象**和一个更低级别的gRPC实现。
因此,如果您使用Google的Python SDK for DocumentAI,则可能已经生成了例如Document的Python存根,并且是SDK的一部分,您可以利用这些存根。或者,您可以使用protoc为自己生成存根,尽管这有点麻烦,因为您需要正确配置--proto_path才能访问import的protos。
假设您已经(稀疏 checkout )googleapis/googleapis并且位于克隆的根目录中:

.
├── google
│   └── cloud
│       └── documentai
│           └── v1beta3
└── protoc-22.2-linux-x86_64
    ├── bin
    └── include

然后,您可以使用以下命令为document.proto生成Python存根。存根将位于document.proto源代码旁边:

protoc \
--proto_path=${PWD} \
--python_out=${PWD} \
--pyi_out=${PWD} \
${PWD}/google/cloud/documentai/v1beta3/document.proto

一旦你有了Protobuf消息,你可以使用SerializeToString或者文本格式来MessageToString

注意SerializeToString序列化为binary格式,下面是使用它的示例。

toiithl6

toiithl62#

好的,“序列化”是指将Document对象保存为JSON还是实际的.proto文件或二进制文件?
在使用Document AI API和客户端库(如Python)时,可以使用Document.to_json()方法将Document proto保存为文件的JSON字符串。
注意:如果您使用批处理而不是在线处理,则结果将在Google Cloud Storage中的JSON文件中。
联机处理示例:

from google.cloud import documentai

client = documentai.DocumentProcessorServiceClient()

# Create Processing Request
# Refer to https://cloud.google.com/document-ai/docs/send-request

# Send Processing Request
result = client.process_document(request=request)

# Serialize the Document Proto to JSON
json_string = Document.to_json(result.document, including_default_value_fields=False)

# Write JSON String to File
with open(json_file, "w") as outfile:
    outfile.write(json_string)

此外,您在帖子中链接的文档是针对Document AI Toolbox的,这是一个用于文档AI的附加Python SDK,具有用于预处理和后处理的辅助函数,旨在与文档AI结合使用。
以下是有关在由Document AI处理的文档上使用Document AI Toolbox的信息。
https://cloud.google.com/document-ai/docs/handle-response#toolbox

相关问题