Beispiel #1
0
    def handle_conn(self):
        """
        连接处理
        :return:
        """
        log.info('Socket conn eastablished with %s:%s' % (self.addr))
        # 检查美学模型是否是ok的,如果不是ok的,那么告诉客户端你凉了
        if self.aes_model == None or (not self.aes_model.initFinish()):
            self.sock.send(Config.CODE_ERROR)
            self.sock.close()
            log.info('Aes not init, return CODE_ERROR')
            return

        # 美学检测通过,返回CODE_OK,进行下一步
        self.sock.send(Config.CODE_OK.encode('utf-8'))

        # 正式接受数据
        received_path = self.recv_end()
        log.info('Received path at -> %s' % (received_path))

        # 路径校验
        suc, normed_path, msg = FileUtils.valid_path(received_path,
                                                     relative_path=False)
        if not suc:
            self.sock.send(Config.CODE_FILE_ERROR.encode('utf-8'))
            self.sock.close()
            log.info('Received path at -> %s is invalid!' % (received_path))
            return

        # 进行美学评估
        aesScore = self.aes_model.runModelForSingleImg(normed_path, True)
        self.sock.send(aesScore.encode('utf-8'))
        self.sock.close()
        log.info('Aes over, score = %s for img->%s' % (aesScore, normed_path))
Beispiel #2
0
def launch_model():
    """
    启动美学模型
    :return:
    """
    from core.PhotoAesModel import aes_model
    aes_model.initModel()
    log.info('Init aes_model over')
    return aes_model
Beispiel #3
0
def start_listen():
    """
    开启端口监听
    :return:
    """
    # 使用ipV4
    socket_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 本机服务,端口8848
    socket_conn.bind((Config.LISTEN_IP, Config.LISTEN_PORT))
    # 并发连接数目为4
    socket_conn.listen(Config.CONCURRENT_NUM)
    log.info('Start to listener at port %d' % (Config.LISTEN_PORT))
    return socket_conn
Beispiel #4
0
    def __init__(self, is_player_one=False, print_extended_frame_data=False):
        self.frame_data = {}
        self.game_events = []
        self.current_game_event = None
        self.is_player_one = is_player_one
        self.print_extended_frame_data = print_extended_frame_data

        self.active_frame_wait = 1
        self.punish_window_counter = 0

        self.was_fight_being_reacquired = True
        self.is_match_recorded = False

        self.stat_filename = "TekkenData/matches.txt"
        if self.is_player_one:
            self.load_stats()

        self.current_punish_window = None
        self.punish_windows = []
        self.current_frame_data_entry = None
        self.previous_frame_data_entry = None

        if TekkenEncyclopedia.__logger is None:
            TekkenEncyclopedia.__logger = LogUtils.initialize_module_logger(
                __name__
            )
Beispiel #5
0
    def __init__(self, movelist_bytes, movelist_pointer):
        self.bytes = movelist_bytes
        self.pointer = movelist_pointer

        if MovelistParser.__logger is None:
            MovelistParser.__logger = LogUtils.initialize_module_logger(
                __name__)

        self.parse_header()
Beispiel #6
0
def main():
    """
    美学微服务的入口
    :return:
    """
    # log注册
    log.register_logger()
    # 初始化美学模型
    aes_model = launch_model()
    # 开启端口监听
    socket_conn = start_listen()
    # TODO:这边其实用一个线程池来进行维护会比较好
    try:
        while True:
            # 接受一个新连接:
            sock, addr = socket_conn.accept()
            # 处理连接
            conn_handler = ConnHandler(aes_model, sock, addr)
            worker = ConnWorker(conn_handler)
            worker.start()

    finally:
        socket_conn.close()
Beispiel #7
0
    def initModel(self):
        """
        模型初始化
        全局只会初始化一次
        包括:
        1.inceptionV2结构化定义
        2.加载模型权重
        :param weightsFilePath:
        :return:
        """
        from keras.models import Model
        from keras.layers import Dense, Dropout
        from keras.applications.inception_resnet_v2 import InceptionResNetV2

        # 初始化过,就不要再初始化了
        if self.initFinish():
            log.info('the model has already init before, now re-use it')
            return

        # 同步Graph
        self.graph = tf.Graph()
        # session = tf.Session()

        # 模型构建
        log.info(('start to build model based on weights in -> %s' %
                  (self.weightsFile)))
        # with tf.device('/CPU:0'):

        with self.graph.as_default():
            # with session.as_default():
            # 模型参数定义
            base_model = InceptionResNetV2(input_shape=(None, None, 3),
                                           include_top=False,
                                           pooling='avg',
                                           weights=None)
            log.info('suc create v2 model')
            x = Dropout(0.75)(base_model.output)
            x = Dense(10, activation='softmax')(x)
            self.model = Model(base_model.input, x)
            # 读取权重数据
            self.model.load_weights(self.weightsFile)
            self.model._make_predict_function()

        # graph = tf.get_default_graph()
        self.hasModelInit = True
        log.info('model init complete!')
        return
Beispiel #8
0
    def runModelForSingleImg(self, imgFilePath, resize):
        """
        运行模式 - 单照片运行
        这个函数必须在模型已经初始化完毕之后才能使用
        注意,此函数线程安全,进程不安全
        :param imgFilePathLst:
        :param resize:
        :return:
        :param imgFilePath:
        :param resize:
        :return:
        """
        if not self.initFinish:
            log.error(
                'Failed to calculate aes score : model is not initialized!')
            return

        # with tf.device('/CPU:0'):
        #     with graph.as_default():
        with self.graph.as_default():

            log.info('Now processing img -> %s' % (imgFilePath))
            # 预处理
            imgArr = self._preImgProcess(imgFilePath, resize)
            try:
                self.lock.acquire()
                log.info('Now preprocessing img -> %s' % (imgFilePath))
                # 预测
                scores = self.model.predict(imgArr, batch_size=1, verbose=0)[0]
                aesScore = score.calculateAesScore(scores)
                aesScore = aesScore * 10
                log.info('The score for img -> %s is %.2f' %
                         (imgFilePath, aesScore))
            finally:
                self.lock.release()

        return str(aesScore)
Beispiel #9
0
 def initialize_class_logger(cls):
     cls.__logger = LogUtils.initialize_module_logger(__name__)
Beispiel #10
0
def main(argv=sys.argv[1:]):

    log = LogUtils("Let's Encrypt")

    config = None
    domain = None
    mailto = None
    # we will not authorize domain by default
    authz = False
    # authorization and get certificate will be skipped if already done
    force = False
    showdns = False
    challenge = False
    getcert = False
    export = True
    revoke = False
    certpath = None
    opts, argv = getoptionspw(argv, "c:d:m:A:D:C:R:rh", [
        "config=", "domain=", "mailto=", "authorization", "challenge", "dns",
        "certificate", "force", "help", "revoke"
        "revoke-cert="
    ])
    for o, v in opts:
        opt = o.lstrip("-")
        if opt in ("h", "help"):
            usage()
        elif opt in ("d", "domain"):
            domain = v
        elif opt in ("m", "mailto"):
            mailto = v
        elif opt in ("c", "config"):
            config = v
        elif (opt == "A" and v == "UTH") or opt == "authorization":
            authz = True
        elif (opt == "D" and v == "NS") or opt == "challenge":
            challenge = True
        elif (opt == "C" and v == "ERT") or opt == "certificate":
            getcert = True
        elif opt == "dns":
            showdns = True
        elif opt == "force":
            force = True
        elif opt in ("r", "R", "revoke", "revoke-cert"):
            revoke = True
            if v:
                certpath = v
        else:
            print "GetoptError exception: option -%s%s not recognized" % (opt,
                                                                          v)
            usage()

    if len(argv) >= 1 and domain is None:
        domain = argv[0]

    if not domain:
        log.warn("error: Domain name is mandatory")
        usage()

    try:
        app = LetsEncrypt(domain, config)
        app.init()
    except ValueError as strerror:
        log.warn("error: %s" % strerror)
        usage()

    appconfig = app.config.path
    if config:
        if config == appconfig:
            log.warn("use provided config: %s" % appconfig)
        else:
            log.warn(
                "provided config could not be used. Please check path (%s)" %
                congig)
            log.warn("use config: %s" % appconfig)

    # if we are not registered yet (1st run for provided domain)
    if not app.config.domain("reg"):
        # registration
        status = app.register(mailto)
        if status is None:
            log.warn("error: email address is not correct (mailto: %s)" %
                     mailto)
            usage()

    if not app.config.contact("agreement"):
        # accept EULA
        app.agreement()

    if authz and (not app.config.domain("authz") or force):
        app.authorization()

    app.checkAuthorization()

    if showdns and app.config.domain("authz"):
        print app.dnsRecord()

    if challenge and app.config.challenges("status") == "pending":
        app.challenge()

    if getcert and app.config.challenges("status") == "valid" and (
            not app.config.certificate() or force):
        app.certificate()

    if export and app.config.certificate():
        app.saveCert()

    if revoke:
        crt = None
        if certpath and os.path.isfile(certpath):
            crt = open(certpath, "r").read()
        app.revoke(crt)
Beispiel #11
0
    def __init__(self, data_dict):
        """
        """
        if not BotSnapshot.__logger:
            BotSnapshot.__logger = LogUtils.initialize_module_logger(__name__)

        # self.xyz = (
        #    data_dict['PlayerDataAddress.x'], data_dict['PlayerDataAddress.y'],
        #    data_dict['PlayerDataAddress.z']
        # )
        self.move_id = data_dict['PlayerDataAddress.move_id']
        self.simple_state = SimpleMoveStates(
            data_dict['PlayerDataAddress.simple_move_state'])
        self.attack_type = AttackType(
            data_dict['PlayerDataAddress.attack_type']
        )
        self.startup = data_dict['PlayerDataAddress.attack_startup']
        self.startup_end = data_dict['PlayerDataAddress.attack_startup_end']
        self.attack_damage = data_dict['PlayerDataAddress.attack_damage']
        self.complex_state = ComplexMoveStates(
            data_dict['PlayerDataAddress.complex_move_state'])
        self.damage_taken = data_dict['PlayerDataAddress.damage_taken']
        self.move_timer = data_dict['PlayerDataAddress.move_timer']
        self.recovery = data_dict['PlayerDataAddress.recovery']
        self.char_id = data_dict['PlayerDataAddress.char_id']
        self.throw_flag = data_dict['PlayerDataAddress.throw_flag']
        self.rage_flag = data_dict['PlayerDataAddress.rage_flag']
        self.input_counter = data_dict['PlayerDataAddress.input_counter']
        self.input_direction = InputDirection(
            data_dict['PlayerDataAddress.input_direction']
        )
        try:
            self.input_button = InputAttack(
                data_dict['PlayerDataAddress.input_attack']
                # % InputAttackCodes.xRAGE.value
            )
        except ValueError:
            self.__logger.debug(
                'unknown input attack: %d',
                data_dict['PlayerDataAddress.input_attack']
            )
            self.input_button = InputAttack.NULL
        self.rage_button_flag = (
            data_dict['PlayerDataAddress.input_attack']
            >= InputAttack.B_RAGE.value
        )
        self.stun_state = StunStates(data_dict['PlayerDataAddress.stun_type'])
        self.is_power_crush = data_dict['PlayerDataAddress.power_crush'] > 0

        cancel_window_bitmask = data_dict['PlayerDataAddress.cancel_window']
        recovery_window_bitmask = data_dict['PlayerDataAddress.recovery']

        self.is_cancelable = (
            (CancelStatesBitmask.CANCELABLE.value & cancel_window_bitmask)
            == CancelStatesBitmask.CANCELABLE.value
        )
        self.is_bufferable = (
            (CancelStatesBitmask.BUFFERABLE.value & cancel_window_bitmask)
            == CancelStatesBitmask.BUFFERABLE.value
        )
        self.is_parry1 = (
            (CancelStatesBitmask.PARRYABLE_1.value & cancel_window_bitmask)
            == CancelStatesBitmask.PARRYABLE_1.value
        )
        self.is_parry2 = (
            (CancelStatesBitmask.PARRYABLE_2.value & cancel_window_bitmask)
            == CancelStatesBitmask.PARRYABLE_2.value
        )
        self.is_recovering = (
            (ComplexMoveStates.RECOVERING.value & recovery_window_bitmask)
            == ComplexMoveStates.RECOVERING.value
        )
        self.is_starting = self.startup > 0 and self.move_timer <= self.startup
        self.throw_tech = ThrowTechs(data_dict['PlayerDataAddress.throw_tech'])

        #self.highest_y = max(data_dict['PlayerDataAddress.y'])
        # self.lowest_y = min(data_dict['PlayerDataAddress.y'])

        # self.hitboxes = [
        #     data_dict['PlayerDataAddress.hitbox1'],
        #     data_dict['PlayerDataAddress.hitbox2'],
        #     data_dict['PlayerDataAddress.hitbox3'],
        #     data_dict['PlayerDataAddress.hitbox4'],
        #     data_dict['PlayerDataAddress.hitbox5']
        # ]
        self.skeleton = (
            data_dict['PlayerDataAddress.x'], data_dict['PlayerDataAddress.y'],
            data_dict['PlayerDataAddress.z']
        )

        self.active_xyz = (
            data_dict['PlayerDataAddress.activebox_x'],
            data_dict['PlayerDataAddress.activebox_y'],
            data_dict['PlayerDataAddress.activebox_z']
        )

        self.is_jump = (
            data_dict['PlayerDataAddress.jump_flags']
            & JumpFlagBitmask.JUMP.value == JumpFlagBitmask.JUMP.value
        )
        self.hit_outcome = HitOutcome(
            data_dict['PlayerDataAddress.hit_outcome']
        )
        self.mystery_state = data_dict['PlayerDataAddress.mystery_state']

        #self.movelist_to_use = data_dict['PlayerDataAddress.movelist_to_use']

        self.current_side = BattleSide(
            data_dict['PlayerDataAddress.current_side']
        )

        self.wins = data_dict['EndBlockPlayerDataAddress.round_wins']
        self.combo_counter = (
            data_dict['EndBlockPlayerDataAddress.display_combo_counter']
        )
        self.combo_damage = (
            data_dict['EndBlockPlayerDataAddress.display_combo_damage']
        )
        self.juggle_damage = (
            data_dict['EndBlockPlayerDataAddress.display_juggle_damage']
        )

        self.use_opponents_movelist = data_dict['use_opponent_movelist']
        self.movelist_parser = data_dict['movelist_parser']

        try:
            self.character_name = CharacterIDs(
                data_dict['PlayerDataAddress.char_id']
            ).name
        except KeyError:
            self.character_name = "UNKNOWN"