FastAPI应用程序python错误JSON不可序列化

问题描述 投票:0回答:2

我正在为这个项目使用 FastAPI 编写 API TripoSR

我现在的代码如下(我只需要这2个函数):

from fastapi import FastAPI
from gradio_app import preprocess, generate

# initialise FastAPI instance
app = FastAPI()

@app.get("/tripo-api")
def generator(input_image, do_remove_background: bool, foreground_ratio: float, mc_resolution, formats=["obj", "glb"]):
    """
    Generator function, which calls preprocessing and generating function

    Parameters:
      - input_image, data type: PIL.Image.Image
      - do_remove_background, data type: boolean
      - foreground_ratio, data type: float
    """

    # call preprocessing function with given parameters
    output_prepr = preprocess(input_image=input_image, do_remove_background=do_remove_background, foreground_ratio=foreground_ratio)

    # call generate function, based on prepocessing
    rv = generate(output_prepr, mc_resolution=mc_resolution, formats=formats)
    
    return {rv}

当我尝试调用此 api 时遇到的错误如下:

Traceback (most recent call last):
  File "C:\Users\user\TripoSR\api_test.py", line 30, in <module>
    response = requests.post(url, json=payload)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\site-packages\requests\api.py", line 115, in post
    return request("post", url, data=data, json=json, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\site-packages\requests\sessions.py", line 575, in request
    prep = self.prepare_request(req)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\site-packages\requests\sessions.py", line 486, in prepare_request
    p.prepare(
  File "C:\Python\3.11\Lib\site-packages\requests\models.py", line 371, in prepare
    self.prepare_body(data, files, json)
  File "C:\Python\3.11\Lib\site-packages\requests\models.py", line 511, in prepare_body
    body = complexjson.dumps(json, allow_nan=False)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
          ^^^^^^^^^^^
  File "C:\Python\3.11\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\json\encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "C:\Python\3.11\Lib\json\encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

我使用以下 python 代码调用 api:

import requests
from PIL import Image
import io

# API endpoint
url = "http://localhost:8000/tripo-api"

# Example input parameters
input_image = Image.open("examples\captured.jpeg")
do_remove_background = True
foreground_ratio = 0.8
mc_resolution = 512
formats = ["obj", "glb"]

# Convert the input image to bytes
img_bytes = io.BytesIO()
input_image.save(img_bytes, format='JPEG')
img_bytes = img_bytes.getvalue()

# Prepare the request payload
payload = {
    "input_image": img_bytes,
    "do_remove_background": do_remove_background,
    "foreground_ratio": foreground_ratio,
    "mc_resolution": mc_resolution,
    "formats": formats
}

# Send the POST request to the API
response = requests.post(url, json=payload)

# Check the response
if response.status_code == 200:
    print("API request successful!")
    print(response.json())
else:
    print("API request failed with status code:", response.status_code)
    print("Error message:", response.text)

这背后的想法是围绕这个项目构建一个自己的前端。为此,我需要一个 API,所以这就是我写这篇文章的原因。如果有人知道帮助,将会非常有帮助!

python artificial-intelligence fastapi
2个回答
0
投票

请求负载中的

input_image
似乎是字节数据类型。通常,在请求负载中发送图像文件时,您希望将其编码为 Base-64 格式。

input_image
进行编码并将其作为字符串发送应该可以解决您的错误。 然后,您可以在
generator
端点中解码 Base64 编码的图像文件。


0
投票

如果您正在考虑发送 JSON 有效负载中的任何文件,通常的做法是以 Base64 格式对其进行编码。然而,这种方法常常会导致字符串又长又乱,不太理想。

另一种方法可能是:

  1. 利用 FastAPI 中的专用端点,例如
    UploadFile(..)
  2. 生成图像并将其上传到云服务(例如 AWS 存储桶),然后在 JSON 响应中返回其链接。
© www.soinside.com 2019 - 2024. All rights reserved.