You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI接收图片字节调用Nougat OCR接口报错求助

问题解决步骤

第一步:修正FastAPI接口定义

你的接口错误地将图片字节设为query参数,这不符合二进制数据的传输规范。正确做法是用File接收上传的图片:

from fastapi import FastAPI, File
from nougat import NougatModel  # 按实际Nougat导入方式调整

app = FastAPI()

@app.post("/predict-from-image/")
async def predict_from_image(img_bytes: bytes = File(...)):
    # 调用Nougat模型处理图片字节
    model = NougatModel.from_pretrained("facebook/nougat-base")
    markdown_result = model.predict(img_bytes)
    return {"markdown": markdown_result}

第二步:修正客户端请求代码

你之前误用了query参数(requests库中没有这个参数),二进制图片应该通过files参数传递:

客户端代码示例(截屏+请求)

import requests
from PIL import ImageGrab
import io

# 截取指定屏幕区域
screen_img = ImageGrab.grab(bbox=(100, 100, 600, 600))  # 自定义区域坐标

# 将图片转为字节流
img_byte_stream = io.BytesIO()
screen_img.save(img_byte_stream, format='PNG')
img_byte_stream.seek(0)

# 发送POST请求
session = requests.Session()
response = session.post(
    "http://localhost:8000/predict-from-image/",
    files={"img_bytes": ("screenshot.png", img_byte_stream, "image/png")}
)

# 处理响应
if response.status_code == 200:
    print("转换结果:\n", response.json()["markdown"])
else:
    print(f"请求失败: {response.status_code}\n{response.text}")

错误原因说明

  • 422错误:接口定义要求query参数img_bytes,但二进制图片不适合通过query传递(会被URL编码且长度受限),客户端无法正确传递参数导致报错。
  • TypeError错误:requests.Session.request()不存在query参数,二进制文件上传需用files参数对应multipart/form-data格式,这是文件传输的标准方式。

内容的提问来源于stack exchange,提问作者HankY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:42:12