Gradio Interface 和 ChatInterface 布局都相对固定,只能通过参数添加组件,如果想要自定义页面布局,就需要更高级的布局方式 Block
。Gradio 中可以通过行和列进行布局,可以互相嵌套。我们先看一官方的例子:
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("https://random.imagecdn.app/500/500")
btn = gr.Button("Go")
demo.launch()
上面是一个嵌套的例子,行列嵌套。如果想做一个多标签页的效果怎么实现呢?通过 TabInterface 组合在一起,看下面这个例子。
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("https://random.imagecdn.app/500/500")
btn = gr.Button("Go")
with gr.Blocks() as demo1:
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("https://random.imagecdn.app/500/500")
btn = gr.Button("Go")
with gr.Blocks() as demo3:
tabTemo = gr.TabbedInterface([demo, demo1], ["Hello World", "Bye World"])
b22 = gr.Button("GoGo")
demo3.launch()
这样写,维护起来就很麻烦,可以不使用 with 的方式,直接用对象的方式调用放回 block,可以做到模块化,便于维护。
demo3 = gr.Blocks()
demo3.append(tabTemo)
b22 = gr.Button("GoGo")
demo3.append(b22)
demo3.launch()
最后需要将按钮和输入输出绑定在一起进行逻辑处理。通过 click 方法传入三个参数,输入组件、输出组件、API 名称,API 名称是对外接口名。
btn.click(fn=greet, inputs=text1, outputs=text2, api_name="greet")
inbtw.click(fn=greet, inputs=text2, outputs=text4, api_name="greet1")
总结
Gradio 复杂布局通过行列嵌套 Block 实现,除了 Block 布局,Gradio 也支持自定义组件,组件的开发方式在下篇文章中进行介绍。