def runModel(imgFilePathLst, resize): """ 运行模式 - 多照片运行 这个函数必须在模型已经初始化完毕之后才能使用 :param imgFilePathLst: :param resize: :return: """ global model, hasModelInit if model == None or (not hasModelInit): log.error('Failed to calculate aes score : model is not initialized!') return with tf.device('/CPU:0'): scoreLst = [] for imgPath in imgFilePathLst: log.info('Now processing img -> %s' % (imgPath)) # 预处理 imgArr = _preImgProcess(imgPath, resize) # 预测 scores = model.predict(imgArr, batch_size=1, verbose=0)[0] aesScore = score.calculateAesScore(scores) aesScore = aesScore * 10 # log.success('The aes score for img -> %s is %0.3f' % (imgPath, aesScore)) _, imgName = os.path.split(imgPath) scoreLst.append((imgName, aesScore)) # 进行排序 sortedScoreLst = sorted(scoreLst, key=lambda s: s[1], reverse=True) return sortedScoreLst
def runModelForSingleImg(imgFilePath, resize): """ 运行模式 - 单照片运行 这个函数必须在模型已经初始化完毕之后才能使用 :param imgFilePathLst: :param resize: :return: :param imgFilePath: :param resize: :return: """ global model, hasModelInit, graph if model == None or (not hasModelInit): log.error('Failed to calculate aes score : model is not initialized!') return with tf.device('/CPU:0'): with graph.as_default(): log.info('Now processing img -> %s' % (imgFilePath)) # 预处理 imgArr = _preImgProcess(imgFilePath, resize) # 预测 scores = model.predict(imgArr, batch_size=1, verbose=0)[0] aesScore = score.calculateAesScore(scores) aesScore = aesScore * 10 return aesScore
def addAesInfo(user_id, file_name, aes_score, db): """ 向DB增加一条美学数据 这里的检查交给调用者去做 :param user_id: :param file_name: :param db: :return: """ user_aes_info = AesUserInfo(user_id, file_name, aes_score) db.session.add(user_aes_info) db.session.commit() log.info('Add aes info into db for img -> %s' % file_name)
def make_request(abs_img_path): """ 使用Socket进行图片美学打分 真正的模型预测在美学微服务中 :param abs_img_path: :return: """ # 进行文件检查 suc, normed_path, msg = FileUtils.valid_path(abs_img_path, relative_path=False) if not suc: log.error('Invalid File path : %s' % abs_img_path) return 'Invalid File' abs_img_path = normed_path try: # 使用ipV4 socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接 socket_conn.connect((LISTEN_IP, LISTEN_PORT)) rtn_code = (socket_conn.recv(2048)).decode('utf-8') if rtn_code == CODE_ERROR: log.error('Aes model not init') return 'Model Init Error' elif rtn_code == CODE_OK: log.info('Socket established!') # 添加END_MAKRER给微服务进行内容识别 test_img_path = abs_img_path test_img_path += END_MARKER log.info('Send info -> %s' % test_img_path) # 发送请求 socket_conn.send(test_img_path) aes_score = (socket_conn.recv(2048)).decode('utf-8') log.info('The aes score is %s' % aes_score) socket_conn.close() return aes_score else: socket_conn.close() return 'Unknow Error' finally: if socket_conn: socket_conn.close()
def queryAesInfoById(user_id): """ 通过user_id 查询对应用户已经进行过美学评测的所有照片 :param user_id: :param db: :return: """ aes_score_container = {} aes_info_lst = AesUserInfo.query.filter_by(userId=user_id) if aes_info_lst is None: return aes_score_container for aesInfo in aes_info_lst: aes_score_container[aesInfo.photoName] = aesInfo.photoScore log.info('The aes score for img=%s is %s' % (aesInfo.photoName, aesInfo.photoScore)) return aes_score_container
def initModel(weightsFilePath): """ 模型初始化 全局只会初始化一次 包括: 1.inceptionV2结构化定义 2.加载模型权重 :param weightsFilePath: :return: """ # 初始化过,就不要再初始化了 global model, hasModelInit, graph if model != None and hasModelInit: log.info('the model has already init before, now re-use it') return # 模型构建 log.info( ('start to build model based on weights in -> %s' % (weightsFilePath))) with tf.device('/CPU:0'): # 模型参数定义 base_model = InceptionResNetV2(input_shape=(None, None, 3), include_top=False, pooling='avg', weights=None) x = Dropout(0.75)(base_model.output) x = Dense(10, activation='softmax')(x) model = Model(base_model.input, x) # 读取权重数据 model.load_weights(weightsFilePath) graph = tf.get_default_graph() hasModelInit = True log.info('model init complete!') return
from core.helper import FileUtils from core.helper import LogUtils as log from core.photoaes import PhotoAesModel as AesModel # flask 后台相关 app = Flask(__name__) app.config['SECRET_KEY'] = 'gaokuaidian' app.config['UPLOAD_FOLDER'] = 'data/' app.config['LOG_FOLDER'] = 'logs/' app.config['THUMBNAIL_FOLDER_NAME'] = 'thumbnail' app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/aesinfo.db' app.config['AES_MODEL_PATH'] = 'weights/weights.h5' db = SQLAlchemy(app) bootstrap = Bootstrap(app) log.register_logger(app) app.logger.name = "PhotoAes" # 数据库初始化 db.create_all() # 照片美学相关环境启动 AesModel.initModel(app.config['AES_MODEL_PATH']) """ db对象,这里因为只是用来存储一下文件名,用户id和照片美学得分的 所以简单做,只是一个简单存储而已 """ class AesUserInfo(db.Model):