推理提供商文档
使用 Gradio 和 Inference Providers 构建 AI 图像编辑器
并获得增强的文档体验
开始使用
使用 Gradio 和推理提供商构建 AI 图像编辑器
在本指南中,我们将构建一个 AI 驱动的图像编辑器,允许用户上传图像并使用自然语言提示词对其进行编辑。本项目将演示如何将推理提供商(Inference Providers)与图生图模型结合使用,例如 Qwen 的 Image Edit 和 Black Forest Labs 的 Flux Kontext。
我们的应用程序将
- 接受图像上传:通过 Web 界面上传
- 处理自然语言提示词:解析如“把猫变成老虎”之类的编辑指令
- 转换图像:使用 Qwen Image Edit 或 FLUX.1 Kontext
- 显示结果:在 Gradio 界面中展示
摘要 - 本指南将向您展示如何使用 Gradio 和推理提供商构建一个 AI 图像编辑器,就像 这个 一样。
步骤 1:设置身份验证
在开始编写代码之前,请使用您的 Token 对 Hugging Face 进行身份验证
# Get your token from https://huggingface.co/settings/tokens
export HF_TOKEN="your_token_here"本指南假定您拥有 Hugging Face 帐户。如果您没有,可以免费在 huggingface.co 上创建。
当您设置此环境变量后,它将为您所有的推理调用自动处理身份验证。您可以从 您的设置页面 生成 Token。
步骤 2:项目设置
创建一个新的项目目录并使用 uv 进行初始化
mkdir image-editor-app
cd image-editor-app
uv init这将创建一个包含 pyproject.toml 文件的基础项目结构。现在添加所需的依赖项
uv add huggingface-hub>=0.34.4 gradio>=5.0.0 pillow>=11.3.0
依赖项现已安装并准备就绪!此外,当您添加依赖项时,uv 会为您维护 pyproject.toml 文件。
我们使用
uv是因为它是一个快速的 Python 包管理器,可以自动处理依赖解析和虚拟环境管理。它比 pip 快得多,并提供更好的依赖解析。如果您不熟悉uv,可以在 这里 查看。
步骤 3:构建核心图像编辑函数
现在让我们为应用程序创建主要逻辑——一个使用 AI 转换图像的图像编辑函数。
创建 main.py,然后导入必要的库并实例化 InferenceClient。我们使用 fal-ai 提供商来实现快速图像处理,但也可以使用 replicate 等其他提供商。
import os
import gradio as gr
from huggingface_hub import InferenceClient
import io
# Initialize the client with fal-ai provider for fast image processing
client = InferenceClient(
provider="fal-ai",
api_key=os.environ["HF_TOKEN"],
)现在让我们创建图像编辑函数。该函数接收输入图像和提示词,并返回编辑后的图像。我们还希望优雅地处理错误,如果发生错误则返回原始图像,这样我们的 UI 始终能显示内容。
def edit_image(input_image, prompt):
"""
Edit an image using the given prompt.
Args:
input_image: PIL Image object from Gradio
prompt: String prompt for image editing
Returns:
PIL Image object (edited image)
"""
if input_image is None:
return None
if not prompt or prompt.strip() == "":
return input_image
try:
# Convert PIL Image to bytes
img_bytes = io.BytesIO()
input_image.save(img_bytes, format="PNG")
img_bytes = img_bytes.getvalue()
# Use the image_to_image method with Qwen's image editing model
edited_image = client.image_to_image(
img_bytes,
prompt=prompt.strip(),
model="Qwen/Qwen-Image-Edit",
)
return edited_image
except Exception as e:
print(f"Error editing image: {e}")
return input_image我们使用
fal-ai提供商和Qwen/Qwen-Image-Edit模型。fal-ai 提供商提供了快速的推理时间,非常适合交互式应用程序。不过,您可以尝试不同的提供商以获得各种性能特性
client = InferenceClient(provider="replicate", api_key=os.environ["HF_TOKEN"]) client = InferenceClient(provider="auto", api_key=os.environ["HF_TOKEN"]) # Automatic selection
步骤 4:创建 Gradio 界面
现在让我们使用 Gradio 构建一个简单且用户友好的界面。
# Create the Gradio interface
with gr.Blocks(title="Image Editor", theme=gr.themes.Soft()) as interface:
gr.Markdown(
"""
# 🎨 AI Image Editor
Upload an image and describe how you want to edit it using natural language!
"""
)
with gr.Row():
with gr.Column():
input_image = gr.Image(label="Upload Image", type="pil", height=400)
prompt = gr.Textbox(
label="Edit Prompt",
placeholder="Describe how you want to edit the image...",
lines=2,
)
edit_btn = gr.Button("✨ Edit Image", variant="primary", size="lg")
with gr.Column():
output_image = gr.Image(label="Edited Image", type="pil", height=400)
# Example images and prompts
with gr.Row():
gr.Examples(
examples=[
["cat.png", "Turn the cat into a tiger"],
["cat.png", "Make it look like a watercolor painting"],
["cat.png", "Change the background to a forest"],
],
inputs=[input_image, prompt],
outputs=output_image,
fn=edit_image,
cache_examples=False,
)
# Event handlers
edit_btn.click(fn=edit_image, inputs=[input_image, prompt], outputs=output_image)
# Allow Enter key to trigger editing
prompt.submit(fn=edit_image, inputs=[input_image, prompt], outputs=output_image)在这个应用中,我们将使用一些实用的 Gradio 功能来打造一个用户友好的应用
- 我们将使用 blocks 创建一个两列布局,分别放置图像上传和编辑后的图像。
- 我们将添加一些 markdown 来解释该应用的功能。
- 此外,我们将使用
gr.Examples来显示一些示例输入,为用户提供灵感。
最后,在 main.py 的末尾添加启动配置
if __name__ == "__main__":
interface.launch(
share=True, # Creates a public link
server_name="0.0.0.0", # Allow external access
server_port=7860, # Default Gradio port
show_error=True, # Show errors in the interface
)现在运行您的应用程序
python main.py
您的应用将在本地 https://:7860 启动,Gradio 还会提供一个公开的可分享链接!
完整运行代码
📋 点击查看完整的 main.py 文件
import os
import gradio as gr
from huggingface_hub import InferenceClient
from PIL import Image
import io
# Initialize the client
client = InferenceClient(
provider="fal-ai",
api_key=os.environ["HF_TOKEN"],
)
def edit_image(input_image, prompt):
"""
Edit an image using the given prompt.
Args:
input_image: PIL Image object from Gradio
prompt: String prompt for image editing
Returns:
PIL Image object (edited image)
"""
if input_image is None:
return None
if not prompt or prompt.strip() == "":
return input_image
try:
# Convert PIL Image to bytes
img_bytes = io.BytesIO()
input_image.save(img_bytes, format="PNG")
img_bytes = img_bytes.getvalue()
# Use the image_to_image method
edited_image = client.image_to_image(
img_bytes,
prompt=prompt.strip(),
model="Qwen/Qwen-Image-Edit",
)
return edited_image
except Exception as e:
print(f"Error editing image: {e}")
return input_image
# Create Gradio interface
with gr.Blocks(title="Image Editor", theme=gr.themes.Soft()) as interface:
gr.Markdown(
"""
# 🎨 AI Image Editor
Upload an image and describe how you want to edit it using natural language!
"""
)
with gr.Row():
with gr.Column():
input_image = gr.Image(label="Upload Image", type="pil", height=400)
prompt = gr.Textbox(
label="Edit Prompt",
placeholder="Describe how you want to edit the image...",
lines=2,
)
edit_btn = gr.Button("✨ Edit Image", variant="primary", size="lg")
with gr.Column():
output_image = gr.Image(label="Edited Image", type="pil", height=400)
# Example images and prompts
with gr.Row():
gr.Examples(
examples=[
["cat.png", "Turn the cat into a tiger"],
["cat.png", "Make it look like a watercolor painting"],
["cat.png", "Change the background to a forest"],
],
inputs=[input_image, prompt],
outputs=output_image,
fn=edit_image,
cache_examples=False,
)
# Event handlers
edit_btn.click(fn=edit_image, inputs=[input_image, prompt], outputs=output_image)
# Allow Enter key to trigger editing
prompt.submit(fn=edit_image, inputs=[input_image, prompt], outputs=output_image)
if __name__ == "__main__":
interface.launch(
share=True, # Creates a public link
server_name="0.0.0.0", # Allow external access
server_port=7860, # Default Gradio port
show_error=True, # Show errors in the interface
)部署到 Hugging Face Spaces
让我们将应用部署到 Hugging Face Spaces。
首先,我们将依赖项导出到 requirements 文件中。
uv export --format requirements-txt --output-file requirements.txt这将创建一个 requirements.txt 文件,其中包含项目的所有依赖项及其在 lockfile 中的精确版本。
uv export命令确保您的 Space 将使用与您在本地测试时完全相同的依赖版本,从而防止因版本不匹配导致的部署问题。
现在您可以部署到 Spaces
- 创建一个新空间:前往 huggingface.co/new-space
- 选择 Gradio SDK 并将其设置为公开
- 上传您的文件:上传
main.py、requirements.txt以及任何示例图像 - 添加你的令牌:在 Space 设置中,将
HF_TOKEN添加为秘密 - 启动:您的应用程序将在
https://huggingface.co/spaces/your-username/your-space-name上上线
后续步骤
恭喜!您已经创建了一个生产级别的 AI 图像编辑器。既然您已经拥有了一个可运行的图像编辑器,这里有一些扩展想法:
- 批量处理:一次编辑多张图像
- 物体移除:从图像中移除不需要的物体
- 提供商对比:针对您的使用场景对不同提供商进行基准测试
祝构建愉快!记得将您的应用分享给 Hub 社区。
在 GitHub 上更新