使用Google Document AI Python SDK处理JPEG时遭遇两类错误求助
解决Google Document AI OCR处理JPEG时的错误
问题分析
- 初始错误
ValueError: Unknown field for ProcessRequest: document_type:原示例代码针对PDF可能默认添加了document_type字段,但处理图片时该字段属于多余参数,会被API拒绝。 - 后续
OSError: [Errno 63] File name too long:错误地将base64编码后的字符串传给了file_path参数,该参数要求传入本地文件路径而非编码内容,导致系统把超长字符串识别为文件名报错。
正确解决方案
Google Document AI的Python客户端库支持直接传入图片文件路径,无需手动做base64编码。只需确保构造请求时不添加多余的document_type字段,直接传递图片路径即可。
修正后的完整代码示例
from google.cloud import documentai_v1 as documentai def process_document_sample( project_id: str, location: str, processor_id: str, file_path: str, ): # 初始化客户端 client = documentai.DocumentProcessorServiceClient() # 构建处理器名称 name = client.processor_path(project_id, location, processor_id) # 读取本地图片文件内容 with open(file_path, "rb") as image_file: content = image_file.read() # 构造文档对象,无需指定document_type(图片类型会被自动识别) document = documentai.Document(content=content) request = documentai.ProcessRequest(name=name, document=document) # 发送请求并获取识别结果 result = client.process_document(request=request) print("处理完成,识别文本:") print(result.document.text) # 调用函数,直接传入JPEG文件路径 process_document_sample( project_id="99999FAKE", location="us", processor_id="99999FAKE", file_path="merged_images/fake.jpeg" )
关键说明
- 无需手动base64编码:Python客户端库会自动处理文件内容的编码和传输逻辑,直接传入本地文件路径即可。
- 移除
document_type字段:处理图片时不需要指定该参数,API会自动检测文件类型,原示例中若有相关设置需删除。
内容的提问来源于stack exchange,提问作者Hack-R
相关产品推荐
相关产品推荐

