第一步:安装
pip install gradio
第二步:一个简单的案例
import gradio as gr
def greet(name):
return "Hello " + name + "!!"
iface = gr.Interface(fn=greet, inputs="text", outputs="text")
iface.launch()
如果输出端一直出现error
将pydantic的版本降到1.10.7
gradio==3.34.0
第三步:再玩一个动态交互的案例
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
iface = gr.Interface(
calculator,
["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
live=True,
)
iface.launch()
今日更新:自己训练了一个模型,然后测试用gradio写一个界面,感觉这个搭界面是真的快,封装的很高级,适用于快速原型验证,工程部署的的还是需要其它框架的
import torchvision
import torch
import torch.nn.functional as F
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 32, (5, 5), padding=(2, 2), bias=True)
self.conv2 = torch.nn.Conv2d(32, 64, (5, 5), padding=(2, 2), bias=True)
self.conv3 = torch.nn.Conv2d(64, 128, (5, 5), padding=(2, 2), bias=True)
self.fc1 = torch.nn.Linear(128 * 3 * 3, 128, bias=True)
self.fc2 = torch.nn.Linear(128, 10, bias=True)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))
x = x.reshape(-1, 128 * 3 * 3)
x = F.relu(self.fc1(x))
y = self.fc2(x)
z = F.softmax(y, dim=1)
z = torch.argmax(z, dim=1)
# return y, z
return y
model = Net()
model.load_state_dict(torch.load('save.pt'))
model.eval()
from PIL import Image
def img_infer(image):
image = image[:, :, 0]
image = Image.fromarray(image)
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((28, 28)),
torchvision.transforms.ToTensor()])
image = transform(image)
image1 = image.unsqueeze(0)
image = image.float() # Convert to float
with torch.no_grad():
output = model(image1)
prediction = torch.argmax(output, dim=1).item()
return str(prediction)
import gradio as gr
iface = gr.Interface(
fn=img_infer,
inputs="image",
outputs="text",
live=True,
capture_session=True
)
iface.launch()
#iface.launch(share=True) #可以分享
续更
gradio是为深度学习快速部署而开发的包,如果想要自己的项目落地,可能需要其它工具。
好了,今天就写到这里