Gradio笔记<持续更新>

本文介绍了如何使用gradio在Python中创建简单的接口,包括文本输入和动态交互的计算器示例,以及如何将深度学习模型集成到gradio中进行图像识别。gradio被用于快速原型验证和模型部署,但对于大规模工程,可能需要其他工具支持。
摘要由CSDN通过智能技术生成

第一步:安装

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是为深度学习快速部署而开发的包,如果想要自己的项目落地,可能需要其它工具。
好了,今天就写到这里

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值