为了调用deepdanbooru而搭建的服务器

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,time,json
from bottle import *
from typing import Any, Iterable, List, Tuple, Union
import six
import tensorflow as tf
import deepdanbooru as dd

HTML = """
<!DOCTYPE html>
<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>DeepDanbooru</title>
<style type="text/css">
body{
font-size:14px;
align-text:center;
}
input{ 
vertical-align:middle;
margin:0;
padding:0
}
.file-box{
position:relative;
width:340px;
margin:0px;
}
.txt{
height:22px;
border:1px solid #cdcdcd;
width:180px;
}
.btn{
background-color:#FFF;
border:1px solid #CDCDCD;
height:24px;
width:70px;
}
.file{
position:absolute;
top:0;
right:80px;
height:24px;
filter:alpha(opacity:0);
opacity: 0;
width:260px
}
</style> 
</head> 
<body> 
<h1>Deep Danbooru</h1>
<h3>Upload image</h3> 
<div class="file-box"> 
<form action="/upload" method="post" enctype="multipart/form-data"> 
<input type="text" name="textfield" id="textfield" class="txt" /> 
<input type="button" class="btn" value="浏览..." /> 
<input type="file" name="fileField" class="file" id="fileField" size="28" onchange="document.getElementById('textfield').value=this.value" /> 
<input type="submit" name="submit" class="btn" value="上传" onclick="" /> 
</form> 
</div> 
</body>
</html>
"""
 
model_path = "/root/model/model-resnet_custom_v4.h5"
tags_path = "/root/model/tags.txt"
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
model = tf.keras.models.load_model(model_path, compile=True)
tags = dd.data.load_tags(tags_path)
def evaluate_image(
    image_input: Union[str, six.BytesIO], model: Any, tags: List[str], threshold: float
) -> Iterable[Tuple[str, float]]:
    width = model.input_shape[2]
    height = model.input_shape[1]

    image = dd.data.load_image_for_evaluate(
        image_input, width=width, height=height)

    image_shape = image.shape
    image = image.reshape(
        (1, image_shape[0], image_shape[1], image_shape[2]))
    y = model.predict(image)[0]

    result_dict = {}

    for i, tag in enumerate(tags):
        result_dict[tag] = y[i]

    for tag in tags:
        if result_dict[tag] >= threshold:
            yield tag, result_dict[tag]


def evaluate(file_path):
    resp = []
    for tag, score in evaluate_image(file_path, model, tags, 0.5):
        resp.append({"tag":tag,"socre":str(score)})
    os.remove(file_path)
    return json.dumps(resp)


base_path = os.path.dirname(os.path.realpath(__file__))  # 获取脚本路径
 
upload_path = os.path.join(base_path, 'upload')   # 上传文件目录
if not os.path.exists(upload_path):
    os.makedirs(upload_path)
    

@route('/', method='GET')
@route('/upload', method='GET')
@route('/index.html', method='GET')
@route('/upload.html', method='GET')
def index():
    """显示上传页"""
    return HTML
 
 
@route('/upload', method='POST')
def do_upload():
    """处理上传文件"""
    filedata = request.files.get('fileField')
     
    if filedata.file:
        file_name = os.path.join(upload_path, str(hash(time.time()))+os.path.splitext(filedata.filename)[1])
        try:
            filedata.save(file_name)  # 上传文件写入
        except IOError:
            return '上传文件失败'
        return evaluate(file_name)
    else:
        return '上传文件失败'
 
@route('/favicon.ico', method='GET')
def server_static():
    """处理网站图标文件, 找个图标文件放在脚本目录里"""
    return static_file('favicon.ico', root=base_path)
 
 
@error(404)
def error404(error):
    """处理错误信息"""
    return '404 Not Found'
@error(500)
def error500(error):
    return '500 Internal Error'

run(host='0.0.0.0', port=80, reloader=True) #这里注意host不能填"127.0.0.1"否则对外无法访问

Tags:

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

近期评论
归档
分类