提取不支持的文档异常



我正在尝试使用 boto3 来运行 textract detect_document_text请求。

我正在使用以下代码:

client = boto3.client('textract')
response = client.detect_document_text(
Document={
'Bytes': image_b64['document_b64']
}
)

其中image_b64['document_b64']是我使用的示例 https://base64.guru/converter/encode/image 网站转换的base64图像代码。

但是我收到以下错误:

UnsupportedDocumentException

我做错了什么?

每个文档:

如果您使用 AWS 开发工具包调用 Amazon Textract,则可能不需要对使用 Bytes 字段传递的图像字节进行 base64 编码。

仅当直接调用 REST API 时才需要 Base64 编码。使用 Python 或 NodeJS SDK 时,请使用本机字节(二进制字节(。

为了将来参考,我使用以下方法解决了这个问题:

client = boto3.client('textract')
image_64_decode = base64.b64decode(image_b64['document_b64']) 
bytes = bytearray(image_64_decode)
response = client.detect_document_text(
Document={
'Bytes': bytes
}
)

使用 Boto3 如果您使用 Jupyternotebook 作为图像(.jpg 或 .png(,您可以使用:

import boto3
import cv2 
with open(images_path, "rb") as img_file:
img_str = bytearray(img_file.read())
textract = boto3.client('textract')
response = textract.detect_document_text(Document={'Bytes': img_str})  

这对我有用。它假定您已使用 aws 凭证配置 ~/.aws

import boto3
import os
def main():
client = boto3.client('textract', region_name="ca-central-1")
for imageFile in os.listdir('./img'):
image_file = f"./imgs/{imageFile}"
with open(image_file, "rb") as f:
response = client.analyze_expense(
Document={
'Bytes': f.read(),
'S3Object': {
'Bucket': 'REDACTED',
'Name': imageFile,
'Version': '1'
}
})
print(response)
if __name__ == "__main__":
main()

最新更新