Gradio 智能体 & MCP 黑客马拉松

获奖者
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")

你可以设置行中的每个元素具有相同的高度。使用 `equal_height` 参数进行配置。

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

行中元素的宽度可以通过每个组件都具有的 `scale` 和 `min_width` 参数组合来控制。

  • `scale` 是一个整数,定义元素在行中占用空间的方式。如果 `scale` 设置为 `0`,元素将不会扩展以占用空间。如果 `scale` 设置为 `1` 或更大,元素将扩展。一行中的多个元素将按其比例扩展。在下方示例中,`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` 值,行将换行。

文档中了解更多关于行的信息。

列和嵌套

列中的组件将垂直堆叠。由于垂直布局是 Blocks 应用的默认布局,为了实用,列通常嵌套在行中。例如

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()

看看第一列中有两个垂直排列的文本框。第二列中有一个垂直排列的图片和按钮。请注意,两列的相对宽度是如何通过 `scale` 参数设置的。`scale` 值是两倍的列占据的宽度也是两倍。

文档中了解更多关于列的信息。

填充浏览器高度/宽度

要使应用占据浏览器的全部宽度,并移除侧边填充,请使用 `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 语句会组合在一起,以便一次只能选择一个选项卡,并且只显示该选项卡上下文内的组件。

例如

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` 参数,可以进行初始设置和更新。在列上设置 `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()

同样,如果你已经在 Gradio 应用中定义了一个组件,但希望取消渲染它以便在应用的另一个部分定义它,那么你可以调用 `.unrender()` 方法。在以下示例中,`Textbox` 将出现在第三列中

import gradio as gr

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            gr.Markdown("Row 1")
            textbox = gr.Textbox()
        with gr.Column():
            gr.Markdown("Row 2")
            textbox.unrender()
        with gr.Column():
            gr.Markdown("Row 3")
            textbox.render()

demo.launch()