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

无法使用Gradio Client API进行图像预测的技术求助

使用@gradio/client调用Gradio图像API报错问题排查与解决

问题详情

尝试用@gradio/client向Gradio服务发送图像进行预测,客户端代码如下:

import { client } from "@gradio/client";

const response_0 = await fetch("https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png");
const exampleImage = await response_0.blob();
                        
const app = await client("airvit2/pet_classifier");
const result = await app.predict("/predict", [
                exampleImage,   // blob in 'img' Image component
    ]);

console.log(result.data);

执行后返回错误:

{
    "type": "status",
    "endpoint": "/predict",
    "fn_index": 0,
    "time": "2024-03-17T18:36:53.270Z",
    "queue": true,
    "message": null,
    "stage": "error",
    "success": false
}

对应的Gradio服务端代码:

from fastai.vision.all import *
import gradio as gr

learn = load_learner('model.pkl')

def predict(img):
    print("Imagem: ", img)
    img = load_image(img)
    # img = PILImage.create(img)
    pred, pred_idx, probs = learn.predict(img)
    return pred

gr.Interface(fn = predict, inputs = gr.Image(type="pil", height = 224, width = 224), outputs = gr.Label(num_top_classes = 3)).launch(share = True)

已尝试将图像转换为Blob格式,问题仍未解决。

解决方法

1. 对齐服务端输入类型与处理逻辑

服务端gr.Image指定了type="pil",但客户端传Blob时,Gradio会将其转为临时文件路径传给后端,而非直接传递PIL对象。可以两种方式调整:

  • 方式一:修改输入类型为文件路径
    把服务端的gr.Image类型改为"filepath",这样后端接收的是文件路径,load_image可直接处理:
    gr.Interface(fn = predict, inputs = gr.Image(type="filepath", height = 224, width = 224), outputs = gr.Label(num_top_classes = 3)).launch(share = True)
    
  • 方式二:直接使用传入的PIL对象
    保持type="pil",后端直接使用传入的PIL Image,无需额外转换:
    def predict(img):
        print("Imagem: ", img)
        # 直接使用传入的PIL对象
        pred, pred_idx, probs = learn.predict(img)
        return pred
    

2. 确保客户端连接正确的服务地址

客户端代码中连接的是示例模型"airvit2/pet_classifier",需替换为你自己部署的Gradio服务共享链接(启动服务后控制台会输出,格式类似https://xxxx.gradio.live):

const app = await client("你的Gradio服务共享链接");

3. 查看后端日志定位具体错误

启动服务后,观察控制台输出的"Imagem: ", img内容,确认传入的图像数据格式是否符合预期。如果是路径,检查路径有效性;如果是PIL对象,确认能否被fastai正常解析。

内容的提问来源于stack exchange,提问作者Carlos Eduardo Rocha Miranda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:45:56