pip install gradio
pythonimport gradio
def greet(name):
return "Hello " + name + "!"
demo = gradio.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()
gradio app.py
应用界面:
gradio.Interface
(简易场景)gradio.Blocks
(定制化场景)控制组件:
gradio.Button
(按钮)布局组件:
gradio.Tab
(标签页)gradio.Row
(行布局)gradio.Column
(列布局)gradio.Image
(图像)gradio.Textbox
(文本框)gradio.DataFrame
(数据框)gradio.Dropdown
(下拉选项)gradio.Number
(数字)gradio.Markdown
(Markdown)gradio.Files
(文件)gradio.Slider(0, 10)
(滑动选择器)gradio.Checkbox
(勾选框)gradio.Radio(['1', '2'])
(单选)inputs=gradio.Textbox(lines=3, placeholder="Name Here...",label="my input")
gradio.Interface(live=True)
当 live=True 时,只要输入发生变化,结果马上发生改变
app, local_url, share_url = gradio.Interface.launch()
gradio.launch( server_name="0.0.0.0", server_port=8080, share=True, # 创建外部访问链接 )
pythonimport gradio
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 = gradio.Interface(
fn=greet,
inputs=["text", "checkbox", gradio.Slider(0, 100)],
outputs=["text", "number"],
)
demo.launch()
pythonimport numpy
import gradio
def sepia(input_img):
sepia_filter = numpy.array([
[0.393, 0.769, 0.189],
[0.349, 0.686, 0.168],
[0.272, 0.534, 0.131]
])
sepia_img = input_img.dot(sepia_filter.T)
sepia_img /= sepia_img.max()
return sepia_img
demo = gradio.Interface(sepia, "image", "image")
demo.launch()
当使用 Image 组件作为输入时,函数将收到一个维度为(w,h,3)的 numpy 数组,按照 RGB 的通道顺序排列
数据在一个页面会话中的多次提交中持久存在
pythonimport random
import gradio
def chat(message, history):
history = history or []
message = message.lower()
if message.startswith("how many"):
response = random.randint(1, 10)
elif message.startswith("how"):
response = random.choice(["Great", "Good", "Okay", "Bad"])
elif message.startswith("where"):
response = random.choice(["Here", "There", "Somewhere"])
else:
response = "I don't know"
history.append((message, str(response)))
return history, history
#设置一个对话窗
chatbot = gradio.Chatbot()
demo = gradio.Interface(
chat,
# 添加state组件
["text", "state"],
[chatbot, "state"],
)
demo.launch()
pythonimport gradio
import numpy
def flip(im):
return numpy.flipud(im)
demo = gradio.Interface(
flip,
gradio.Image(source="webcam", streaming=True),
"image",
live=True
)
demo.launch()