Gradio 基础使用示例

Gradio 基础使用示例

简介

  • Gradio 是一个用于构建快速原型和部署机器学习应用程序的开源库。它的目标是使机器学习模型的创建和部署变得简单易用,无需深入了解 Web 开发或前端知识。
  • 以下是 Gradio 的一些关键特点和优势:
    1. 简单易用: Gradio 提供了简单直观的 API,使得用户能够快速创建交互式的机器学习界面,无需繁琐的代码编写。
    2. 多样化输入输出: Gradio 支持多种类型的输入和输出,包括图像、文本、音频等,同时还能够处理多个输入和输出。
    3. 即时预览: 在开发过程中,Gradio 提供了即时预览功能,让用户可以实时查看和测试他们的应用程序,以便进行调试和优化。
    4. 部署简单: Gradio 允许用户一键部署他们的应用程序,无需复杂的配置或部署流程,可以将应用程序轻松地分享给其他人使用。
    5. 可定制性: 尽管 Gradio 提供了许多预定义的组件和样式,但用户仍然可以通过自定义 CSS 和 JavaScript 来定制界面的外观和行为。
    6. 跨平台兼容性: Gradio 可以在多个平台上运行,包括本地环境、云端服务器以及基于 Docker 的容器中。
  • 总的来说,Gradio 提供了一个简单而强大的工具,使得任何人都能够轻松地构建和部署交互式的机器学习应用程序,从而促进了机器学习技术的普及和应用。
  • 当然,你也可以用 Gradio 来做一些简单功能的可视化,以便于日常使用,不是非要应用到AI方面。
  • 更多案例

安装

  • $ pip install gradio==4.29 -i "https://pypi.doubanio.com/simple/"
  • 当前安装的版本信息,输出如下
Successfully installed aiofiles-23.2.1 altair-5.3.0 attrs-23.2.0 contourpy-1.2.1 cycler-0.12.1 ffmpy-0.3.2 filelock-3.14.0 fonttools-4.51.0 fsspec-2024.3.1 gradio-4.29.0 gradio-client-0.16.1 httpcore-1.0.5 httpx-0.27.0 huggingface-hub-0.23.0 importlib-resources-6.4.0 jsonschema-4.22.0 jsonschema-specifications-2023.12.1 kiwisolver-1.4.5 markdown-it-py-3.0.0 matplotlib-3.8.4 mdurl-0.1.2 orjson-3.10.3 pillow-10.3.0 pydub-0.25.1 pygments-2.18.0 pyparsing-3.1.2 python-multipart-0.0.9 referencing-0.35.1 requests-2.31.0 rich-13.7.1 rpds-py-0.18.1 ruff-0.4.3 semantic-version-2.10.0 shellingham-1.5.4 tomlkit-0.12.0 typer-0.12.3 urllib3-2.2.1 websockets-11.0.3

示例-简单的输入、输出

import gradio as gr

print(gr.__version__)

def process_data(text, image, filter_type):
    print(type(image))
    # 数据处理逻辑
    processed_text = text.upper()
    if filter_type:
        image = image.convert(filter_type)
    return processed_text, image


iface = gr.Interface(
    fn=process_data,
    inputs=[
        gr.Textbox(label="输入文本"),
        gr.Image(label="上传图片", type="pil"),
        gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), 
    ],
    outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")],
    title="文本、图像处理",
    description="输入文本、图像,以获得处理。",
)

iface.launch()

image.png

示例-启动配置

  • 一些常用的启动配置说明
# 设置启动端口
iface.launch(server_name='127.0.0.1', server_port=8080, show_error=True)
# 当把server_name设置为'0.0.0.0'时,局域网内的电脑皆可通过服务器IP访问该服务
iface.launch(server_name='0.0.0.0')

# 在互联网分享(Gradio的服务器会提供XXX.gradio.app地址)
iface.launch(share=True)

# 设置用户、密码
iface.launch(auth=("admin", "admin12345"))
# 更复杂的用户、密码校验
def my_auth(username, password):
    # 例如可以连接到外部系统校验登录
    return username == "admin" and password == "admin12345"
iface.launch(auth=my_auth, auth_message="login error")

# 启动服务时,自动打开默认浏览器
face.launch(inbrowser=True)

示例-聊天对话

  • 聊天接口
  • 通过使用yield,可以实现流式响应 Streaming outputs
import gradio as gr
import time

print(gr.__version__)

def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.05)
        yield "机器人回复: " + message[: i+1]

iface = gr.ChatInterface(slow_echo).queue()

iface.launch()

image.png

示例-多页面Tab切换

  • 最简单的
import gradio as gr
import time

def function1(input1):
    return f"处理结果: {input1}"

def function2(input2):
    return f"分析结果: {input2}"

iface1 = gr.Interface(function1, "text", "text")
iface2 = gr.Interface(function2, "text", "text")

tabbed_interface = gr.TabbedInterface([iface1, iface2], ["界面1", "界面2"])
tabbed_interface.launch()

image.png

  • 结合前面2个示例
import gradio as gr
import time

def process_data(text, image, filter_type):
    print(type(image))
    # 数据处理逻辑
    processed_text = text.upper()
    if filter_type:
        image = image.convert(filter_type)
    return processed_text, image

base_iface = gr.Interface(
    fn=process_data,
    inputs=[
        gr.Textbox(label="输入文本"),
        gr.Image(label="上传图片", type="pil"),
        gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), 
    ],
    outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")],
    title="文本、图像处理",
    description="输入文本、图像,以获得处理。",
)

def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.05)
        yield "机器人回复: " + message[: i+1]

chat_iface = gr.ChatInterface(slow_echo).queue()

tabbed_interface = gr.TabbedInterface([base_iface, chat_iface], ["基础界面", "聊天界面"])
tabbed_interface.launch()

image.png

示例-使用Block自定义布局

import gradio as gr
import time



def process_data(text, image, filter_type):
    print(type(image))
    # 数据处理逻辑
    processed_text = text.upper()
    if filter_type:
        image = image.convert(filter_type)
    return processed_text, image

base_iface = gr.Interface(
    fn=process_data,
    inputs=[
        gr.Textbox(label="输入文本"),
        gr.Image(label="上传图片", type="pil"),
        gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), 
    ],
    outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")],
    title="文本、图像处理",
    description="输入文本、图像,以获得处理。",
)



def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.05)
        yield "机器人回复: " + message[: i+1]

chat_iface = gr.ChatInterface(slow_echo).queue()



with gr.Blocks() as block1_iface:
    # 多个Row,均分纵轴
    with gr.Row():
        # 多个Column,则均分横纵
        with gr.Column():
            input_text = gr.Textbox(label="输入")
            submit_button = gr.Button("提交")
        with gr.Column():
            output_text = gr.Label(label="输出")

    submit_button.click(fn=lambda x: f"你输入了: {x}", inputs=input_text, outputs=output_text)



with gr.Blocks() as block2_iface:
    # Group 连接2个组件
    with gr.Group():
        input1 = gr.Textbox()
        input2 = gr.Slider()
    # Accordion 连接2个组件,并包含,并有标题提示
    with gr.Accordion("详细设置"):
        checkbox = gr.Checkbox(label="选项")
        dropdown = gr.Dropdown(choices=["选项1", "选项2"])

    submit_button = gr.Button("提交")
    output_label = gr.Label()

    submit_button.click(fn=lambda x, y, z: f"{x}, {y}, {z}", inputs=[input1, input2, checkbox], outputs=output_label)



with gr.Blocks() as block3_iface:
    with gr.Row():
        with gr.Column():
                input_text = gr.Textbox(label="输入文本")
                with gr.Group():
                    input_image = gr.Image(label="上传图片", type="pil")
                    input_mode = gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L")
                submit_button = gr.Button("提交")
        with gr.Column():
            output_text = gr.Text(label="处理后的文本")
            output_image = gr.Image(label="处理后的图片")

    submit_button.click(fn=process_data, inputs=[input_text, input_image, input_mode], outputs=[output_text, output_image])



tabbed_interface = gr.TabbedInterface(
    [base_iface, chat_iface, block1_iface, block2_iface, block3_iface], 
    ["基础界面", "聊天界面", "Block1界面", "Block2界面", "Block3界面"]
)
tabbed_interface.launch()

image.png

示例-Plot绘图

import gradio as gr
import pandas as pd

# pip install plotly
import plotly.express as px
import matplotlib.pyplot as plt


def explore_data(dataset, columns):
    df = pd.read_csv(dataset)
    # plotly库,自带功能更多
    # fig = px.scatter(df, x=columns[0], y=columns[1])

    # matplotlib库
    fig = plt.figure()
    plt.scatter(df[columns[0]], df[columns[1]])
    plt.xlabel(columns[0])
    plt.ylabel(columns[1])
    return fig


demo = gr.Interface(
    fn=explore_data,
    inputs=[
        gr.File(label="上传CSV文件"),
        gr.CheckboxGroup(choices=["num", "age", "tall"], label="选择列"),
    ],
    outputs=gr.Plot(),
)
demo.launch()

image.png

  • 数据可视化探索工具
import gradio as gr
import pandas as pd

# pip install seaborn
import seaborn as sns
import matplotlib.pyplot as plt


def plot_data(file, chart_type):
    df = pd.read_csv(file)
    if chart_type == "柱状图":
        plt.figure(figsize=(10, 6))
        sns.barplot(data=df)
    elif chart_type == "折线图":
        plt.figure(figsize=(10, 6))
        sns.lineplot(data=df)
    plt.tight_layout()
    return plt


iface = gr.Interface(
    plot_data, 
    inputs=[gr.File(), gr.Dropdown(["柱状图", "折线图"])], 
    outputs="plot"
)
iface.launch()

image.png

示例-状态管理

import gradio as gr

def update_output(input_text, state_obj):
    state_obj = state_obj or 0
    state_obj += 1
    return f"您输入了:{input_text}", f"状态值:{state_obj}", state_obj

# gr.State() 是会话级状态
# 全局状态,直接在代码里面定义一个state_obj变量即可
iface = gr.Interface(
    fn=update_output,
    inputs=[gr.Textbox(), gr.State()],
    outputs=[gr.Textbox(), gr.Label(), gr.State()]
)
iface.launch()

image.png

示例-提示、进度条

def start_process(name):
    gr.Info("Starting process")
    if name is None:
        gr.Warning("Name is empty")
    ...
    if success == False:
        raise gr.Error("Process failed")
  • 进度条
import gradio as gr
import time

def slowly_reverse(word, progress=gr.Progress()):
    progress(0, desc="Starting")
    time.sleep(1)
    progress(0.05)
    new_string = ""
    for letter in progress.tqdm(word, desc="Reversing"):
        time.sleep(0.25)
        new_string = letter + new_string
    return new_string

demo = gr.Interface(slowly_reverse, gr.Text(), gr.Text())

demo.launch()

image.png

  • 进度条(通过设置gr.Progress(track_tqdm=True),自动追踪tqdm,显示进度)
import gradio as gr
import time
import tqdm

# gr.Progress(track_tqdm=True) 必须写在方法入参这里
def slowly_reverse2(word, progress=gr.Progress(track_tqdm=True)):
    time.sleep(1)
    new_string = ""
    tqdm_progress = tqdm.tqdm(word, desc="Reversing")
    for letter in tqdm_progress:
        time.sleep(0.25)
        new_string = letter + new_string
    return new_string

demo = gr.Interface(slowly_reverse2, gr.Text(), gr.Text())

demo.launch()

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值