目 录CONTENT

文章目录
ACM

Python库 - Gradio

解小风
2025-08-25 / 0 评论 / 1 点赞 / 11 阅读 / 31227 字

简介

Gradio 是一个用于创建机器学习和数据科学应用程序的开源 Python 库,它的主要目标是使开发人员能够以简单的方式快速构建交互式的 Web 应用,特别适合展示机器学习模型数据分析工具算法演示。与传统的 Web 开发不同,Gradio 无需编写 HTML、CSS、JavaScript,只需几行 Python 代码即可快速、轻松地构建美观的交互式 Web 应用程序。


安装与配置

安装 Gradio

# 安装
pip install --no-cache-dir -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple gradio==5.41.1

# 查看版本
import gradio as gr
print(gr.__version__)

配置 Gradio

# Gradio 两大核心基础配置:

# 1、基础界面设置:Interface() 或 Blocks() 用于创建交互式界面,以下以 Interface() 为例
# fn: {必填} 指定 Gradio 应用的核心逻辑函数
# inputs: {必填} 输入组件类型
# outputs: {必填} 输出组件类型
# title: {可选} 应用标题,显示在页面顶部
# description: {可选} 应用描述,显示在标题下方
# theme: {可选} 主题样式,可选 ["default", "huggingface", "grass", "peach", "monochrome"] 等
# css: {可选} 自定义 CSS 样式
# js: {可选} 自定义 JavaScript 代码

# 2、启动设置:launch()
# server_name: 服务器地址,默认{"127.0.0.1"},设置为 "0.0.0.0" 可允许外部访问
# server_port: 端口号,默认{7860},如果端口被占用会自动选择下一个可用端口
# share: 是否创建公共链接,默认{False},设置为 True 会生成一个公共的 gradio.live 链接
# debug: 是否启用调试模式,默认{False},启用后会显示详细的错误信息
# show_error: 是否在界面上显示错误信息,默认{False}
# quiet: 是否静默启动,默认{False},设置为 True 会减少控制台输出
# inbrowser: 是否自动在浏览器中打开,默认{True}
# auth: 身份验证,可以设置用户名和密码,格式为 ("username", "password")
# max_threads: 最大并发线程数,默认{40}


# 示例配置
import gradio as gr

def my_function(text):
    return f"Hello, {text}!"

# 基础界面设置
iface = gr.Interface(
    fn=my_function,
    inputs=gr.Textbox(label="输入文本"),
    outputs=gr.Textbox(label="输出结果"),
    title="我的 Gradio 应用",
    description="这是一个简单的问候应用",
    theme="default",
    css=".gradio-container {background-color: #f0f0f0;}"
)

# 启动设置
iface.launch(
    server_name="0.0.0.0",      # 允许外部访问
    server_port=7860,           # 指定端口
    share=False,                # 不创建公共链接
    debug=True,                 # 启用调试模式
    inbrowser=True,             # 自动打开浏览器
    auth=("admin", "password")  # 设置身份验证
)

运行 Gradio

# 运行 Gradio 应用(以 myapp.py 应用文件为例,文件内容如【配置 Gradio】中所示)
python myapp.py

基础知识

页面显示

基础页面

# Gradio 两大核心页面:

# 1、Interface():适合简单任务(单输入单输出)、对界面样式要求不高
# fn: {必填} 指定 Gradio 应用的核心逻辑函数
# inputs: {必填} 输入组件类型
# outputs: {必填} 输出组件类型
# title: {可选} 应用标题,显示在页面顶部
# description: {可选} 应用描述,显示在标题下方
# theme: {可选} 主题样式,可选 ["default", "huggingface", "grass", "peach", "monochrome"] 等
# css: {可选} 自定义 CSS 样式
# js: {可选} 自定义 JavaScript 代码

import gradio as gr

def my_function(text):
    return f"Hello, {text}!"

# 基础界面设置
iface = gr.Interface(
    fn=my_function,
    inputs=gr.Textbox(label="输入文本"),
    outputs=gr.Textbox(label="输出结果"),
    title="我的 Gradio 应用",
    description="这是一个简单的问候应用",
    theme="default",
    css=".gradio-container {background-color: #f0f0f0;}"
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)
# Gradio 两大核心页面:

# 2、Blocks():适合复杂任务(多输入多输出)、需要动态交互(如按钮点击、条件渲染)、高度定制化布局或样式

import gradio as gr

def my_function(name, is_uppercase):
    if is_uppercase:
        return name.upper()
    else:
        return name.lower()

with gr.Blocks() as demo:
    gr.Markdown("## 问候应用")
    with gr.Row():
        name = gr.Textbox(label="输入名字")
        is_uppercase = gr.Checkbox(label="输出大写")
    output = gr.Textbox(label="结果")
    submit = gr.Button("提交")
    
    # 绑定事件
    submit.click(fn=my_function, inputs=[name, is_uppercase], outputs=output)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

文本显示

# gr.Markdown() 显示 Markdown 格式文本
# gr.HTML() 显示 HTML 格式文本
# gr.Text() 显示纯文本

import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("# 这是一个标题")
    gr.Markdown("**这是粗体文本**")
    gr.HTML("<p style='color: red;'>这是红色的 HTML 文本</p>")
    gr.Text("这是普通文本")

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

数据表格

# gr.Dataframe() 显示数据表格
# headers: 表头
# datatype: 数据类型
# interactive: 是否可交互编辑

import gradio as gr
import pandas as pd

def create_dataframe():
    data = {
        '姓名': ['张三', '李四', '王五'],
        '年龄': [25, 30, 35],
        '城市': ['北京', '上海', '广州']
    }
    return pd.DataFrame(data)

iface = gr.Interface(
    fn=create_dataframe,
    inputs=None,
    outputs=gr.Dataframe(label="数据表格")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

数据图表

# gr.Plot() 显示图表(支持 matplotlib 和 plotly)

import gradio as gr
import matplotlib.pyplot as plt
import numpy as np

def create_plot():
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    plt.figure(figsize=(8, 6))
    plt.plot(x, y)
    plt.title("正弦函数")
    plt.xlabel("x")
    plt.ylabel("sin(x)")
    return plt.gcf()

iface = gr.Interface(
    fn=create_plot,
    inputs=None,
    outputs=gr.Plot(label="图表")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

进度条

# 使用 gr.Progress() 显示进度条

import gradio as gr
import time

def long_running_task(text, progress=gr.Progress()):
    progress(0, desc="开始处理...")
    for i in range(10):
        time.sleep(0.5)
        progress((i + 1) / 10, desc=f"处理中... {i+1}/10")
    return f"处理完成: {text}"

iface = gr.Interface(
    fn=long_running_task,
    inputs=gr.Textbox(label="输入文本"),
    outputs=gr.Textbox(label="处理结果")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

多标签页

# gr.Tab() 创建多标签页界面

import gradio as gr

with gr.Blocks() as demo:
    with gr.Tab("标签页1"):
        gr.Text("标签页1的内容")
    
    with gr.Tab("标签页2"):
        gr.Text("标签页2的内容")

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)
# gr.TabbedInterface() 创建多标签页界面
# interface_list: 界面列表
# tab_names: 标签页名称列表
# title: 整体标题

import gradio as gr

def text_processor(text):
    return text.upper()

def number_processor(number):
    return number * 2

def image_processor(image):
    return image

# 创建多个界面
text_interface = gr.Interface(
    fn=text_processor,
    inputs=gr.Textbox(label="输入文本"),
    outputs=gr.Textbox(label="大写文本"),
    title="文本处理"
)

number_interface = gr.Interface(
    fn=number_processor,
    inputs=gr.Number(label="输入数字"),
    outputs=gr.Number(label="双倍数字"),
    title="数字处理"
)

image_interface = gr.Interface(
    fn=image_processor,
    inputs=gr.Image(type="pil", label="上传图像"),
    outputs=gr.Image(type="pil", label="处理后图像"),
    title="图像处理"
)

# 组合成多标签页界面
demo = gr.TabbedInterface(
    interface_list=[text_interface, number_interface, image_interface],
    tab_names=["文本处理", "数字处理", "图像处理"],
    title="多功能处理平台"
)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

条件可见

# 使用 gr.update() 动态更新组件属性
# visible: 控制组件可见性
# interactive: 控制组件交互性
# value: 更新组件值

import gradio as gr

def toggle_visibility(show_advanced):
    return gr.update(visible=show_advanced)

def process_data(basic_input, advanced_input=None):
    result = f"基础输入: {basic_input}"
    if advanced_input:
        result += f"\n高级输入: {advanced_input}"
    return result

with gr.Blocks() as demo:
    basic_input = gr.Textbox(label="基础输入")
    show_advanced = gr.Checkbox(label="显示高级选项")
    
    with gr.Column(visible=False) as advanced_column:
        advanced_input = gr.Textbox(label="高级输入")
    
    output = gr.Textbox(label="输出")
    
    show_advanced.change(
        toggle_visibility,
        show_advanced,
        advanced_column
    )
    
    gr.Button("处理").click(
        process_data,
        [basic_input, advanced_input],
        output
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

条件显示

# 根据条件动态显示不同组件

import gradio as gr

def update_interface(model_type):
    if model_type == "文本分类":
        return gr.update(visible=True), gr.update(visible=False)
    else:
        return gr.update(visible=False), gr.update(visible=True)

with gr.Blocks() as demo:
    model_selector = gr.Dropdown(
        ["文本分类", "图像识别"],
        value="文本分类",
        label="选择模型类型"
    )
    
    with gr.Column(visible=True) as text_interface:
        gr.Textbox(label="输入文本")
        gr.Button("分类")
    
    with gr.Column(visible=False) as image_interface:
        gr.Image(label="上传图像")
        gr.Button("识别")
    
    model_selector.change(
        update_interface,
        model_selector,
        [text_interface, image_interface]
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

实时刷新

# 使用 gr.Timer() 实现实时数据刷新

import gradio as gr
import random

def get_real_time_data():
    return random.randint(1, 100)

def start_monitoring():
    return get_real_time_data()

with gr.Blocks() as demo:
    gr.Markdown("## 实时数据监控")
    
    data_display = gr.Number(label="实时数据", value=0)
    
    # 定时器:每秒触发一次更新
    timer = gr.Timer(value=1)  # value 表示时间间隔(单位:秒)

    # 当点击按钮时,启动定时器并初始化数据
    update_btn = gr.Button("开始监控")
    update_btn.click(
        fn=start_monitoring,
        outputs=data_display
    )

    # 将定时器的触发条件绑定到按钮的点击事件
    update_btn.click(None, None, timer)

    # 定时器触发时更新数据
    timer.tick(fn=start_monitoring, outputs=data_display)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

组件联动

# 实现多个组件之间的联动效果

import gradio as gr

def update_options(category):
    options_map = {
        "水果": ["苹果", "香蕉", "橙子"],
        "蔬菜": ["胡萝卜", "西兰花", "菠菜"],
        "肉类": ["牛肉", "猪肉", "鸡肉"]
    }
    return gr.update(choices=options_map.get(category, []), value=None)

def calculate_price(category, item, quantity):
    prices = {
        "苹果": 5, "香蕉": 3, "橙子": 4,
        "胡萝卜": 2, "西兰花": 6, "菠菜": 4,
        "牛肉": 30, "猪肉": 25, "鸡肉": 20
    }
    price = prices.get(item, 0)
    total = price * quantity
    return f"单价: {price}元, 总价: {total}元"

with gr.Blocks() as demo:
    gr.Markdown("## 商品价格计算器")
    
    category = gr.Dropdown(["水果", "蔬菜", "肉类"], label="商品类别")
    item = gr.Dropdown([], label="具体商品")
    quantity = gr.Number(value=1, label="数量")
    result = gr.Textbox(label="价格信息")
    
    # 类别变化时更新商品选项
    category.change(update_options, category, item)
    
    # 计算价格
    gr.Button("计算价格").click(
        calculate_price,
        [category, item, quantity],
        result
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

组件布局

# gr.Row() 水平布局
# gr.Column() 垂直布局
# gr.Tab() 标签页布局
# gr.Accordion() 折叠面板

import gradio as gr

with gr.Blocks() as demo:
    with gr.Row():
        gr.Text("左侧文本")
        gr.Text("右侧文本")
    
    with gr.Column():
        gr.Text("上方文本")
        gr.Text("下方文本")
    
    with gr.Tab("标签页1"):
        gr.Text("标签页1的内容")
    
    with gr.Tab("标签页2"):
        gr.Text("标签页2的内容")
    
    with gr.Accordion("点击展开"):
        gr.Text("折叠面板中的内容")

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

主题定制

# 使用 gr.themes 定制界面主题
# 可以选择预设主题或自定义主题
# 可用主题:gr.themes.Default(), gr.themes.Soft(), gr.themes.Glass(), gr.themes.Monochrome()

import gradio as gr

def simple_function(text):
    return f"处理结果: {text}"

# 使用预设主题
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 软主题示例")
    text_input = gr.Textbox(label="输入")
    output = gr.Textbox(label="输出")
    
    gr.Button("处理").click(simple_function, text_input, output)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

交互控件

文本输入

# gr.Textbox() 文本输入框
# placeholder: 占位符文本
# lines: 行数(多行文本)
# max_lines: 最大行数
# interactive: 是否可交互

import gradio as gr

def echo_text(text):
    return f"您输入的是: {text}"

with gr.Blocks() as demo:
    # 单行文本输入
    text_input = gr.Textbox(placeholder="请输入文本", label="单行输入")
    output_1 = gr.Textbox(label="单行输出")
    text_input.change(echo_text, text_input, output_1)
    
    # 多行文本输入
    text_area = gr.Textbox(lines=3, placeholder="请输入多行文本", label="多行输入")
    output_2 = gr.Textbox(label="多行输出")
    text_area.change(echo_text, text_area, output_2)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

数字输入

# gr.Number() 数字输入框
# minimum: 最小值
# maximum: 最大值
# step: 步长
# value: 默认值

import gradio as gr

def calculate_square(number):
    return number ** 2

iface = gr.Interface(
    fn=calculate_square,
    inputs=gr.Number(minimum=0, maximum=100, step=1, value=5, label="输入数字"),
    outputs=gr.Number(label="平方值")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

滑块控件

# gr.Slider() 滑块控件
# minimum: 最小值
# maximum: 最大值
# step: 步长
# value: 默认值

import gradio as gr

def multiply_by_factor(value, factor):
    return value * factor

with gr.Blocks() as demo:
    value_slider = gr.Slider(minimum=0, maximum=100, step=1, value=50, label="数值")
    factor_slider = gr.Slider(minimum=1, maximum=10, step=0.1, value=2, label="倍数")
    result = gr.Number(label="结果")
    
    gr.Button("计算").click(
        multiply_by_factor,
        inputs=[value_slider, factor_slider],
        outputs=result
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

下拉选择框

# gr.Dropdown() 下拉选择框
# choices: 选项列表
# value: 默认值
# multiselect: 是否多选
# interactive: 是否可交互

import gradio as gr

def greet_by_language(language):
    greetings = {
        "中文": "你好!",
        "English": "Hello!",
        "Français": "Bonjour!",
        "Español": "¡Hola!"
    }
    return greetings.get(language, "Hello!")

iface = gr.Interface(
    fn=greet_by_language,
    inputs=gr.Dropdown(
        choices=["中文", "English", "Français", "Español"],
        value="中文",
        label="选择语言"
    ),
    outputs=gr.Textbox(label="问候语")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

单选按钮

# gr.Radio() 单选按钮组
# choices: 选项列表
# value: 默认值
# interactive: 是否可交互

import gradio as gr

def calculate_area(shape, length, width=None):
    if shape == "正方形":
        return length ** 2
    elif shape == "长方形":
        return length * (width or 1)
    elif shape == "圆形":
        return 3.14159 * (length ** 2)
    return 0

with gr.Blocks() as demo:
    shape = gr.Radio(["正方形", "长方形", "圆形"], value="正方形", label="选择形状")
    length = gr.Number(value=5, label="长度/半径")
    width = gr.Number(value=3, label="宽度(仅长方形)")
    area = gr.Number(label="面积")
    
    gr.Button("计算面积").click(
        calculate_area,
        inputs=[shape, length, width],
        outputs=area
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

复选框

# gr.Checkbox() 复选框
# value: 默认值(True/False)
# label: 标签文本
# interactive: 是否可交互

import gradio as gr

def process_options(option1, option2, option3):
    selected = []
    if option1:
        selected.append("选项1")
    if option2:
        selected.append("选项2")
    if option3:
        selected.append("选项3")
    return f"已选择: {', '.join(selected) if selected else '无'}"

with gr.Blocks() as demo:
    cb1 = gr.Checkbox(label="选项1", value=False)
    cb2 = gr.Checkbox(label="选项2", value=True)
    cb3 = gr.Checkbox(label="选项3", value=False)
    result = gr.Textbox(label="选择结果")
    
    gr.Button("确认选择").click(
        process_options,
        inputs=[cb1, cb2, cb3],
        outputs=result
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

按钮控件

# gr.Button() 按钮控件
# value: 按钮文本
# variant: 按钮样式,可选["primary", "secondary", "stop"]
# size: 按钮大小,可选["sm", "lg"]

import gradio as gr

def button_click():
    return "按钮被点击了!"

with gr.Blocks() as demo:
    output = gr.Textbox(label="输出")
    
    # 不同样式的按钮
    gr.Button("主要按钮", variant="primary").click(
        lambda: "主要按钮被点击", outputs=output
    )
    gr.Button("次要按钮", variant="secondary").click(
        lambda: "次要按钮被点击", outputs=output
    )
    gr.Button("停止按钮", variant="stop").click(
        lambda: "停止按钮被点击", outputs=output
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

图像上传下载

# gr.Image() 显示图像
# type: 图像类型,可选["pil", "numpy", "filepath"]
# label: 组件标签
# show_label: 是否显示标签

import gradio as gr

def process_image(image):
    return image  # 直接返回原图像

iface = gr.Interface(
    fn=process_image,
    inputs=gr.Image(type="pil", label="上传图像"),
    outputs=gr.Image(type="pil", label="处理后图像")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

音频上传下载

# gr.Audio() 音频播放组件
# type: 音频类型,可选["numpy", "filepath"]
# autoplay: 是否自动播放
# format: 音频格式,可选["wav", "mp3"]

import gradio as gr
import os
import shutil
import tempfile

# 创建临时目录用于存储处理后的音频文件
tmpdir = tempfile.mkdtemp()
print(f"临时文件夹地址:{tmpdir}")

def process_audio(audio):
    if audio is None:
        return "没有音频文件"
    # 获取原始文件名
    original_filename = os.path.basename(audio)
    processed_filename = f"processed_{original_filename}"
    output_audio_path = os.path.join(tmpdir, processed_filename)
    # 复制音频文件到临时目录(此处可替换为实际的音频处理逻辑)
    shutil.copy(audio, output_audio_path)
    # 返回处理后的音频路径
    return output_audio_path

iface = gr.Interface(
    fn=process_audio,
    inputs=gr.Audio(type="filepath", label="上传音频"),
    outputs=gr.Audio(type="filepath", label="处理后的音频(可播放和下载)"),
    title="音频处理与下载",
    description="上传音频后,系统将处理并生成可播放和下载的音频文件。"
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

视频上传下载

# gr.Video() 显示和播放视频
# label: 组件标签

import gradio as gr

def process_video(video):
    return video  # 直接返回原视频

iface = gr.Interface(
    fn=process_video,
    inputs=gr.Video(label="上传视频"),
    outputs=gr.Video(label="处理后视频")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

文件上传下载

# gr.File() 文件上传组件
# file_count: 文件数量,"single" 或 "multiple"
# file_types: 允许的文件类型列表,如[".txt", ".pdf", ".docx"]
# label: 组件标签

import gradio as gr
import os
import tempfile

# 创建临时目录用于存储上传的文件
tmpdir = tempfile.mkdtemp()
print(f"临时文件夹地址:{tmpdir}")

def process_file(file):
    if file is None:
        return "没有上传文件", None
    # 获取上传文件的路径
    file_path = file.name
    # 获取文件大小
    file_size = os.path.getsize(file_path)
    # 返回文件信息(字符串)和文件路径(用于下载)
    file_info = f"文件名: {file_path}\n文件大小: {file_size} 字节"
    return file_info, file_path  # 返回两个输出值

iface = gr.Interface(
    fn=process_file,
    inputs=gr.File(
        file_count="single",
        file_types=[".txt", ".pdf", ".docx"],
        label="上传文件"
    ),
    outputs=[
        gr.Textbox(label="文件信息"),
        gr.File(label="下载文件")
    ],
    title="文件上传与下载",
    description="上传文件后,系统将展示文件信息并提供下载链接。"
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

其他特性

状态管理

# gr.State() 状态管理组件,用于在多次交互间保持数据

import gradio as gr

def increment_counter(count):
    return count + 1, count + 1

def reset_counter():
    return 0, 0

with gr.Blocks() as demo:
    counter_state = gr.State(value=0)
    counter_display = gr.Number(value=0, label="计数器")
    
    gr.Button("增加").click(
        increment_counter,
        inputs=counter_state,
        outputs=[counter_display, counter_state]
    )
    
    gr.Button("重置").click(
        reset_counter,
        outputs=[counter_display, counter_state]
    )

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

事件处理

# 常用事件:click, change, submit, upload, select
# 事件绑定语法:组件.事件名(函数, inputs=输入, outputs=输出)

import gradio as gr

def on_text_change(text):
    return f"实时输入: {text}"

def on_button_click(text):
    return f"按钮点击: {text}"

with gr.Blocks() as demo:
    text_input = gr.Textbox(placeholder="输入文本", label="输入框")
    output1 = gr.Textbox(label="实时输出")
    output2 = gr.Textbox(label="点击输出")
    
    # 文本变化事件
    text_input.change(on_text_change, text_input, output1)
    
    # 按钮点击事件
    gr.Button("处理文本").click(on_button_click, text_input, output2)

demo.launch(
    server_name="0.0.0.0",
    server_port=7860
)

聊天界面

# gr.ChatInterface() 创建聊天界面
# fn: 聊天处理函数
# chatbot: 聊天机器人组件
# textbox: 输入框组件

import gradio as gr

def chat_response(message, history):
    # 简单的聊天机器人逻辑
    if "你好" in message:
        return "你好!有什么可以帮助你的吗?"
    elif "再见" in message:
        return "再见!祝你有美好的一天!"
    else:
        return f"我收到了你的消息:{message}"

chat_interface = gr.ChatInterface(
    fn=chat_response,
    title="简单聊天机器人",
    description="与AI助手对话"
)

chat_interface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

进阶使用

多页面应用

  • 【目标】

    • 实现多应用展示:构建具有多个页面的Web应用,每个页面专注于不同的任务。

    • 子页面独立开发:确保每个子页面应用的代码逻辑清晰,独立于其他应用,便于开发和后续维护。

    • 算法与框架分离:将算法实现和框架结构分开存储,以促进代码的复用和扩展性。


  • 【方案】

    • 主页面

      • 提供页面路由:负责供用户选择要查看的子页面应用

      • 使用字典映射:键为子应用名称,值为子应用模块的引用

      • 保持文件简洁:仅负责页面路由和布局设置,具体功能实现在子应用中

    • 子页面

      • 每个子页面都是一个独立的子应用

      • 每个子应用使用 app() 函数封装子应用的逻辑流程和界面元素

      • 每个子应用创建独立的 py 文件,专注于某个特定的任务,与界面UI逻辑解耦


项目文件结构

my_project
├── main_app.py # 主页面
└── subpages # 子页面
    ├── __init__.py # 子页面配置文件
    ├── home.py # 子页面 1 首页模块
    ├── analysis.py # 子页面 2 数据分析模块
    └── prediction.py # 子页面 3 预测模块

主页面

# my_project/main_app.py

import gradio as gr
# 导入子页面
from subpages import home, analysis, prediction

def create_app():
    with gr.Blocks(title="模块化多页面应用") as app:
        gr.Markdown("# AI 多功能平台")
        with gr.Tabs():
            with gr.Tab("首页"):
                home.create_home_interface()
            with gr.Tab("数据分析"):
                analysis.create_analysis_interface()
            with gr.Tab("模型预测"):
                prediction.create_prediction_interface()
    return app

if __name__ == "__main__":
    app = create_app()
    app.launch(
    server_name="0.0.0.0",
    server_port=7860
)

子页面

# my_project/subpages/__init__.py

__author__ = "Faramita"
__version__ = "1.0"
# my_project/subpages/home.py

import gradio as gr

def create_home_interface():
    gr.Markdown("## 欢迎使用AI平台")
    gr.Markdown("这是一个集成多种AI功能的平台")
    
    with gr.Row():
        gr.Markdown("### 功能特色")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("- 数据分析")
            gr.Markdown("- 模型预测")
        with gr.Column():
            gr.Markdown("- 可视化展示")
            gr.Markdown("- 实时处理")
# my_project/subpages/analysis.py

import gradio as gr
import pandas as pd

def analyze_data(file):
    if file is None:
        return "请上传CSV文件"
    try:
        df = pd.read_csv(file.name)
        return f"数据形状: {df.shape}\n列名: {list(df.columns)}"
    except Exception as e:
        return f"分析失败: {str(e)}"

def create_analysis_interface():
    gr.Markdown("## 数据分析模块")

    file_input = gr.File(label="上传CSV文件", file_types=[".csv"])
    analysis_result = gr.Textbox(label="分析结果", lines=5)
    
    gr.Button("开始分析").click(
        analyze_data,
        inputs=file_input,
        outputs=analysis_result
    )
# my_project/subpages/prediction.py

import gradio as gr

def predict_sentiment(text):
    # 简单的情感分析模拟
    positive_words = ['好', '棒', '优秀', '喜欢', 'good', 'great', 'excellent']
    negative_words = ['坏', '差', '糟糕', '讨厌', 'bad', 'terrible', 'awful']
    
    text_lower = text.lower()
    positive_count = sum(1 for word in positive_words if word in text_lower)
    negative_count = sum(1 for word in negative_words if word in text_lower)
    
    if positive_count > negative_count:
        return "正面情感", 0.8
    elif negative_count > positive_count:
        return "负面情感", 0.8
    else:
        return "中性情感", 0.5

def create_prediction_interface():
    gr.Markdown("## 情感预测模块")
    
    text_input = gr.Textbox(label="输入文本", placeholder="请输入要分析的文本")
    
    with gr.Row():
        sentiment_output = gr.Textbox(label="情感倾向")
        confidence_output = gr.Number(label="置信度")
    
    gr.Button("开始预测").click(
        predict_sentiment,
        inputs=text_input,
        outputs=[sentiment_output, confidence_output]
    )

大文件内存优化

# 处理大文件和内存优化

import gradio as gr
import gc
import psutil
import os

def get_memory_usage():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss / 1024 / 1024  # MB

def memory_efficient_processing(file):
    if file is None:
        return "请上传文件"
    initial_memory = get_memory_usage()
    try:
        # 分块读取大文件
        chunk_size = 1024 * 1024  # 1MB chunks
        total_size = 0
        with open(file.name, 'rb') as f:
            while True:
                chunk = f.read(chunk_size)
                if not chunk:
                    break
                total_size += len(chunk)
                # 定期清理内存
                if total_size % (10 * chunk_size) == 0:
                    gc.collect()
        final_memory = get_memory_usage()
        memory_used = final_memory - initial_memory
        return f"文件大小: {total_size} 字节\n内存使用: {memory_used:.2f} MB"
    except Exception as e:
        return f"处理失败: {str(e)}"
    finally:
        gc.collect()  # 强制垃圾回收

iface = gr.Interface(
    fn=memory_efficient_processing,
    inputs=gr.File(label="上传大文件"),
    outputs=gr.Textbox(label="处理结果")
)

iface.launch(
    server_name="0.0.0.0",
    server_port=7860
)

1
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区