鉴黄windows10本地运行ok版本

https://blog.csdn.net/kingroc/article/details/89519293?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162789463716780264081371%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162789463716780264081371&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-3-89519293.first_rank_v2_pc_rank_v29&utm_term=%E9%89%B4%E9%BB%84&spm=1018.2226.3001.4187

serving更改代码
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((‘127.0.0.1’, 5000))

tornado更改代码
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((‘127.0.0.1’, 5000))

import tensorflow as tf
import os
import numpy as np
import socket

def init_socket():
    # server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if os.path.exists("/tmp/tfserver.sock"):
        os.unlink("/tmp/tfserver.sock")
    # server.bind("/tmp/tfserver.sock")
    server.bind(('127.0.0.1', 5000))
    server.listen(0)
    return server

def id_to_string(node_id):
    if node_id not in uid_to_human:
        return ''
    return uid_to_human[node_id]

lines = tf.gfile.GFile('./inception_model/output_labels.txt').readlines()
uid_to_human = {}
TFServer = init_socket()

for uid, line in enumerate(lines):
    line = line.strip('\n')
    uid_to_human[uid] = line

with tf.gfile.FastGFile('./inception_model/output_graph.pb', 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    tf.import_graph_def(graph_def, name='')

with tf.Session() as sess:
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
    while True:
        #这里等待接收用户的图片信息。
        connection, address = TFServer.accept()
        rec = connection.recv(1024)
        picPath = str(rec, encoding="utf-8")
        print (picPath)
        image_data = tf.gfile.GFile(picPath, 'rb').read()
        predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        predictions = np.squeeze(predictions)

        top_k = predictions.argsort()[::-1]
        result = ''
        for node_id in top_k:
            human_string = id_to_string(node_id)
            score = predictions[node_id]
            buf = ('%s (score = %.2f%%) \n' % (human_string, score*100))
            result = result + buf
        print(result)
        #将打分结果返回给提交打分申请的客户端
        connection.send(bytes(result, 'utf-8'))
    connection.close()


import tornado.ioloop
import tornado.web
import os
import time
import operator
import socket
import glob

staticFilePath = 'static'

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Main")

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Index")

class UploadFileHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('UploadFile.html')

    def getFileName(self):
        now = time.time()
        millisecond = int((now - int(now)) * 1000)
        t = time.localtime(now)
        time_str = "%d-%d-%d-%d-%d-%d-%d" % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, millisecond)
        return time_str

    def post(self):
        # 文件的暂存路径
        upload_path = os.path.join(os.path.dirname(__file__) + '/static', str(self.request.remote_ip))
        if(os.path.exists(upload_path) == False):
            os.makedirs(upload_path)

        file_metas = self.request.files['file']    #提取表单中‘name’为‘file’的文件元数据
        fileData = file_metas[0]
        fileName = fileData['filename']
        arr = os.path.splitext(fileName)
        extFileName = arr[len(arr) - 1]

        fileType = fileData['content_type']
        print(fileName)
        print(fileType)
        #这里判断图片是否为jpeg格式的文件,将其他格式的图片进行了过滤。
        if (operator.eq(fileType, 'image/jpeg') == False):
            self.write('请上传JPEG格式的图片!')
            return
        else:
            fileNameTime = self.getFileName()
            fileName = fileNameTime + extFileName
            fileFullName = os.path.join(upload_path, fileName)
            #将用户上传的图片进行本地化存储。
            with open(fileFullName, 'wb') as up:
                 up.write(fileData['body'])
            #self.write('finished!')

            #通过socket管道将图片路径传给Tensorflow服务器
            # client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            # client.connect("/tmp/tfserver.sock")
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect(('127.0.0.1', 5000))
            client.send(bytes(fileFullName, 'utf-8'))

            #接收Tensorflow服务的打分数据
            resultbyte = client.recv(1024)
            resultStr = str(resultbyte, encoding="utf-8")

            n = fileFullName.find(staticFilePath)
            imagePath = fileFullName[n:]

            #将图片源文件和打分数据同时进行显示。
            htmlSource = '<!DOCTYPE html> ' \
                       + '<head> <meta charset="UTF-8"> </head> ' \
                       + '<body> ' \
                       + '<p> ' +  resultStr  + '</p>' \
                       + '<img src="' + imagePath + '"/>' \
                       + '</body>' \
                       + '</html>'
            print(htmlSource)
            self.write(htmlSource)
        return

#handlers = [(r"/", UploadFileHandler),]

setting = dict(
    #template_path = os.path.join(os.path.dirname(__file__), "temploop"),
    static_path = os.path.join(os.path.dirname(__file__), staticFilePath)
)

application = tornado.web.Application([
    (r"/main", MainHandler),
    (r"/index", IndexHandler),
    (r'/file',UploadFileHandler),
], **setting)

#application = tornado.web.Application(handlers, template_path, static_path)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值