本指南介绍了如何让 Gradio 界面自动刷新或连续流式传输数据。
This guide covers how to get Gradio interfaces to refresh automatically or continuously stream data.
你可以通过在界面中设置 live=True 来使界面自动刷新。 现在,只要用户输入发生变化,界面就会重新计算。
You can make interfaces automatically refresh by setting live=True in the interface. Now the interface will recalculate as soon as the user input changes.
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
live=True,
)
demo.launch()
请注意,没有提交按钮,因为界面会在更改时自动重新提交。
Note there is no submit button, because the interface resubmits automatically on change.
某些组件具有“流”模式,例如麦克风模式下的 Audio 组件或网络摄像头模式下的 Image 组件。 Streaming 意味着数据不断地发送到后端, Interface 函数不断地重新运行。
Some components have a "streaming" mode, such as Audio component in microphone mode, or the Image component in webcam mode. Streaming means data is sent continuously to the backend and the Interface function is continuously being rerun.
gr.Audio(source='microphone') 和 gr.Audio(source='microphone', streaming=True) 之间的区别,当两者都在 gr.Interface(live=True) 中使用时,第一个 Component 将自动当用户停止录制时提交数据并运行 Interface 功能,而第二个 Component 将在录制期间不断发送数据并运行 Interface 功能。
The difference between gr.Audio(source='microphone') and gr.Audio(source='microphone', streaming=True), when both are used in gr.Interface(live=True), is that the first Component will automatically submit data and run the Interface function when the user stops recording, whereas the second Component will continuously send data and run the Interface function during recording.
这是从网络摄像头流式传输图像的示例代码。
Here is example code of streaming images from the webcam.
import gradio as gr
import numpy as np
def flip(im):
return np.flipud(im)
demo = gr.Interface(
flip,
gr.Image(source="webcam", streaming=True),
"image",
live=True
)
demo.launch()