Gradio 月活用户达到 100 万的历程!

阅读更多
Gradio logo
  1. 使用 Blocks 构建
  2. 控制布局

控制布局

默认情况下,Blocks 中的组件是垂直排列的。让我们看看如何重新排列组件。在底层,这种布局结构使用 web 开发的 flexbox 模型

with gr.Row 子句中的元素都将水平显示。例如,要并排显示两个按钮

with gr.Blocks() as demo:
    with gr.Row():
        btn1 = gr.Button("Button 1")
        btn2 = gr.Button("Button 2")

您可以将 Row 中的每个元素设置为具有相同的高度。使用 equal_height 参数配置此项。

with gr.Blocks() as demo:
    with gr.Row(equal_height=True):
        textbox = gr.Textbox()
        btn2 = gr.Button("Button 2")

Row 中元素的宽度可以通过每个组件中都存在的 scalemin_width 参数的组合来控制。

  • scale 是一个整数,定义元素在 Row 中占用空间的方式。如果 scale 设置为 0,则元素不会扩展以占用空间。如果 scale 设置为 1 或更大,则元素将扩展。行中的多个元素将按比例扩展其 scale。在下面,btn2 将扩展的量是 btn1 的两倍,而 btn0 将根本不扩展
with gr.Blocks() as demo:
    with gr.Row():
        btn0 = gr.Button("Button 0", scale=0)
        btn1 = gr.Button("Button 1", scale=1)
        btn2 = gr.Button("Button 2", scale=2)
  • min_width 将设置元素将占用的最小宽度。如果没有足够的空间来满足所有 min_width 值,Row 将会换行。

文档中了解有关 Row 的更多信息。

列和嵌套

Column 中的组件将彼此垂直放置。由于垂直布局无论如何都是 Blocks 应用的默认布局,因此为了有用,Columns 通常嵌套在 Rows 中。例如

import gradio as gr

with gr.Blocks() as demo:
    with gr.Row():
        text1 = gr.Textbox(label="t1")
        slider2 = gr.Textbox(label="s2")
        drop3 = gr.Dropdown(["a", "b", "c"], label="d3")
    with gr.Row():
        with gr.Column(scale=1, min_width=300):
            text1 = gr.Textbox(label="prompt 1")
            text2 = gr.Textbox(label="prompt 2")
            inbtw = gr.Button("Between")
            text4 = gr.Textbox(label="prompt 1")
            text5 = gr.Textbox(label="prompt 2")
        with gr.Column(scale=2, min_width=300):
            img1 = gr.Image("images/cheetah.jpg")
            btn = gr.Button("Go")

demo.launch()

看看第一个 column 如何垂直排列了两个 Textbox。第二个 column 如何垂直排列了一个 Image 和 Button。请注意,两个 column 的相对宽度是如何通过 scale 参数设置的。scale 值是两倍的 column 占用的宽度是另一列的两倍。

文档中了解有关 Column 的更多信息。

填充浏览器高度/宽度

要使应用占据浏览器的完整宽度(通过删除侧面内边距),请使用 gr.Blocks(fill_width=True)

要使顶级组件扩展以占据浏览器的完整高度,请使用 fill_height 并将 scale 应用于扩展组件。

import gradio as gr

with gr.Blocks(fill_height=True) as demo:
    gr.Chatbot(scale=1)
    gr.Textbox(scale=0)

尺寸

某些组件支持设置高度和宽度。这些参数接受数字(解释为像素)或字符串。使用字符串可以直接将任何 CSS 单位应用于封装的 Block 元素。

下面是一个示例,说明了视口宽度 (vw) 的用法

import gradio as gr

with gr.Blocks() as demo:
    im = gr.ImageEditor(width="50vw")

demo.launch()

选项卡和手风琴

您还可以使用 with gr.Tab('tab_name'): 子句创建选项卡。在 with gr.Tab('tab_name'): 上下文中创建的任何组件都将显示在该选项卡中。连续的 Tab 子句组合在一起,以便一次可以选择单个选项卡,并且仅显示该 Tab 上下文中的组件。

例如

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:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tab("Flip Text"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    with gr.Accordion("Open for More!", open=False):
        gr.Markdown("Look at me...")
        temp_slider = gr.Slider(
            0, 1,
            value=0.1,
            step=0.1,
            interactive=True,
            label="Slide 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()

另请注意此示例中的 gr.Accordion('label')。手风琴是一种可以切换打开或关闭的布局。与 Tabs 类似,它是一种可以选择性地隐藏或显示内容的布局元素。在 with gr.Accordion('label'): 内定义的任何组件都将在单击手风琴的切换图标时隐藏或显示。

在文档中了解有关选项卡手风琴的更多信息。

侧边栏是一个可折叠面板,可在屏幕左侧渲染子组件,并且可以展开或折叠。

例如

import gradio as gr
import random

def generate_pet_name(animal_type, personality):
    cute_prefixes = ["Fluffy", "Ziggy", "Bubbles", "Pickle", "Waffle", "Mochi", "Cookie", "Pepper"]
    animal_suffixes = {
        "Cat": ["Whiskers", "Paws", "Mittens", "Purrington"],
        "Dog": ["Woofles", "Barkington", "Waggins", "Pawsome"],
        "Bird": ["Feathers", "Wings", "Chirpy", "Tweets"],
        "Rabbit": ["Hops", "Cottontail", "Bouncy", "Fluff"]
    }

    prefix = random.choice(cute_prefixes)
    suffix = random.choice(animal_suffixes[animal_type])

    if personality == "Silly":
        prefix = random.choice(["Sir", "Lady", "Captain", "Professor"]) + " " + prefix
    elif personality == "Royal":
        suffix += " the " + random.choice(["Great", "Magnificent", "Wise", "Brave"])

    return f"{prefix} {suffix}"

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    with gr.Sidebar(position="left"):
        gr.Markdown("# 🐾 Pet Name Generator")
        gr.Markdown("Use the options below to generate a unique pet name!")

        animal_type = gr.Dropdown(
            choices=["Cat", "Dog", "Bird", "Rabbit"],
            label="Choose your pet type",
            value="Cat"
        )
        personality = gr.Radio(
            choices=["Normal", "Silly", "Royal"],
            label="Personality type",
            value="Normal"
        )

    name_output = gr.Textbox(label="Your pet's fancy name:", lines=2)
    generate_btn = gr.Button("Generate Name! 🎲", variant="primary")
    generate_btn.click(
        fn=generate_pet_name,
        inputs=[animal_type, personality],
        outputs=name_output
    )

demo.launch()

在文档中了解有关侧边栏的更多信息。

可见性

组件和布局元素都有一个 visible 参数,可以用来设置初始状态和更新状态。在 Column 上设置 gr.Column(visible=...) 可以用来显示或隐藏一组组件。

import gradio as gr

with gr.Blocks() as demo:
    name_box = gr.Textbox(label="Name")
    age_box = gr.Number(label="Age", minimum=0, maximum=100)
    symptoms_box = gr.CheckboxGroup(["Cough", "Fever", "Runny Nose"])
    submit_btn = gr.Button("Submit")

    with gr.Column(visible=False) as output_col:
        diagnosis_box = gr.Textbox(label="Diagnosis")
        patient_summary_box = gr.Textbox(label="Patient Summary")

    def submit(name, age, symptoms):
        return {
            submit_btn: gr.Button(visible=False),
            output_col: gr.Column(visible=True),
            diagnosis_box: "covid" if "Cough" in symptoms else "flu",
            patient_summary_box: f"{name}, {age} y/o",
        }

    submit_btn.click(
        submit,
        [name_box, age_box, symptoms_box],
        [submit_btn, diagnosis_box, patient_summary_box, output_col],
    )

demo.launch()

分别定义和渲染组件

在某些情况下,您可能希望在实际在 UI 中渲染它们之前定义组件。例如,您可能希望在相应的 gr.Textbox 输入框上方显示一个使用 gr.Examples 的示例部分。由于 gr.Examples 需要将输入组件对象作为参数,您将需要首先定义输入组件,然后在定义 gr.Examples 对象之后再渲染它。

对此的解决方案是在 gr.Blocks() 作用域之外定义 gr.Textbox,并在您希望将其放置在 UI 中的任何位置使用组件的 .render() 方法。

这是一个完整的代码示例

input_textbox = gr.Textbox()

with gr.Blocks() as demo:
    gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
    input_textbox.render()