gradio 自定义组件
package
本文字数:382 字 | 阅读时长 ≈ 1 min

gradio 自定义组件

package
本文字数:382 字 | 阅读时长 ≈ 1 min

除了之前介绍的 interface 类,gradio 还允许自定义组件,可以处理复杂的数据流,例如可以将某一个函数的输出作为另一个函数的输入

1. Blocks 的简单式子

1.1 一个简单的 greet 例子

import gradio as gr
def greet(name):
    return "Hello " + name + "!"
with gr.Blocks() as demo:
    #设置输入组件
    name = gr.Textbox(label="Name")
    # 设置输出组件
    output = gr.Textbox(label="Output Box")
    #设置按钮
    greet_btn = gr.Button("Greet")
    #设置按钮点击事件
    greet_btn.click(fn=greet, inputs=name, outputs=output)
demo.launch()

下面展示了输出结果,其中按钮 submit 变为了 greet

1.2 如何使用多个模块

import numpy as np
import gradio as gr
def flip_text(x):
    return x[::-1]
def flip_image(x):
    return np.fliplr(x)
with gr.Blocks() as demo:
    #用markdown语法编辑输出一段话
    gr.Markdown("Flip text or image files using this demo.")
    # 设置tab选项卡
    with gr.Tab("Flip Text"):
        #Blocks特有组件,设置所有子组件按垂直排列
        #垂直排列是默认情况,不加也没关系
        with gr.Column():
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        #Blocks特有组件,设置所有子组件按水平排列
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")
    #设置折叠内容
    with gr.Accordion("Open for More!"):
        gr.Markdown("Look at me...")
    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)
demo.launch()

例子也不难,配合注释可以很好的理解,下面展示两个模块的结构

4月 06, 2025
3月 10, 2025
12月 31, 2024