当前位置:   article > 正文

西北乱跑娃 --- bottle框架部署pytorch模型_bottle深度学习部署

bottle深度学习部署

一、前言

在网站荡了很多关于深度学习的代码,包括在码云、github和各种博客。但是作者毕竟是一个文科生,也没有怎么接触过深度学习分类的代码,加上那些文章中的代码文件太多,极其晦涩难懂所以在之前的半年里一部分是做自己本分的网站全栈开发,另外就是一直想去学习人工智能,但是由于没有很简单直白的学习资料,所以一直游离于人工智能的门外。这两天索性不再给自己的能力找借口,也不为自己的时间短缺找借口,于是自己摸索了两三天,加上自己在图像处理和网站搭建的经验写下了此篇文章。

二、部署代码

# encoding: utf-8
import io
import os
from bottle import run, route, jinja2_template, TEMPLATE_PATH, request, json_dumps, static_file
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms as T
from torchvision.models import resnet50


model = None
use_gpu = False

with open(r'C:\Users\Administrator\Desktop\project\imagenet_class.txt', 'r', encoding='utf8') as f:
    idx2label = eval(f.read())


def load_model():
    """Load the pre-trained model, you can use your model just as easily.

    """
    global model
    # 加载在线模型resnet50
    model = resnet50(pretrained=True)
    model.eval()
    # 判断是否有GPU加速
    # if use_gpu:
    #     model.cuda()


def prepare_image(image, target_size):
    """在对任何数据进行预测之前,都要进行图像预处理。

    :param image:       original image
    :param target_size: target image size
    :return:
                        preprocessed image
    """
    if image.mode != 'RGB':
        image = image.convert("RGB")

    # 调整输入图像的大小并对其进行预处理。
    image = T.Resize(target_size)(image)
    image = T.ToTensor()(image)
    # 转换为Torch.Tensor并进行归一化.
    image = T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(image)
    # 添加batch_size轴.
    image = image[None]
    # 使用torch.no_grad()上下文管理器中执行梯度来更新权重和偏差
    with torch.no_grad():
        return image

# 此处为网站设置可以跳过
@route('<filename:re:.*\.css|.*\.js|.*\.png|.*\.jpg|.*\.jpeg|.*\.gif|.*\.otf|.*\.eot|.*\.woff|.*\.mp3|.*\.map|.*\.mp4>')
def server_static(filename):
    """定义static下所有的静态资源路径"""
    return static_file(filename, root='static')


@route('/prot', method=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        # bottle web框架获取客户端上传的图片文件
        image = request.POST.get('file').file.read()
        # PLI图片读取二进制流为数组
        image = Image.open(io.BytesIO(image))
        # 预处理图像并准备进行分类.
        image = prepare_image(image, target_size=(224, 224))
        # 对输入图像进行分类,然后初始化预测列表以返回到客户端。
        preds = F.softmax(model(image), dim=1)
        results = torch.topk(preds.cpu().data, k=3, dim=1)
        data = []

        # 循环搜索结果并将其添加到返回的预测列表中
        for prob, label in zip(results[0][0], results[1][0]):
            # 根据给定好的txt文件,依据键获取预测值 .item将tensor(2)类型转化为数值2
            label_name = idx2label[label.item()]
            # 打印出预测文本
            # print(label_name)
            r = {
   "pret": label_name, "like": float(prob)}
            data.append(r)
        return json_dumps(data)
    else:
        return jinja2_template('img.html')


# 调用加载模型函数
load_model()
# 固定网站配置,定义html文件的位置
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_PATH.append('/'.join((BASE_DIR, 'templates')))
# 启动网站
run(host='127.0.0.1', port='8000', server='tornado')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95

img.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img width="200" height="150" src="" alt="">
    <div>
        <input type="file" id="image">
        <button id="pull">提交</button>
    </div>
    <div class="card-body  card-content" style="height: 500px; overflow: auto">
                    <table class="table table-responsive table-hover ">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>预测事物</th>
                                <th>相似度</th>
                            </tr>
                        </thead>
                        <tbody id="tcontent">

                        </tbody>
                    </table>
                </div>

    <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script type="application/javascript">
            var btn = $('#pull');
            btn.click(function () {
   
                let dic = new FormData();
                var file = $('#image')[0].files[0];
                dic.append("file",file);
                var url = window.URL.createObjectURL(file);
                $('img').attr('src', url);
                $.ajax({
   
                    async: false,
                    type: 'post',
                    url: "/prot",
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    processData: false,
                    data:dic,
                    success: function (res) {
   
                        var str = '';
                        result = JSON.parse(res);
                        for (i=0;i<result.length;i++){
   
                            str += '<tr><td>' + i + '</td><td>'+ result[i].pret +'</td><td>'+ result[i].like +'</td></tr>';
                        }
                        $('#tcontent').html(str)
                    },
                    error: function (error) {
   
                        console.log(error);
                    }
                });
            })
    </script>
</body>
</html>


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

三、映射字典

此处是文章中的txt文件,可以直接创建文件

{
   0: 'tench, Tinca tinca',
 1: 'goldfish, Carassius auratus',
 2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
 3: 'tiger shark, Galeocerdo cuvieri',
 4: 'hammerhead, hammerhead shark',
 5: 'electric ray, crampfish, numbfish, torpedo',
 6: 'stingray',
 7: 'cock',
 8: 'hen',
 9: 'ostrich, Struthio camelus',
 10: 'brambling, Fringilla montifringilla',
 11: 'goldfinch, Carduelis carduelis',
 12: 'house finch, linnet, Carpodacus mexicanus',
 13: 'junco, snowbird',
 14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
 15: 'robin, American robin, Turdus migratorius',
 16: 'bulbul',
 17: 'jay',
 18: 'magpie',
 19: 'chickadee',
 20: 'water ouzel, dipper',
 21: 'kite',
 22: 'bald eagle, American eagle, Haliaeetus leucocephalus',
 23: 'vulture',
 24: 'great grey owl, great gray owl, Strix nebulosa',
 25: 'European fire salamander, Salamandra salamandra',
 26: 'common newt, Triturus vulgaris',
 27: 'eft',
 28: 'spotted salamander, Ambystoma maculatum',
 29: 'axolotl, mud puppy, Ambystoma mexicanum',
 30: 'bullfrog, Rana catesbeiana',
 31: 'tree frog, tree-frog',
 32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
 33: 'loggerhead, loggerhead turtle, Caretta caretta',
 34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',
 35: 'mud turtle',
 36: 'terrapin',
 37: 'box turtle, box tortoise',
 38: 'banded gecko',
 39: 'common iguana, iguana, Iguana iguana',
 40: 'American chameleon, anole, Anolis carolinensis',
 41: 'whiptail, whiptail lizard',
 42: 'agama',
 43: 'frilled lizard, Chlamydosaurus kingi',
 44: 'alligator lizard',
 45: 'Gila monster, Heloderma suspectum',
 46: 'green lizard, Lacerta viridis',
 47: 'African chameleon, Chamaeleo chamaeleon',
 48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',
 49: 'African crocodile, Nile crocodile, Crocodylus niloticus',
 50: 'American alligator, Alligator mississipiensis',
 51: 'triceratops',
 52: 'thunder snake, worm snake, Carphophis amoenus',
 53: 'ringneck snake, ring-necked snake, ring snake',
 54: 'hognose snake, puff adder, sand viper',
 55: 'green snake, grass snake',
 56: 'king snake, kingsnake',
 57: 'garter snake, grass snake',
 58: 'water snake',
 59: 'vine snake',
 60: 'night snake, Hypsiglena torquata',
 61: 'boa constrictor, Constrictor constrictor',
 62: 'rock python, rock snake, Python sebae',
 63: 'Indian cobra, Naja naja',
 64: 'green mamba',
 65: 'sea snake',
 66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
 67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',
 68: 'sidewinder, horned rattlesnake, Crotalus cerastes',
 69: 'trilobite',
 70: 'harvestman, daddy longlegs, Phalangium opilio',
 71: 'scorpion',
 72: 'black and gold garden spider, Argiope aurantia',
 73: 'barn spider, Araneus cavaticus',
 74: 'garden spider, Aranea diademata',
 75: 'black widow, Latrodectus mactans',
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/375171
推荐阅读
相关标签
  

闽ICP备14008679号