示例#1
0
def handle_message(event):
    cmd_txt = event.message.text
    rtn_txt = ""

    if cmd_txt in ["salmon", "sal", "サーモンラン", "サーモン", "バイト"]:
        rtn_txt = salmon.main()
    elif cmd_txt in ["re", "regular", "レギ", "レギュ", "レギュラー", "レギュラーマッチ", "ナワバリ", "ナワバリマッチ"]:
        rtn_txt = match.main("regular")
    elif cmd_txt in ["ga", "gachi", "ガチ", "ガチマ", "ガチマッチ"]:
        rtn_txt = match.main("gachi")
    elif cmd_txt in ["le", "league", "リグ", "リグマ", "リーグ", "リーグマッチ"]:
        rtn_txt = match.main("league")
    elif cmd_txt in ["ウンチーコング", "うんちーこんぐ"]:
        line_bot_api.reply_message(
            event.reply_token,
            ImageSendMessage(
                original_content_url='https://i.ytimg.com/vi/qlMzrNl6peo/hqdefault.jpg',
                preview_image_url='https://i.ytimg.com/vi/qlMzrNl6peo/hqdefault.jpg'
            )
        )
    if rtn_txt != "":
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=rtn_txt)
        )
示例#2
0
def main(WIN):
    g = gameState()
    # match.main(g, WIN)
    while True:
        games = ["quiz", "reaction", "match"]
        random.shuffle(games)
        for game in games:
            if game == "quiz":
                quiz(WIN, g)
            elif game == "reaction":
                reaction.main(g, WIN, g.map)
            elif game == "match":
                match.main(g, WIN)  
示例#3
0
def main(a, b, c, susp, d, e):
    window = int(a)
    overlap = int(b)
    mdist = int(c)
    start = int(d)
    finish = int(e)
    filelist = sorted(os.listdir(srcfilepath))
    start = int(round(float(len(filelist)) / 100 * int(d)))
    finish = int(round(float(len(filelist)) / 100 * int(e)))
    indexfilepath = localpath + 'index_' + str(window) + '_' + str(
        overlap) + '_' + str(start + 1) + '_' + str(finish) + '.txt'
    susp_index = index.fileIndex(susp, window, overlap)
    if os.path.isfile(indexfilepath):
        source_index = writer.fRead(indexfilepath)
        indexflag = False
    else:
        source_index = index.sourceIndex(srcfilepath, window, overlap, start,
                                         finish)
        indexflag = True
        #pool.apply_async(writer.fWrite, (indexfilepath, source_index,))
        writer.fWrite(indexfilepath, source_index)
    result = {
        'index_keys': len(source_index),
        'susp_keys': len(susp_index),
        'window': window,
        'overlap': overlap,
        'merge_distance': mdist,
        'index_from': filelist[start],
        'index_upto': filelist[finish - 1],
        'new_index': indexflag
    }
    result['top_matches'] = match.main(susp_index, source_index, mdist)
    return result
示例#4
0
 def get_dir_response(self, input_sentence):
     t0 = time.time()
     user_info = srcFiles._get_user_info("10", "user")
     print("user_id=10 info:\n", user_info)
     chatbot_info = srcFiles._get_chatbot_info(
         "7b7924503aaf48b5b45bb1a30c69f14c", "pet")
     print("chatbot info:\n", chatbot_info)
     try:
         host_info = srcFiles._get_user_info(chatbot_info["user_id"],
                                             "user")
     except:
         host_info = {}
     print("user_id={} info:{}\n".format(chatbot_info["user_id"],
                                         host_info))
     # object_info = {"host": host_info, "user": user_info, "chatbot": chatbot_info}
     # qa_info = {"host": qa_host_info, "user": self_label, "chatbot": qa_chat_info}
     from_ques = u""
     try:
         match = Match(input_sentence, logger)
         answer, answer_type, answer_ind, _, _ = main(
             match, proc_trie, proc_ratio, idf_trie, answer_indexs,
             srcFiles.template_file)
         status = 0
         if answer_ind:
             try:
                 from_ques = src_trie[answer_ind]
             except:
                 pass
         del match
     except:
         print(traceback.format_exc())
         answer = "error ocurr in match"
         status = 1
     t1 = time.time()
     t_delta = t1 - t0
     response = jsonify({
         "response": answer,
         "match_type": answer_type,
         "match_ques": from_ques,
         "status": status,
         "time_response": t_delta
     })
     return response
示例#5
0
    def get_simple_response(self):
        params = request.get_json()
        t0 = time.time()
        answer_type = ""
        base_label = ["name", "old", "gender", "constellation"]
        user_info = {}
        host_info = {}
        chatbot_info = {}
        # qa_info = {"host": qa_host_info, "user": self_label, "chatbot": qa_chat_info}

        params_ls = ["content", "sessionId", "message_type"]
        input_sentence = ""
        session_id = "0000"
        if all(param in params for param in params_ls):
            input_sentence = params["content"]
            session_id = params["sessionId"]
            message_type = params["message_type"]

            if params.has_key("user_label"):
                try:
                    if isinstance(params["user_label"], dict):
                        user_info = params["user_label"]
                    else:
                        user_info_tmp = json.loads(params["user_label"])
                        if isinstance(user_info_tmp, dict):
                            user_info = user_info_tmp
                except:
                    pass
            chatbot_info_tmp = params.get("pet_label", {})
            if isinstance(chatbot_info_tmp, dict):
                chatbot_info = chatbot_info_tmp
            else:
                try:
                    chatbot_info_tmp = json.loads(params["pet_label"])
                    if isinstance(chatbot_info_tmp, dict):
                        chatbot_info = chatbot_info_tmp
                except:
                    chatbot_info = {}
            logger.info("pet label = {}".format(chatbot_info))
            host_info_tmp = params.get("host_label", {})
            if isinstance(host_info_tmp, dict):
                host_info = host_info_tmp
            else:
                try:
                    host_info_tmp = json.loads(params["host_label"])
                    if isinstance(host_info_tmp, dict):
                        host_info = host_info_tmp
                except:
                    host_info = {}
            logger.info("host Label={}".format(host_info))
            input_sentence = remove_emoji(input_sentence)
            # logger.info("input sentence clean res{}".format(input_sentence))
            try:
                if (message_type == 1) and len(input_sentence) > 0:
                    rule = NoStanfordRule(qa_host_label=host_info,
                                          qa_chat_label=chatbot_info)
                    match = Match(input_sentence, logger, session_id, rule)
                    # cache_post = requests.post(url="http://127.0.0.1", data={"userId": user_id, "petId": pet_id})
                    # if cache_post.status_code == 200:
                    #     resp = json.loads(cache_post.text)
                    #     cache = resp["cache"]

                    # if match.user_info:
                    #     for _key in match.user_info:
                    #         if type(match.user_info[_key]) in (str, int, float, unicode):
                    #             cache.set_user(_key, match.user_info[_key])
                    # for _base in base_label:
                    #     cache_user = cache.get_user(_base)
                    #     cache_host = cache.get_host(_base)
                    #     cache_chatbot = cache.get_chatbot(_base)
                    #     if cache_user:
                    #         user_info.update({_base: cache_user})
                    #     if cache_host:
                    #         host_info.update({_base: cache_host})
                    #     if cache_chatbot:
                    #         chatbot_info.update({_base: cache_chatbot})

                    # for _key in user_info:
                    #     print("the user info key= %s and value= %s" %(_key,user_info[_key]))
                    # object_info = {"host":host_info,"user":user_info,"chatbot":chatbot_info}
                    answer, answer_type, _, _, _ = main(
                        match, proc_trie, proc_ratio, idf_trie, answer_indexs,
                        srcFiles.template_file)

                    del match
                    del rule
                else:
                    answer = random.choice(emoji_lib)
                code = 10000
            except:
                logger.info(traceback.format_exc())
                answer = random.choice(ans_libs)
                code = 20000
        else:
            answer = "invalid params input"
            code = 30000
        t1 = time.time()
        t_delta = t1 - t0
        if isinstance(answer, unicode):
            answer = answer.encode("utf-8")
        # lock = threading.RLock()
        # lock.acquire()
        logger.info("add s,p,o into graph...")
        time_stamp = str(time.time()).replace(".", "")
        add2rdf(session_id, input_sentence, answer, time_stamp)
        self.cn += 1
        if self.cn > 5:
            logger.info("serailize into log file")
            pwd = cur_dir
            logger.info("current dir:\t%s" % pwd)
            if cur_dir.endswith("src"):
                #返回上级目录
                pwd = os.path.dirname(cur_dir)
                if pwd.endswith("chatbot"):
                    pwd = os.path.join(pwd, "log")
            g.serialize(os.path.join(pwd, "session.rdf"), format="xml")
            # logger.info("serailize sucessfully")
            self.cn = 0

        # lock.release()
        response = jsonify({
            "code": code,
            "response": answer,
            "match_type": answer_type,
            "time_response": t_delta
        })
        # response = {"code": code, "response": answer, "match_type": answer_type, "time_response": t_delta}
        return response
示例#6
0
def chat():
    base_label = ["name", "old", "gender", "constellation"]
    user_info = {}
    host_info = {
        "userAge": 18,
        "sex": 1,
        "hobby": u"吃鸡睡觉打豆豆"
    }
    chatbot_info = {"name": u"小可爱", "sex": u"纯爷们儿", "age": 2}
    # qa_info = {"host": qa_host_info, "user": self_label, "chatbot": qa_chat_info}
    if session.get('qa') == None:
        session['qa'] = []
    if request.method == 'POST':
        if session.get('ip') == None:
            session['ip'] = request.remote_addr.replace(".", "_")
        sentence = request.form['sentence']
        session_id = str(random.random()).split(".")[-1]
        answer_type = ""
        t0 = time.time()
        try:
            rule = NoStanfordRule(qa_host_label=host_info,
                                  qa_chat_label=chatbot_info)
            match = Match(sentence, logger, session_id, rule)
            # if match.user_info:
            #     for _key in match.user_info:
            #         cache.set_user(_key,match.user_info[_key])
            # for _base in base_label:
            #     cache_user = cache.get_user(_base)
            #     cache_host = cache.get_host(_base)
            #     cache_chatbot = cache.get_chatbot(_base)
            #     if cache_user:
            #         user_info.update({_base: cache_user})
            #     if cache_host:
            #         host_info.update({_base: cache_host})
            #     if cache_chatbot:
            #         chatbot_info.update({_base: cache_chatbot})

            # for _k in user_info:
            #     print("user key= %s and value= %s" %(_k,user_info[_k]))
            # object_info = {"host": host_info, "user": user_info, "chatbot": chatbot_info}
            answer, answer_type, answer_ind, _, _ = main(
                match, proc_trie, proc_ratio, idf_trie, answer_indexs,
                srcFiles.template_file)
            if answer_ind:
                try:
                    from_ques = src_trie[answer_ind]
                except:
                    pass
            code = 10000
            del match
        except:
            logger.info(traceback.format_exc())
            answer = random.choice(ans_libs)
            code = 20000
        t1 = time.time()
        t_delta = t1 - t0
        # response = jsonify({"code":code,"response":answer,"match_type":answer_type,"time_response":t_delta})
        if isinstance(answer, unicode):
            answer = answer.encode("utf-8")
        # res = {"code": code, "answer": answer, "from_ques": from_ques, "match_type": answer_type, "time_response": t_delta}
        _answer = [answer, answer_type, t_delta, code]
        try:
            print "answer:\t\n%s\n" % _answer
        except Exception:
            pass
        session['qa'] = [[sentence] + _answer] + session['qa']
        try:
            print session
        except Exception:
            pass
        return render_template('chat.html',
                               qa=session.get('qa'),
                               qa_len=len(session.get('qa')))
    return render_template('chat.html',
                           qa=session['qa'],
                           qa_len=len(session['qa']))