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

如何让Gradio Image组件的下载按钮使用随机文件名?

自定义Gradio图片组件下载文件名的问题

我有3个gr.Image()组件,仅在LLM推理执行完成后才会输出内容,组件定义代码如下:

img1 = gr.Image(
    label="Generated Image",
    type="pil",
    format="png",
    interactive=False,
    show_share_button=False,
    elem_classes="generated-image"
)

推理API调用代码示例:

def inference_with_timer(model_key, prompt, api_key):
    API_URL = models[model_key]
    headers = {"Authorization": f"Bearer {api_key}"}
    payload = {"inputs": prompt}
    try:
        start_time = time.time()
        response = requests.post(API_URL, headers=headers, json=payload)
        response.raise_for_status()
        elapsed_time = round(time.time() - start_time, 2)
        image = Image.open(BytesIO(response.content))
        return image, f"{elapsed_time}s"
    except Exception as e:
        return str(e), "Error"

需求说明

当前gr.Image()组件的内置下载按钮默认文件名为“image.{ext}”,我需要实现每次推理完成后,下载文件名变为随机值,同时满足以下场景:

  • 首次加载页面时,所有图片块的下载按钮均不存在
  • 可能出现仅第一个图片块有下载按钮,另外两个仍无的情况
  • 三个图片块可同时拥有下载按钮
  • 首次推理后下载按钮会保留,且系统支持发起新的推理

核心要求:仅在新推理成功完成时,更新3个对应锚标签的download属性。

遇到的问题

我曾尝试使用自定义Javascript实现,但无法判断推理是否成功——即使推理失败,img标签的src属性仍会有值,例如:

<img
    src="https://mayeenulislam-imagen.hf.space/gradio_api/file=/home/user/app/500 Server Error: Internal Server Error for url: https:/api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
    alt=""
    loading="lazy"
    class="svelte-1pijsyv"
>

现寻求解决方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:03:31