丰富组件。
raise gr.Error("Cannot divide by zero!")
Interface 默认布局左右两栏,函数有三个参数:处理函数,输入,输出
def greet(name):
return "Hello, " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
以上表示,用户输入文本,经过 greet 处理后,输出文本。此外可以输入文字,图片,选项框等
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(lines=2, placeholder="Name Here...", label="Input Your Name"),
outputs="text",
)
以上输入是一个多行的文本框。
def greet(name, is_morning, temperature):
salutation = "Good morning" if is_morning else "Good evening"
greeting = f"{salutation} {name}. It is {temperature} degrees today"
celsius = (temperature - 32) * 5 / 9
return greeting, round(celsius, 2)
demo = gr.Interface(
fn=greet,
inputs=["text", "checkbox", gr.Slider(0, 100)],
outputs=["text", "number"],
)
以上输入三个表单,界面将在左边显示文本框,选择按钮,滑动按钮供用户操作。同时greet函数就需要定义三个输入变量,两个输出变量
iface = gr.Interface(
greet,
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number", gr.Image(source="webcam", streaming=True)],
"number",
live=True,
)
live=True设置流模式,图片设置来源于摄像头
相比 Interface 而言,Blocks可定制更强。
with gr.Blocks() as demo:
with gr.Row():
img1 = gr.Image()
text1 = gr.Text()
btn1 = gr.Button("button")
以上 gr.Row 定义一行,左边图片,右边输入框。Blocks默认列布局,所以第一列是gr.Row,第二列是一按钮。
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!"):
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)
以上定义了一个Tab,包含两个选项卡,一个是文本翻转,一个是图片翻转。最后定义按钮点击事件。
img = gr.Image("lion.jpg").style(height='24', rounded=False)
当请求时间很长,保证websocket连接不断开,开启。
demo = gr.Interface(...).queue()
# 或
with gr.Blocks() as demo:
pass
demo.queue()
每隔1s生成一张图片,共生成steps张图片。
import gradio as gr
import numpy as np
import time
#生成steps张图片,每隔1秒钟返回
def fake_diffusion(steps):
for _ in range(steps):
time.sleep(1)
image = np.random.randint(255, size=(300, 600, 3))
yield image
demo = gr.Interface(fake_diffusion,
#设置滑窗,最小值为1,最大值为10,初始值为3,每次改动增减1位
inputs=gr.Slider(1, 10, value=3, step=1),
outputs="image")
#生成器必须要queue函数
demo.queue()
demo.launch()
在多个web页面中共享状态。
data ={"name": "John", "age": 25}, {"name": "Jane", "age": 30};
import gradio as gr
def session_state_demo(input_text, history):
# Your processing logic here
history.append("Processed: " + input_text)
return history
iface_session = gr.Interface(
fn=session_state_demo, inputs=["text", gr.Session("text")], outputs="text"
)
在 inputs 中带入 gr.Session