表单识别器自定义模型失败,文件类型无效`{“错误”:{“代码”:“1000”,“消息”:“输入文件无效”。}`

2024-09-24 22:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地训练了一个用于键值提取的自定义模型,但是我用于评估模型的任何文件或文件类型都无法返回结果。到目前为止,我已经尝试了pdf和png文件

我已经匹配了the API docs中提供的查询来创建我的查询,但仍然失败,有什么建议吗

import requests
import json
import os
import pathlib

# path of file to evaluate
floc = 'path/to/file'

# extract file type
file_type = pathlib.Path(floc).suffix[1:]

# set headers with file type and our api key
headers = {
    'Content-Type': f'application/{file_type}',
    'Ocp-Apim-Subscription-Key': os.environ["AZURE_FORM_RECOGNIZER_KEY"]
}

# read in the file as binary to send
files = {'file': open(floc, 'rb')}

# post the file to be analysed
r = requests.post(
    f'https://eastus.api.cognitive.microsoft.com/formrecognizer/v2.1/custom/models/{os.environ["MODEL_ID"]}/analyze',
    headers=headers,
    files=files
)

r

结果是400,出现以下错误:

{"error":{"code":"1000","message":"Invalid input file."}}

使用layout/analyze请求的一个非常类似的查询可以完美地工作。我也读过this question,它有同样的错误,但来自cURL,但没有帮助


Tags: 文件thetopath模型importapios
1条回答
网友
1楼 · 发布于 2024-09-24 22:20:53

我已经解决了我的问题,但将把我的答案留给其他人

有两个主要问题:

修复程序如下所示:

import requests
import json
import os
import pathlib

# path of file to evaluate
floc = 'path/to/file'

# extract file type
file_type = pathlib.Path(floc).suffix[1:]

# set headers with file type and our api key
headers = {
    'Content-Type': f'application/{file_type}',
    'Ocp-Apim-Subscription-Key': os.environ["AZURE_FORM_RECOGNIZER_KEY"]
}

# post the file to be analysed
r = requests.post(
    f'{endpoint}/formrecognizer/v2.1/custom/models/{os.environ["MODEL_ID"]}/analyze',
    headers=headers, 
    data=open(floc, 'rb') # send binary of your file
)

r

通过转到表单识别器的Azure实例,您可以找到自己的endpoint值:

Form recognizer instance info

相关问题 更多 >