gradio的函数输入输出类型,一般只有以下几种:
Image、Label、Text/Textbox、Checkbox、Number
下面是一个多输入和输出的例子:
import gradio as gr
def greet(name, is_morning, temperature):
salutation = "Good morning" if is_morning else "Good evening"
greeting = salutation + ", " + name + "! "
celsius = (temperature - 32) * 5.0/9.0
return greeting, round(celsius, 2)
demo = gr.Interface(fn=greet, inputs=["text","checkbox",gr.Slider(0,100,value=17)], outputs=["text","number"])
demo.launch()
提供了文本输入、选择框选项选择、滚动条调节,通过greet函数处理,输出文本和数字。
gradio常用的几个组件:
(1)TabbedInterface:用于在应用中创建多个标签页,每个标签页可以包含不同界面与功能。
def function1(input1):
return f"结果:{input1}"
def function2(input2):
return f"结果:{input2}"
tab1 = gr.Interface(function1,"text","text")
tab2 = gr.Interface(function2,"text","text")
tabbed_interface = gr.TabbedInterface([tab1, tab2], ["Tab 1", "Tab 2"])
tabbed_interface.launch()
(2)Blocks布局
创建一个blocks对象,使用with语句将它作为上下文环境,定义布局、添加组件或设置事件,最后调用lauch方法启动应用程序。
def update(name):
return f"Hello {name} !"
with gr.Blocks() as demo:
gr.Markdown("# Hello Gradio")
with gr.Row():
inp = gr.Textbox(placeholder= "what is your name?")
out = gr.Textbox()
btn = gr.Button("Run")
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()
如果去掉“with gr.Row()”, 内容将竖向排列。