gradio是一个web ui框架,主要用于验证大模型应用开发出来的效果咋样
**课程目标:**用 Gradio 将 Python 函数、机器学习模型或大模型 API 快速包装成可交互的 Web 页面,方便验证效果、演示和临时分享。
一、Gradio 是什么
Gradio 是 Hugging Face 生态中的开源 Python 库。它将函数参数映射为输入组件,将函数返回值映射为输出组件,因此不需要编写前端代码也能快速完成 Demo。
- **适用场景:**算法原型、模型效果验证、内部演示、API 调试。
- **典型项目:**ChatGLM2-6B、gpt_academic、stable-diffusion-webui。
- 核心关系:
Python 函数 + 输入组件 + 输出组件 = 可交互 Web 页面。
二、为什么使用 Gradio
- 模型、API 和普通 Python 函数都能直接获得图形化界面。
- 设置
share=True可生成临时公网地址,课程中说明有效期约为 72 小时。 - 非常适合快速验证,不必先投入时间开发完整前端。
三、快速入门:文本反转
python
import gradio as gr
def reverse_text(text):
return text[::-1]
demo = gr.Interface(
fn=reverse_text,
inputs="text",
outputs="text"
)
demo.launch(share=True)
参数对应关系:
| 参数 | 含义 | 注意点 |
|---|---|---|
fn |
要执行的 Python 函数 | 不要写成函数调用结果 |
inputs |
输入组件 | 数量与顺序应对应函数形参 |
outputs |
输出组件 | 数量与顺序应对应返回值 |
share |
是否生成公网链接 | 应使用布尔值 True,不要写成字符串 |
课堂中的问候函数示例
python
import gradio as gr
def hellotoPerson(name):
return "你好," + name
demo = gr.Interface(
fn=hellotoPerson,
inputs="text",
outputs="text"
)
demo.launch()
四、多输出与界面信息配置
下面的函数同时返回"反转后的文本"和"字符数",所以 outputs 需要配置两个组件。
python
import gradio as gr
def reverse_and_count(text):
reversed_text = text[::-1]
length = len(text)
return reversed_text, length
demo = gr.Interface(
fn=reverse_and_count,
inputs="text",
outputs=["text", "number"],
title="文本处理工具",
description="输入一段文字,查看其倒序形式及字符数。",
examples=[["你好,世界"], ["Hello World"]],
flagging_mode="never"
)
demo.launch()
title:页面标题。description:功能说明。examples:可点击并快速填充的示例。flagging_mode="never":关闭 Flag 标记功能。
五、完整案例:图片转铅笔画
处理流程:灰度化 → 像素取反 → 高斯模糊 → 再次取反 → 颜色减淡计算。
python
import gradio as gr
import numpy as np
import cv2
def image_to_sketch(image):
gray_image = image.convert("L")
inverted_image = 255 - np.array(gray_image)
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(
np.array(gray_image),
inverted_blurred,
scale=256.0
)
return pencil_sketch
demo = gr.Interface(
fn=image_to_sketch,
inputs=[gr.Image(label="上传图片", type="pil")],
outputs=[gr.Image(label="输出图")],
title="图像转铅笔画",
description="将上传的图片转为铅笔画。"
)
demo.launch()
关键点: type="pil" 使回调函数接收到 PIL Image 对象;label 用于修改组件在页面中的显示名称。
六、完整案例:接入通义千问 qwen-max
课程通过 DashScope 的 OpenAI 兼容接口调用 qwen-max,并兼容 Gradio 新旧两种历史消息结构。
python
import gradio as gr
import os
from openai import OpenAI
api_key = os.getenv("DASHSCOPE_API_KEY")
def call_qwen(message, history):
# 未设置密钥时直接返回提示,避免继续发起请求
if not api_key:
return "错误:未设置 DASHSCOPE_API_KEY 环境变量,请设置后重试。"
client = OpenAI(
api_key=api_key,
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
messages = []
# 兼容新版字典格式和旧版二元组格式的聊天历史
if history:
try:
for msg in history:
if (
isinstance(msg, dict)
and "role" in msg
and "content" in msg
):
messages.append(msg)
elif isinstance(msg, (list, tuple)) and len(msg) == 2:
user_msg, assistant_msg = msg
messages.append({
"role": "user",
"content": user_msg
})
messages.append({
"role": "assistant",
"content": assistant_msg
})
except Exception as e:
print(f"处理历史记录时出错:{e}")
messages.append({"role": "user", "content": message})
try:
response = client.chat.completions.create(
model="qwen-max",
messages=messages,
stream=False
)
return response.choices[0].message.content
except Exception as e:
return "Error: " + str(e)
demo = gr.ChatInterface(
fn=call_qwen,
title="通义千问-max",
description="基于通义千问 max 的聊天机器人",
examples=[
["你好"],
["你叫什么名字?"],
["给我讲一个笑话呀"]
]
)
if name == "main":
demo.launch(theme=gr.themes.Soft())
聊天示例的执行流程
- 从环境变量读取
DASHSCOPE_API_KEY。 - 把 Gradio 的历史消息转换为 OpenAI 接口要求的
messages字典列表。 - 追加用户当前输入。
- 调用
client.chat.completions.create()。 - 返回
response.choices[0].message.content,交给聊天组件展示。
七、容易出错的细节
- 布尔值: 使用
share=True,不要写成share="True"。 - 切片语法: 反转字符串是
text[::-1],中间是两个冒号。 - 组件类型: 图片案例使用
gr.Image(type="pil"),否则函数接收的数据类型可能不同。 - **消息格式:**聊天历史可能是字典列表,也可能是二元组列表,应分别处理。
- **密钥安全:**API Key 只从环境变量读取,不要硬编码到源码或上传仓库。
- **版本差异:**Gradio 更新较快,如参数报错应先核对本地版本和对应文档。
- 公网链接:
share=True适合临时演示,不替代正式生产部署。
八、总结
**先写好处理函数,再用 Interface 或 ChatInterface 描述输入与输出。**Gradio 的价值在于把模型能力快速变成"可看、可点、可分享"的应用页面。