之前有个同事训练了一个文本分类模型,准确率还不错,但给领导演示的时候直接在Jupyter Notebook里跑——体验差到领导以为是半成品。后来我用Gradio花了15分钟给他搭了个Web界面,拖进去一个文件就能看结果,领导当场拍板推进项目;
Gradio的价值就在这里:让你从"能跑的模型"到"能演示的模型"只差几行Python代码;
安装
pip install gradio
最简单的应用
十行代码,一个文本处理应用就上线了:
import gradio as gr
def analyze_sentiment(text):
# 这里替换成你的模型逻辑
score = len([c for c in text if c in "好评满意赞"]) / max(len(text), 1)
return {"正面": score, "负面": 1 - score}
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(label="输入文本", lines=3, placeholder="请输入要分析的文本"),
outputs=gr.Label(label="情感分析结果"),
title="文本情感分析",
description="输入一段中文文本,自动分析情感倾向"
)
demo.launch()
运行后访问http://localhost:7680,一个带输入框和结果展示的Web界面就出来了。
聊天界面
大模型应用最常见的是聊天场景。Gradio的ChatInterface专门为此设计:
import gradio as gr
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
def chat(message, history):
messages = [{"role": "system", "content": "你是一个技术写作助手,回答简洁专业"}]
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": assistant_msg})
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="deepseek-r1:7b", messages=messages, stream=True
)
partial = ""
for chunk in response:
if chunk.choices[0].delta.content:
partial += chunk.choices[0].delta.content
yield partial
demo = gr.ChatInterface(fn=chat, title="本地AI助手")
demo.launch()
关键点是用yield实现流式输出,用户能看到逐字生成的效果。
图片处理应用
import gradio as gr
from PIL import Image, ImageFilter
def process_image(image, operation):
ops = {
"灰度": lambda img: img.convert("L"),
"模糊": lambda img: img.filter(ImageFilter.GaussianBlur(5)),
"边缘检测": lambda img: img.filter(ImageFilter.FIND_EDGES),
"锐化": lambda img: img.filter(ImageFilter.SHARPEN),
}
return ops.get(operation, lambda img: img)(image)
demo = gr.Interface(
fn=process_image,
inputs=[gr.Image(type="pil", label="上传图片"),
gr.Radio(["灰度", "模糊", "边缘检测", "锐化"], label="处理方式")],
outputs=gr.Image(label="结果"),
title="图片处理工具"
)
demo.launch()
复杂布局用Blocks
Interface适合简单场景,复杂布局需要用Blocks API:
with gr.Blocks(title="AI文档问答") as demo:
gr.Markdown("# AI文档问答系统")
with gr.Row():
with gr.Column(scale=1):
file = gr.File(label="上传文档", file_types=[".pdf", ".md", ".txt"])
question = gr.Textbox(label="输入问题", lines=2)
btn = gr.Button("提问", variant="primary")
with gr.Column(scale=2):
answer = gr.Markdown(label="回答")
sources = gr.JSON(label="引用来源")
btn.click(handle_ask, inputs=[file, question], outputs=[answer, sources])
demo.launch()
部署到HuggingFace Spaces
Gradio应用可以免费部署到HuggingFace Spaces。创建Space,上传app.py和requirements.txt,应用就上线了,自带域名和HTTPS。
写在最后
Gradio解决的是"最后一公里"的问题。模型再好,没人能方便地用上就等于零。花15分钟搭个Gradio界面,让模型的价值真正被看到。