2026/7/22 11:02:56

Gradio安装配置及经典案例说明

Gradio安装配置及经典案例说明 1. Gradio 基本介绍1.1 定义与核心概念Gradio 是一个开源的 Python 库用于为 机器学习 模型和函数创建交互式网页界面。它成立于 2020 年由 Ali Faisal、Hamza Khan 和 Muhammad Furqan 持续开发最新稳定版本为 5.49.1。# 示例查看当前安装的 Gradio 版本 import gradio as gr print(f当前 Gradio 版本: {gr.__version__})1.2 主要特点Gradio 具有以下核心特点简单易用通过几行代码即可创建完整的 Web 界面丰富组件提供 30 多种预构建组件包括音频、摄像头、麦克风、绘图工具等美观界面即使没有前端知识也能生成美观的界面易于分享可以生成公共链接与他人分享实现远程交互跨平台运行支持本地运行、Google Colab、远程服务器等多环境1.3 适用场景Gradio 广泛应用于以下场景机器学习模型演示与测试创建机器学习 API 和 Web 应用程序数据科学项目可视化展示快速原型设计和迭代教育和研究中的模型展示2. 安装与环境配置2.1 基本安装方法Gradio 可通过 pip 或 conda 轻松安装# 基本安装 pip install gradio # 或使用 conda conda install -c conda-forge gradio # 指定版本安装推荐使用最新稳定版 pip install gradio5.49.12.2 虚拟环境配置推荐在虚拟环境中安装 Gradio以避免依赖冲突# 创建虚拟环境Python 3.9 为例 python -m venv gradio-env # 激活虚拟环境Windows gradio-env\Scripts\activate # 激活虚拟环境Linux/Mac source gradio-env/bin/activate # 安装 Gradio pip install gradio2.3 环境要求Gradio 需要 Python 3.7 或更高版本。同时根据应用复杂度可能需要安装额外的依赖# 安装常见依赖 pip install numpy pandas scikit-learn tensorflow torch3. 基础使用方法3.1 创建第一个 Gradio 应用以下是 Gradio 的最基本用法示例import gradio as gr def greet(name): return fHello, {name}! demo gr.Interface(fngreet, inputstext, outputstext) demo.launch()此示例会创建一个简单的文本输入界面用户输入姓名后系统会返回问候语。3.2 核心组件Gradio 的核心组件包括Interface: 最高级 API可用于快速创建完整应用Blocks: 低级 API提供更精细的控制可自定义布局和数据流各种输入组件: 如gr.Textbox,gr.Image,gr.Audio等各种输出组件: 如gr.outputs.Textbox,gr.outputs.Image等3.3 使用 Interface 创建应用Interface 是 Gradio 最主要的高级类允许你快速为 Python 函数创建 Web 界面 import gradio as gr from PIL import Image import requests def invert_image(image): 将图像反转 if image is None: return None img Image.open(image) inverted_img ImageOps.invert(img.convert(RGB)) return inverted_img demo gr.Interface( fninvert_image, inputsgr.Image(label上传图像), outputsgr.Image(label反转后的图像), title图像反转工具, description上传一张图像将其颜色反转 ) demo.launch()4. 创建交互式界面4.1 使用 Interface 快速创建Interface 的基本用法非常直观需要三个核心参数fn: 要封装的函数inputs: 输入组件outputs: 输出组件import gradio as gr import numpy as np import matplotlib.pyplot as plt def plot_sine_wave(freq, amplitude, phase): 生成正弦波图像 x np.linspace(0, 2 * np.pi, 100) y amplitude * np.sin(2 * np.pi * freq * x phase) plt.figure(figsize(10, 6)) plt.plot(x, y) plt.title(f正弦波 - 频率: {freq}, 振幅: {amplitude}, 相位: {phase}) plt.xlabel(时间) plt.ylabel(幅度) plt.grid(True) return plt.gcf() demo gr.Interface( fnplot_sine_wave, inputs[ gr.Slider(0.1, 5, value1, label频率), gr.Slider(0.1, 5, value1, label振幅), gr.Slider(0, 2 * np.pi, value0, label相位) ], outputsplot, liveTrue # 实时更新 ) demo.launch()4.2 使用 Blocks 创建自定义布局Blocks 是 Gradio 的低级 API提供更精细的控制 import gradio as gr with gr.Blocks(title自定义布局示例) as demo: gr.Markdown(# 自定义布局示例) with gr.Tab(选项卡1): with gr.Row(): btn1 gr.Button(点击我1) btn2 gr.Button(点击我2) with gr.Tab(选项卡2): text_input gr.Textbox(label输入文本) output gr.Textbox(label输出结果) def reverse_text(text): return text[::-1] text_input.change(reverse_text, inputstext_input, outputsoutput) with gr.Row(): gr.Markdown(这是一个行布局示例) gr.Image(valuehttps://gradio.app/logo.png, width100) demo.launch()4.3 事件处理与交互Gradio 支持多种事件处理方式实现复杂交互import gradio as gr import time def process_text(text, progressgr.Progress()): 模拟耗时文本处理操作 result for i in range(len(text)): result text[i] progress(i / len(text), f处理字符 {i1}/{len(text)}) time.sleep(0.05) return f处理完成: {result} with gr.Blocks() as demo: gr.Markdown(# 文本处理示例) with gr.Row(): text_input gr.Textbox(label输入文本) output gr.Textbox(label处理结果) with gr.Row(): process_btn gr.Button(开始处理) progress_bar gr.Progress() process_btn.click( process_text, inputs[text_input, progress_bar], outputsoutput ) demo.launch()5. 常用组件Gradio 提供了丰富的组件来创建各种交互式界面。以下是常见组件的用法5.1 输入组件组件用途示例代码gr.Textbox()文本输入gr.Textbox(label输入文本)gr.Number()数值输入gr.Number(label输入数字, value42)gr.Slider()范围滑块gr.Slider(0, 100, value50, label选择百分比)gr.Checkbox()复选框gr.Checkbox(label接受条款)gr.Radio()单选按钮gr.Radio([选项1, 选项2], label选择选项)gr.CheckboxGroup()复选框组gr.CheckboxGroup([选项1, 选项2], label选择多个)gr.Image()图像上传与标注gr.Image(label上传图像)gr.Audio()音频录制与上传gr.Audio(label录制音频)gr.Video()视频上传gr.Video(label上传视频)gr.File()文件上传gr.File(label上传文件)5.2 输出组件组件用途示例代码gr.outputs.Textbox()文本输出gr.outputs.Textbox(label输出文本)gr.outputs.Number()数值输出gr.outputs.Number(label输出数字)gr.outputs.Image()图像显示gr.outputs.Image(label输出图像)gr.outputs.Audio()音频播放gr.outputs.Audio(label输出音频)gr.outputs.Video()视频播放gr.outputs.Video(label输出视频)gr.outputs.Plot()图表显示gr.outputs.Plot(label图表)5.3 布局组件组件用途示例代码gr.Row()水平布局with gr.Row(): ...gr.Column()垂直布局with gr.Column(): ...gr.Tab()选项卡布局with gr.Tab(标签名): ...gr.Group()组合组件with gr.Group(): ...6. 机器学习模型部署教程6.1 部署图像分类模型import gradio as gr from tensorflow.keras.applications import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np import os # 加载预训练模型 model ResNet50(weightsimagenet) def classify_image(img): #图像分类函数 if img is None: return # 预处理图像 img image.load_img(img, target_size(224, 224)) x image.img_to_array(img) x np.expand_dims(x, axis0) x preprocess_input(x) # 预测 preds model.predict(x) results decode_predictions(preds, top3)[0] # 格式化结果 return [{label: f{result[1]}, confidence: f{result[2]:.2%}} for result in results] # 创建Gradio界面 demo gr.Interface( fnclassify_image, inputsgr.Image(label上传一张图像, typefilepath), outputsgr.Label(label预测结果, num_top_classes3), examples[[images/stickercats.jpg], [images/plane.jpg], [images/car.jpg]], title图像分类器, description上传一张图像我会告诉你它是什么 ) # 启动应用 if __name__ __main__: demo.launch()6.2 部署文本分类模型import gradio as gr from transformers import pipeline # 加载文本分类器 classifier pipeline(text-classification, modeldistilbert-base-uncased-finetuned-sst-2-english) def analyze_sentiment(text): # 情感分析函数 if not text: return 请输入文本 result classifier(text) label result[0][label] confidence result[0][score] return f情感: {label}置信度: {confidence:.2f} # 创建Gradio界面 inputs gr.Textbox(lines3, label输入文本, placeholder输入你要分析的文本...) outputs gr.Textbox(label分析结果) demo gr.Interface( fnanalyze_sentiment, inputsinputs, outputsoutputs, title情感分析器, description输入一段文本我将分析其情感倾向, examples[[这个产品非常棒], [我讨厌这个服务。], [食物还可以服务一般。]] ) # 启动应用 if __name__ __main__: demo.launch()6.3 部署对话模型import gradio as gr from transformers import AutoTokenizer, AutoModelForCausalLM import torch # 加载对话模型 tokenizer AutoTokenizer.from_pretrained(microsoft/DialoGPT-medium) model AutoModelForCausalLM.from_pretrained(microsoft/DialoGPT-medium) def chatbot(history, user_input): # 对话机器人函数 # 获取对话历史和用户输入 bot_input_ids tokenizer.encode(user_input tokenizer.eos_token, return_tensorspt) # 与历史对话连接 if history: bot_input_ids torch.cat([history, bot_input_ids], dim-1) # 生成模型回复 chat_history model.generate( bot_input_ids, max_length1000, do_sampleTrue, top_p0.95, temperature0.7, pad_token_idtokenizer.eos_token_id, ) # 解码回复 reply tokenizer.decode(chat_history[:, bot_input_ids.shape[1]:][0], skip_special_tokensTrue) # 返回更新后的历史和回复 return chat_history, reply # 创建Gradio界面 with gr.Blocks() as demo: gr.Markdown(# 聊天机器人) chatbot_history gr.State([]) with gr.Row(): with gr.Column(scale1): user_message gr.Textbox(label用户:, placeholder输入你的消息...) gr.Button(发送, variantprimary).click( chatbot, inputs[chatbot_history, user_message], outputs[chatbot_history, bot_message] ) with gr.Column(scale2): bot_message gr.Textbox(label机器人:, interactiveFalse) # 启动应用 if __name__ __main__: demo.launch()7. 实际项目案例7.1 OCR文本提取工具import gradio as gr import easyocr from PIL import ImageDraw import numpy as np # 初始化 OCR reader reader easyocr.Reader([ch_sim, en], gpuFalse) def perform_ocr(image, language): # 执行OCR并返回结果 # 执行OCR results reader.readtext(image, detail1, paragraphTrue, batch_size5) # 在图像上绘制结果 img Image.fromarray(image) draw ImageDraw.Draw(img) for result in results: bbox, text, confidence result x1, y1 bbox[0] x2, y2 bbox[2] draw.rectangle([x1, y1, x2, y2], outlinered, width2) # 提取文本 ocr_text for result in results: ocr_text result[1] return img, ocr_text.strip() # 创建Gradio界面 with gr.Blocks() as demo: gr.Markdown(# OCR 文本提取工具) with gr.Row(): with gr.Column(scale1): image_input gr.Image(label上传图像, typenumpy) language gr.Radio([中文, 英文], label语言选择, value中文) perform_ocr_btn gr.Button(执行OCR, variantprimary) with gr.Column(scale1): output_image gr.Image(labelOCR结果预览) output_text gr.Textbox(label提取的文本, lines5) perform_ocr_btn.click( perform_ocr, inputs[image_input, language], outputs[output_image, output_text] ) gr.Examples( examples[ [images/text_image1.jpg, 中文], [images/text_image2.jpg, 英文] ], inputs[image_input, language] ) # 启动应用 if __name__ __main__: demo.launch()7.2 数据分析与可视化工具import gradio as gr import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 生成示例数据 def generate_sample_data(): data { 日期: pd.date_range(2023-01-01, periods100, freqD), 销售额: np.random.normal(100, 30, 100).cumsum(), 产品类别: np.random.choice([电子产品, 服装, 食品, 家居], 100), 地区: np.random.choice([北京, 上海, 广州, 深圳], 100) } return pd.DataFrame(data) def analyze_data(data, analysis_type, regionNone): 数据分析函数接收 DataFrame 和参数 if analysis_type 整体销售趋势: fig, ax plt.subplots(figsize(12, 6)) sns.lineplot(datadata, x日期, y销售额, axax) ax.set_title(销售额时间趋势) ax.set_xlabel(日期) ax.set_ylabel(销售额) return fig elif analysis_type 按地区分析 and region: filtered_data data[data[地区] region] fig, ax plt.subplots(figsize(12, 6)) sns.lineplot(datafiltered_data, x日期, y销售额, axax) ax.set_title(f{region} 地区销售额趋势) ax.set_xlabel(日期) ax.set_ylabel(销售额) return fig elif analysis_type 产品类别分析: fig, ax plt.subplots(figsize(12, 6)) category_sales data.groupby(产品类别)[销售额].sum() sns.barplot(xcategory_sales.index, ycategory_sales.values, axax) ax.set_title(按产品类别销售额) ax.set_xlabel(产品类别) ax.set_ylabel(销售额) return fig else: return 请选择有效的分析类型 # 创建Gradio界面 with gr.Blocks() as demo: gr.Markdown(# 数据分析与可视化工具) gr.Markdown(点击下方按钮基于示例数据执行分析。) # 【核心修改】使用 gr.State 存储数据避免直接传入 DataFrame data_state gr.State(generate_sample_data()) # 可选显示数据预览增强用户体验 with gr.Row(): with gr.Column(scale1): preview_df gr.Dataframe( valuegenerate_sample_data().head(10), label数据预览前10行, interactiveFalse, wrapTrue ) analysis_type gr.Radio( [整体销售趋势, 按地区分析, 产品类别分析], label选择分析类型, value整体销售趋势 ) region gr.Radio( [北京, 上海, 广州, 深圳], label选择地区, visibleFalse, interactiveTrue ) def update_region_visibility(analysis_type): return gr.update(visible(analysis_type 按地区分析)) analysis_type.change( fnupdate_region_visibility, inputs[analysis_type], outputs[region] ) btn gr.Button( 执行分析, variantprimary) output gr.Plot(label分析结果) # 【修复】inputs 中传入 data_stategr.State 组件 btn.click( fnanalyze_data, inputs[data_state, analysis_type, region], outputsoutput ) # 启动应用 if __name__ __main__: demo.launch()8. 最佳实践与性能优化8.1 界面设计原则简洁直观保持界面简洁用户操作直观响应及时提供加载状态和进度指示错误处理友好的错误提示和异常处理可访问性支持键盘导航和屏幕阅读器8.2 性能优化策略模型优化使用量化技术减小模型大小、提高推理速度对深度学习模型处理批量样本比处理单个样本更高效数据加载优化使用高效的数据存储和读取方法如使用Pandas的高效文件读取函数WebSockets与数据编码Gradio 5 改进了内部通信方式使用WebSockets并通过编码发送数据减少了延迟缓存机制为频繁访问的数据或结果添加缓存资源监控# 启动带资源监控的演示 demo.launch(server_name0.0.0.0, server_port7860, monitor_hostTrue, enable_queueTrue)8.3 部署优化本地部署使用demo.launch(shareTrue)生成可共享链接通过 Docker 部署设置GRADIO_SERVER_NAME0.0.0.0环境变量云端部署使用 Hugging Face Spaces、Heroku、AWS 等平台配置自动缩放和负载均衡共享注意事项与他人分享 Gradio 应用时会向用户暴露主机机器上的某些文件需注意安全9. Gradio 与其他工具对比特性GradioStreamlitDash学习曲线平缓较平缓陡峭界面美观度高中需自定义扩展性中高高组件丰富度高中高适用场景机器学习模型演示数据可视化、仪表盘复杂Web应用开发灵活性中等高最高性能良好良好需优化9.1 Gradio vs StreamlitGradio 优势更适合快速部署和分享机器学习模型组件的封装程度高尤其适合机器学习模型相关的应用支持断点调试Streamlit 优势更高的灵活性和美观度提供更广泛的定制选项更适合构建各种类型的数据科学和机器学习应用程序9.2 选择建议Gradio 适合快速创建机器学习模型演示、图像处理应用、对话系统Streamlit 适合数据可视化、仪表盘开发、需要高度自定义的Web应用10. 高级应用示例10.1 自定义聊天机器人import gradio as gr import openai import os # 设置OpenAI API密钥 openai.api_key your-api-key def chatgpt_chat(history, message): #使用ChatGPT的聊天函数 if message is None or message : return history, # 准备对话历史 messages [{role: system, content: 你是一个 helpful AI 助手。}] if history: messages.extend(history) # 添加用户消息 messages.append({role: user, content: message}) # 调用ChatGPT API response openai.ChatCompletion.create( modelgpt-3.5-turbo, messagesmessages ) # 获取AI回复 reply response.choices[0].message.content # 更新对话历史 messages.append({role: assistant, content: reply}) return messages, reply # 创建Gradio界面 with gr.Blocks() as demo: gr.Markdown(# ChatGPT 聊天机器人) chat_history gr.State([]) with gr.Row(): chatbot gr.Chatbot(label对话) with gr.Row(): message gr.Textbox(label输入, placeholder输入你的消息...) submit gr.Button(发送, variantprimary) submit.click( chatgpt_chat, inputs[chat_history, message], outputs[chat_history, chatbot] ) message.submit( chatgpt_chat, inputs[chat_history, message], outputs[chat_history, chatbot] ) # 启动应用 if __name__ __main__: demo.launch()10.2 图像生成应用import gradio as gr import torch from diffusers import StableDiffusionPipeline from PIL import Image # 加载图像生成模型 model_id runwayml/stable-diffusion-v1-5 pipe StableDiffusionPipeline.from_pretrained(model_id, torch_dtypetorch.float16) pipe pipe.to(cuda) def generate_image(prompt, width512, height512, steps50): #生成图像的函数 if not prompt: return 请输入提示词 # 生成图像 image pipe(prompt, widthwidth, heightheight, num_inference_stepssteps).images[0] return image # 创建Gradio界面 demo gr.Interface( fngenerate_image, inputs[ gr.Textbox(label提示词, placeholder输入图像生成提示词...), gr.Slider(256, 1024, value512, step64, label宽度), gr.Slider(256, 1024, value512, step64, label高度), gr.Slider(10, 100, value50, label采样步数) ], outputsgr.Image(label生成的图像), title图像生成器, description输入提示词和参数生成对应的图像, examples[[一个美丽的山水画, 512, 512, 50], [未来科技城市, 768, 768, 70], [中国风建筑, 640, 512, 60]] ) # 启动应用 if __name__ __main__: demo.launch()11. 案例门户11.1 Gradio案例门户import gradio as gr import subprocess import webbrowser import sys import os import re import time import threading import queue # ---------- 配置 ---------- APP_SCRIPTS { chatModel: gradio_simple_chatModel.py, chatRobot: gradio_simple_chatRobot.py, dataAnalyze: gradio_simple_dataAnalyzeViewTool.py, generateImage: gradio_simple_generateImage.py, imageClassModel: gradio_simple_imageClassModel.py, ocrTextPerformTool: gradio_simple_ocrTextPerformTool.py, textClassModel: gradio_simple_textClassModel.py, normal: gradio_simple_normal.py, } running_apps {} STARTUP_TIMEOUT 60 # ---------- 辅助函数 ---------- def extract_port_from_output(line: str): match re.search(rRunning on local URL:\shttp://127\.0\.0\.1:(\d), line) return int(match.group(1)) if match else None def open_app(app_key: str): script_name APP_SCRIPTS.get(app_key) if not script_name: return f❌ 未知的应用标识{app_key} # ---------- 新增如果已有运行实例先终止它 ---------- if app_key in running_apps: proc, port running_apps[app_key] if proc.poll() is None: # 进程仍在运行 print(f 终止旧进程 [{app_key}] (PID {proc.pid})) proc.terminate() # 优雅终止 try: proc.wait(timeout3) # 等待最多3秒 except subprocess.TimeoutExpired: proc.kill() # 强制终止 proc.wait() del running_apps[app_key] # 移除记录 # ---------- 以下为原有的启动逻辑完全不变 ---------- base_dir os.path.dirname(os.path.abspath(__file__)) script_path os.path.join(base_dir, script_name) if not os.path.isfile(script_path): return f❌ 脚本文件不存在{script_path} python_exe sys.executable cmd [python_exe, script_path] env os.environ.copy() env[PYTHONUNBUFFERED] 1 print(f\n 正在启动子应用 [{app_key}]) print(f 命令: { .join(cmd)}) print(f 工作目录: {base_dir}) try: proc subprocess.Popen( cmd, stdoutsubprocess.PIPE, stderrsubprocess.STDOUT, universal_newlinesTrue, bufsize1, cwdbase_dir, envenv, ) print(f 进程 PID: {proc.pid}) output_queue queue.Queue() def reader(): try: for line in iter(proc.stdout.readline, ): output_queue.put(line) finally: output_queue.put(None) thread threading.Thread(targetreader, daemonTrue) thread.start() port None output_lines [] start_time time.time() while time.time() - start_time STARTUP_TIMEOUT: try: line output_queue.get(timeout0.5) except queue.Empty: if proc.poll() is not None: while not output_queue.empty(): line output_queue.get_nowait() if line is None: break output_lines.append(line) return ( f❌ 进程在捕获端口前退出退出码 {proc.returncode}。\n f--- 子应用输出日志 ---\n{.join(output_lines)} ) continue if line is None: break output_lines.append(line) print(f[{app_key}] {line.strip()}) extracted extract_port_from_output(line) if extracted: port extracted break if port is None: if proc.poll() is None: proc.terminate() return ( f❌ 启动超时{STARTUP_TIMEOUT}秒或未捕获到服务端口。\n f请检查子应用是否正常启动或适当增加 STARTUP_TIMEOUT 值。\n\n f--- 子应用输出日志 ---\n{.join(output_lines)} ) running_apps[app_key] (proc, port) webbrowser.open_new(fhttp://127.0.0.1:{port}) return f✅ 应用启动成功端口 {port}已在新窗口打开 except Exception as e: return f❌ 门户内部异常{str(e)} # ---------- 自定义 CSS ---------- custom_css .gradio-container { max-width: 1200px !important; margin: 0 auto; } .app-card { background: var(--block-background-fill); border-radius: 16px; padding: 24px 20px 20px 20px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); transition: transform 0.25s ease, box-shadow 0.25s ease; text-align: center; height: 100%; border: 1px solid var(--border-color-primary); } .app-card:hover { transform: translateY(-6px); box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12); } .app-card .title { font-size: 1.4rem; font-weight: 600; margin-bottom: 10px; } .app-card .desc { font-size: 1rem; color: var(--body-text-color-subdued); margin-bottom: 18px; line-height: 1.5; } .app-card .launch-btn { width: 100%; font-weight: 500; } # ---------- 构建界面 ---------- with gr.Blocks( themegr.themes.Soft(primary_hueblue, secondary_huegray), csscustom_css, titleGradio 应用门户, ) as demo: gr.Markdown(# Gradio 应用案例门户) gr.Markdown(点击下方卡片即可在新窗口中启动并打开对应的 Gradio 应用。) # ---------- 第一行前 4 个应用 ---------- with gr.Row(equal_heightTrue): # 1. 图像生成 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **图像生成应用**, elem_classes[title]) gr.Markdown(利用深度学习模型生成逼真图像支持文本到图像的转换。, elem_classes[desc]) btn_gen gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 2. 自定义聊天机器人 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **自定义聊天机器人**, elem_classes[title]) gr.Markdown(基于大语言模型的交互式对话助手可定制性格与知识库。, elem_classes[desc]) btn_chat gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 3. 数据分析与可视化 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **数据分析与可视化工具**, elem_classes[title]) gr.Markdown(上传 CSV / Excel 文件自动生成交互式图表和统计摘要。, elem_classes[desc]) btn_data gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 4. 聊天模型新增 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **聊天模型应用**, elem_classes[title]) gr.Markdown(基于通用聊天模型实现自然语言对话与问答。, elem_classes[desc]) btn_chat_model gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # ---------- 第二行后 4 个应用 ---------- with gr.Row(equal_heightTrue): # 5. 图像分类模型 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown(️ **图像分类模型**, elem_classes[title]) gr.Markdown(对上传的图像进行自动分类识别物体或场景。, elem_classes[desc]) btn_img_class gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 6. OCR 文本识别 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **OCR 文本识别工具**, elem_classes[title]) gr.Markdown(从图片中提取印刷或手写文字支持多种语言。, elem_classes[desc]) btn_ocr gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 7. 文本分类模型 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **文本分类模型**, elem_classes[title]) gr.Markdown(对输入的文本进行情感分析、主题分类等任务。, elem_classes[desc]) btn_text_class gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # 8. 常规示例 with gr.Column(scale1, min_width200): with gr.Group(elem_classes[app-card]): gr.Markdown( **常规示例应用**, elem_classes[title]) gr.Markdown(提供基础的 Gradio 功能演示适合快速上手测试。, elem_classes[desc]) btn_normal gr.Button( 启动应用, variantprimary, sizelg, elem_classes[launch-btn]) # ---------- 状态信息框 ---------- status_box gr.Textbox( label 状态信息, interactiveFalse, visibleTrue, value等待操作…, ) # ---------- 绑定所有按钮 ---------- btn_gen.click(fnopen_app, inputsgr.State(generateImage), outputsstatus_box) btn_chat.click(fnopen_app, inputsgr.State(chatRobot), outputsstatus_box) btn_data.click(fnopen_app, inputsgr.State(dataAnalyze), outputsstatus_box) btn_chat_model.click(fnopen_app, inputsgr.State(chatModel), outputsstatus_box) btn_img_class.click(fnopen_app, inputsgr.State(imageClassModel), outputsstatus_box) btn_ocr.click(fnopen_app, inputsgr.State(ocrTextPerformTool), outputsstatus_box) btn_text_class.click(fnopen_app, inputsgr.State(textClassModel), outputsstatus_box) btn_normal.click(fnopen_app, inputsgr.State(normal), outputsstatus_box) # ---------- 启动门户 ---------- if __name__ __main__: demo.launch()运行示例总结Gradio 是一个功能强大且易于使用的 Python 库使开发者能够快速为机器学习模型和函数创建交互式网页界面。它特别适合于机器学习模型演示、快速原型开发和团队协作。通过本教程我们介绍了 Gradio 的基本概念、安装方法、界面创建、组件使用、机器学习模型部署以及性能优化等方面的内容。希望这些内容能帮助你快速掌握 Gradio 的使用创建出功能丰富、交互性强的应用程序。在实际项目中建议你结合具体需求参考 Gradio 官方文档 (https://www.gradio.app/docs) 获取更多组件和功能的详细信息创建出更加专业和强大的应用。