教程

Gradio快速构建AI应用界面

| 2025-11-24 18:44 | 2239 浏览
# Gradio快速构建AI应用界面 ## 什么是Gradio? Gradio是一个Python库,可以在几分钟内为任何机器学习模型、API或任意Python函数创建Web界面。它被Hugging Face收购,已成为AI Demo的标准工具。 ## 安装 ```bash pip install gradio ``` ## 快速开始 ### 最简单的示例 ```python import gradio as gr def greet(name): return f"你好, {name}!" interface = gr.Interface( fn=greet, inputs="text", outputs="text" ) interface.launch() ``` 运行后打开 http://127.0.0.1:7860 即可使用。 ### 图像分类示例 ```python import gradio as gr from transformers import pipeline classifier = pipeline("image-classification") def classify_image(image): results = classifier(image) return {r["label"]: r["score"] for r in results} interface = gr.Interface( fn=classify_image, inputs=gr.Image(type="pil"), outputs=gr.Label(num_top_classes=5), title="图像分类器", description="上传图片进行分类" ) interface.launch() ``` ## 常用组件 ### 输入组件 ```python gr.Textbox() # 文本输入 gr.Number() # 数字输入 gr.Slider() # 滑块 gr.Dropdown() # 下拉框 gr.Checkbox() # 复选框 gr.Image() # 图像上传 gr.Audio() # 音频上传 gr.File() # 文件上传 ``` ### 输出组件 ```python gr.Textbox() # 文本输出 gr.Label() # 分类标签 gr.Image() # 图像输出 gr.Audio() # 音频输出 gr.DataFrame() # 表格 gr.Plot() # 图表 gr.Markdown() # Markdown ``` ## Blocks高级布局 ```python import gradio as gr with gr.Blocks() as demo: gr.Markdown("# 我的AI应用") with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="输入") submit_btn = gr.Button("提交") with gr.Column(): output_text = gr.Textbox(label="输出") submit_btn.click( fn=process_text, inputs=input_text, outputs=output_text ) demo.launch() ``` ## 流式输出 ```python import gradio as gr def stream_response(message): response = "" for char in "这是一个流式响应示例": response += char yield response with gr.Blocks() as demo: chatbot = gr.Chatbot() msg = gr.Textbox() def respond(message, history): return "", history + [[message, stream_response(message)]] msg.submit(respond, [msg, chatbot], [msg, chatbot]) demo.launch() ``` ## ChatInterface 专门用于聊天应用: ```python import gradio as gr def chat(message, history): # 调用LLM response = call_llm(message) return response interface = gr.ChatInterface( fn=chat, title="AI助手", examples=["你好", "什么是AI"] ) interface.launch() ``` ## 部署方式 ### Hugging Face Spaces 创建app.py和requirements.txt,推送到Spaces即可。 ### 本地部署 ```python interface.launch( server_name="0.0.0.0", server_port=7860, share=True # 创建公共链接 ) ``` ## 总结 Gradio是最快速的AI应用界面构建方式,特别适合快速原型、Demo展示和POC验证。
GradioUIWeb界面演示Hugging Face
156 点赞 24 评论

评论 (0)

登录后发表评论。

暂无评论。成为第一个评论的人吧!