From 078b5540feb7ed074a9ecaa8061d93e1ac5156f6 Mon Sep 17 00:00:00 2001 From: hxw Date: Fri, 29 Jun 2018 17:32:43 +0800 Subject: [PATCH] 修复bug、添加automatchURL等字段 --- GenerateAction/Action.py | 134 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------- GenerateAction/BackgroundConfig.py | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------- GenerateAction/SQLHelper.py | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- GenerateAction/action_service.py | 8 ++++++-- GenerateAction/edit_distance.py | 38 ++++++++++++++++++++++++++++++++++++++ GenerateAction/global_config.txt | 25 ++++++++++++++----------- GenerateAction/post_test.py | 5 +++++ src/entity/Condition.java | 8 ++++---- src/entity/UserInfo.java | 6 ++++++ src/processing/MyFunc.java | 6 ++++++ src/processing/ProcessQuestion.java | 43 +++++++++++++++++++++++++++++-------------- src/servlet/GetAnswerServlet.java | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------- src/servlet/ReloadConfigServlet.java | 9 ++++++++- src/servlet/UpdateServlet.java | 19 ++++++++++++++----- 14 files changed, 421 insertions(+), 132 deletions(-) create mode 100644 GenerateAction/edit_distance.py diff --git a/GenerateAction/Action.py b/GenerateAction/Action.py index 9642af2..21ef266 100644 --- a/GenerateAction/Action.py +++ b/GenerateAction/Action.py @@ -4,23 +4,27 @@ reload(sys); from SQLHelper import * sys.setdefaultencoding('utf8'); import pickle +import json import requests class Action: def __init__(self): + self.CONFIG_DIC = {} #存储全局配置文件的信息 + self.load_global_config("global_config.txt") self.botId = "" self.userName = "" self.botName = "" self.waiting_str = "" self.listening_str = "" - self.http_str = "#actions\r\nname=pivot_httppost\r\naction=select\r\nstatus=waiting\r\n" + self.http_str = "#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\nstyle=httppost\r\nserviceURL=" \ + +self.CONFIG_DIC["serviceURL"] + "\r\nautomatchthreshold=" \ + +self.CONFIG_DIC["automatchthreshold"] + "\r\n" self.next_str = "" self.FUNC_MAP = {"action":self.parse_name,"status":self.parse_status,"condition":self.parse_condition ,"conflict":self.parse_conflict,"process":self.parse_process} - self.CONFIG_DIC = {} #存储全局配置文件的信息 - self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold","automatchurl" - ,"serviceurl","pattern","conflict","importance","style"] - self.load_global_config("global_config.txt") + self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold" + ,"pattern","conflict","importance","style"] + self.KEYWORD_UNIT_INFO = ["options","AutoMatchURL"] self.condition_name_list = [] self.sql_helper = SQLHelper() @@ -30,7 +34,7 @@ class Action: for line in config: if line.strip() == "": continue - name,value = line.split("=") + name,value = line.split("|") self.CONFIG_DIC[name] = value.strip() @@ -38,12 +42,9 @@ class Action: flag = 1 try: userName = parameters["userName"]#.encode("utf-8") - self.userName = userName conditionList = parameters["conditionList"] botName = parameters["botName"] - self.botName = botName botId = parameters["botId"] - self.botId = botId condition_name_list = ["process=nextStep="+condition["conditionName"]+"|"+condition["conditionName"]+"=active|" for condition in conditionList] print condition_name_list @@ -51,53 +52,59 @@ class Action: for condition in conditionList: conditionName = condition["conditionName"]#.encode("utf-8") - relation = condition["relationHead"]+","+condition["relationName"]+","+condition["relationTail"]#.encode("utf-8") - question = condition["question"]#.encode("utf-8") + questionList = [que["que_start_time"]+":"+que["que_stop_time"]+":"+que["que_sen"]+":base" if que["base"] == 1 + else que["que_start_time"]+":"+que["que_stop_time"]+":"+que["que_sen"] + for que in condition["questionList"]] + questionList_str = '~'.join(questionList) repeatList = condition["repeatList"] active_flag = condition["active"] + relation = condition["relationHead"]+","+condition["relationName"]+","+condition["relationTail"]#.encode("utf-8") print conditionName + print active_flag for i in range(3): - + self.insert_action_info(conditionName,active_flag,i) - self.insert_condition(conditionName,relation,question,repeatList,i) + self.insert_condition(conditionName,relation,questionList_str,repeatList,i) self.insert_process(conditionName,repeatList,i) - self.waiting_str += "process="+conditionName+"=+unknown|\r\n"+self.all_nextStep +"\n\r" - except KeyError: + self.waiting_str += "process="+conditionName+"=unknown|pivot_httppost=active|\r\n" + #add a extra information for backend config file +# if active_flag ; +# parameters["activeAction"] = conditionName + except KeyError as e: + print repr(e) return 2 return flag def save_action(self,parameters,auth): - userName = self.userName - botName = self.botName - botId = self.botId - userFile = open(userName+"-"+botName+"-action.txt",'w') - userData = open(userName+"-"+botName+"-action.data",'w') - pickle.dump(parameters,userData) - final_str = self.http_str + self.next_str+ self.waiting_str+self.listening_str+"\r\n\r\n\r\n" - userFile.write(final_str) - userFile.close() - userData.close() - if botId == "" or botId == None or botId == "undefined": - flag = self.post_action(final_str,botName,parameters["cate"],parameters["cdt_name_ls"],auth) - print "flag:"+str(flag) - else: - bot_id = self.sql_helper.query_userid_by_username(botName) - print bot_id - if bot_id != -1: - effect_row = self.sql_helper.update_action_text_by_userid(int(bot_id),final_str) - if not effect_row: - flag = 3 - else: - flag = 4 + userName = parameters["userName"] + botName = parameters["botName"] + botName_yhm = parameters["botName_yhm"] + botId = parameters["botId"] + + final_str = self.http_str + self.next_str + self.waiting_str+self.listening_str+"\r\n\r\n\r\n" + flag,id = self.post_action(final_str,botId,botName_yhm,parameters["cate"],parameters["cdt_name_ls"],auth) + if id != "error": + botName = self.sql_helper.query_username_by_userid(id) + if flag == 1 and botName != "error": + userFile = open("data/"+str(userName)+"-"+str(botName)+"-action.txt",'w') + userData = open("data/"+str(userName)+"-"+str(botName)+"-action.data",'w') + pickle.dump(parameters,userData) + userFile.write(final_str) + userFile.close() + userData.close() + flag = 4 if botName == "error" else flag + print "sql_query:",botName + + return flag def reload_action(self,userName,botName): try: - userFile = open(userName+"-"+botName+"-action.data",'r') + userFile = open("data/"+str(userName)+"-"+str(botName)+"-action.data",'r') ''' actionList = [] action = {} @@ -161,8 +168,9 @@ class Action: def insert_action_info(self,conditionName,active_flag,flag): if not flag: - status = "active" if active_flag==True else "waiting" - self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\nstyle=interrupt,httppost\r\n" + status = "waiting" if not active_flag else "active" + print status + self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\nstyle=interrupt\r\n" for key in self.ACTION_HEAD_INFO: if(self.CONFIG_DIC[key] != ""): self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' @@ -170,26 +178,32 @@ class Action: if flag == 1: status = "listening" - self.listening_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n" + self.listening_str += "\r\n\r\nname=" + conditionName + "_listening\r\nstatus="+status+"\r\n" for key in self.ACTION_HEAD_INFO: if(self.CONFIG_DIC[key] != ""): self.listening_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' self.listening_str += "fellow=pivot_httppost\r\n" + elif flag ==2: + ''' + for key in self.ACTION_HEAD_INFO: + if(self.CONFIG_DIC[key] != ""): + self.http_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' + ''' - def insert_condition(self,conditionName,relation,question,repeatList,flag): + def insert_condition(self,conditionName,relation,questionList,repeatList,flag): if not flag: - self.waiting_str += "condition="+conditionName+"::1|"+relation+"|"+question+"|" + self.waiting_str += "condition="+conditionName+"::1|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.waiting_str += reS + "\r\n" if flag == 1: - self.listening_str += "condition="+conditionName+"|"+relation+"|"+question+"|" + self.listening_str += "condition="+conditionName+"|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.listening_str += reS + "\r\n" if flag == 2: - self.http_str += "reference="+conditionName+"|"+relation+"|"+question+"|" + self.http_str += "reference="+conditionName+"|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.http_str += reS + "\r\n" @@ -198,26 +212,34 @@ class Action: def insert_process(self,conditionName,repeatList,flag): if not flag: for repeat in repeatList: - self.waiting_str += "process="+conditionName+"=+"+repeat["repeatKeywords"]+"|pivot_httppost=active|\r\n" + self.waiting_str += "process="+conditionName+"=+"+repeat["repeatKeywords"].split('-')[0]+"|pivot_httppost=active|\r\n" elif flag == 1: for repeat in repeatList: - self.listening_str += "process="+conditionName+"=+"+repeat["repeatKeywords"]+"|pivot_httppost=active|\r\n" + self.listening_str += "process="+conditionName+"=+"+repeat["repeatKeywords"].split('-')[0]+"|pivot_httppost=active|\r\n" elif flag == 2: self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n" - def post_action(self,action_str,botName,cate,cdt_name_ls,auth): - url= self.CONFIG_DIC["engine_url"] - payload= {'id':"",'botname':botName,'actions':action_str,'cate':cate,"cdt_name_ls":cdt_name_ls} + def post_action(self,action_str,botId,botName_yhm,cate,cdt_name_ls,auth): + url = self.CONFIG_DIC["engine_url"] + print action_str + botId = "" if botId == "undefined" else int(botId) + payload= {'id':botId,'botname':botName_yhm,'actions':action_str,'cate':cate,"cdt_name_ls":cdt_name_ls} headers = {"Authorization":auth} ret= requests.post(url,json=payload,headers=headers) - print "xx" print ret.text - if(ret.status_code == 200): - return 1 - elif(ret.status_code == 111): - return 2 + return_info = json.loads(ret.text) + if(ret.status_code == 200 and return_info["status"] == "Success" and botId == ""): + keywords = [keyword+"|"+self.CONFIG_DIC[keyword]+"\r\n" for keyword in self.KEYWORD_UNIT_INFO] + text = self.sql_helper.query_keyword_unit_by_userid(return_info["id"]) + k_unit_str = text + ''.join(keywords) + flag = self.sql_helper.update_keyword_unit_by_userid(return_info["id"],k_unit_str) + +# flag = self.sql_helper.update_url(return_info["id"],self.CONFIG_DIC["get_info_url"]) + return flag,return_info["id"] + elif(ret.status_code == 200 and return_info["status"] == "Success" and botId != ""): + return 1,return_info["id"] else: - return 4 + return 4,"error" diff --git a/GenerateAction/BackgroundConfig.py b/GenerateAction/BackgroundConfig.py index 98055fd..280ca2b 100644 --- a/GenerateAction/BackgroundConfig.py +++ b/GenerateAction/BackgroundConfig.py @@ -3,6 +3,7 @@ import requests import json from Action import * import sys; +import os reload(sys); sys.setdefaultencoding('utf8'); @@ -22,12 +23,12 @@ class BackgroundConfig(): for line in config: if line.strip() == "": continue - name,value = line.split("=") + name,value = line.split("|") self.CONFIG_DIC[name] = value.strip() def reload_background_config(self,userName,botName): try: - userFile = open(userName+"-"+botName+'-config.data','r') + userFile = open("data/"+userName+"-"+botName+'-config.data','r') ''' actionList = [] action = {} @@ -45,50 +46,120 @@ class BackgroundConfig(): except IOError: data = [] return {"configList":data} - + + ''' + 保存配置文件 + ''' def save_background_config(self,parameters): flag = 1 try: userName = parameters["userName"].strip() configList = parameters["configList"] botName = parameters["botName"].strip() + + self.config_string += self.load_extra_user_info(userName,botName) for config in configList: currentPremiseList = config["currentPremiseList"] reply = config["reply"].strip() if config["reply"] != "" else " " - nextStep = config["nextStep"].strip() + nextStep = config["nextStep"].strip() if config["nextStep"] != "" else " " + feature = "match,post("+config["postURL"].strip()+")" if config["doPost"] else "match" historyPremiseList = config["historyPremiseList"] - if nextStep == "" : - flag = 2 - break if len(currentPremiseList) == 1 and currentPremiseList[0]["keywords"] == "": flag = 3 break - curPreStr = ','.join([currentPremise["actionName"]+"="+currentPremise["keywords"] for currentPremise in currentPremiseList]) + curPreStr = ','.join([currentPremise["actionName"]+"=+"+currentPremise["keywords"].lstrip("+").split("-")[0] for currentPremise in currentPremiseList]) if historyPremiseList != [] and historyPremiseList[0]["keywords"] != "": - hisPreStr = ','.join([historyPremise["actionName"]+"="+historyPremise["keywords"] for historyPremise in historyPremiseList]) + hisPreStr = ','.join([historyPremise["actionName"]+"=+"+historyPremise["keywords"].lstrip("+").split("-")[0] for historyPremise in historyPremiseList]) else: hisPreStr = "" if hisPreStr == "": - config_line = curPreStr + "| |"+"match|=>|"+reply+"|nextStep="+nextStep+'\n' + config_line = curPreStr + "| |"+feature+"|=>|"+reply+"|nextStep="+nextStep+'\n' else: - config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n' + config_line = curPreStr + "|"+hisPreStr+"|"+feature+"|=>|"+reply+"|nextStep="+nextStep+'\n' self.config_string += config_line - print self.config_string + print self.config_string,flag if flag == 1: - userData = open(userName+"-"+botName+'-config.data','w') + userData = open("data/"+userName+"-"+botName+'-config.data','w') pickle.dump(parameters,userData) userData.close() - except KeyError: + except KeyError as e: + print repr(e) flag = 2 return flag - def post_bg_config(self,userName): - url= self.CONFIG_DIC["config_post_url"] - payload= {'userName':userName,'config_string':self.config_string} + + ''' + 从用户之前创建的action中获取额外信息,如设为active的action + ''' + def load_extra_user_info(self,userName,botName): + extra_info = "" + data_file = "data/"+userName+"-"+botName+'-action.data' + if os.path.isfile(data_file): + user_data = {} + with open(data_file,'r') as f: + user_data = pickle.load(f) + + conditionList = user_data["conditionList"] + for condition in conditionList: + if condition["active"]: + extra_info += "-extraInfo-|activeAction|"+condition["conditionName"]+"\n" + + + return extra_info + + + + + + + def change_bg_config(self,userName,botName,conditionList): + data_file = "data/"+userName+"-"+botName+'-config.data' + print "data_file:",data_file + if os.path.isfile(data_file): + user_data = {} + with open(data_file,'r') as f: + user_data = pickle.load(f) + + condition_name_list = [condition["conditionName"] for condition in conditionList] + config_list = user_data["configList"] + config_list_new = [] + for config in config_list: + currentPremiseList_new = [] + config["nextStep"] = config["nextStep"] if config["nextStep"] in condition_name_list else "" + currentPremiseList = config["currentPremiseList"] + currentPremiseList = [{"actionName":premise["actionName"],"keywords":premise["keywords"],"question":premise["question"]} + if premise["actionName"] in condition_name_list + else {"actionName":"","keywords":"","question":premise["question"]} + for premise in currentPremiseList] + empty_indicator = [1 if premise["actionName"] == "" else 0 for premise in currentPremiseList] + if sum(empty_indicator) == len(currentPremiseList): + continue + + historyPremiseList = config["historyPremiseList"] + historyPremiseList = [{"actionName":premise["actionName"],"keywords":premise["keywords"],"question":premise["question"]} + if premise["actionName"] in condition_name_list + else {"actionName":"","keywords":"","question":premise["question"]} + for premise in historyPremiseList] + config["currentPremiseList"] = currentPremiseList + config["historyPremiseList"] = historyPremiseList + config_list_new.append(config) + user_data["configList"] = config_list_new + with open(data_file,'w') as f: + pickle.dump(user_data,f) + + return 1 + + else: + return 1 + + + def post_bg_config(self,botName): + url= self.CONFIG_DIC["config_update_url"] + payload= {'userName':botName,'config_string':self.config_string} ret= requests.post(url,data=payload) if(ret.status_code == 200): diff --git a/GenerateAction/SQLHelper.py b/GenerateAction/SQLHelper.py index 5787bba..79dbb1a 100644 --- a/GenerateAction/SQLHelper.py +++ b/GenerateAction/SQLHelper.py @@ -3,6 +3,7 @@ import pymysql class SQLHelper: def __init__(self): self.conn_dict = dict(host="192.168.1.81",port=3306,user="root",passwd="admin",db="chatCN",charset="utf8") + #self.conn_dict = dict(host="http://qcloud-sh1.chewrobot.com",port=3306,user="root",passwd="3g9^pWQs#ft7",db="chatCN",charset="utf8") def query_userid_by_username(self,username): try: conn = pymysql.connect(**self.conn_dict) @@ -18,11 +19,64 @@ class SQLHelper: else : return -1 except Exception as e: - raise e + print repe(e) finally: cur.close() conn.close() + def query_username_by_userid(self,userid): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "select username from users where id=%d"%int(userid) + print "xx" + cur = conn.cursor() + cur.execute(sql) + results = cur.fetchall() + conn.commit() + if len(results): + return results[0][0] + else: + return "error" + + except Exception as e: + print repr(e) + finally: + cur.close() + conn.close() + + + def query_keyword_unit_by_userid(self,userid): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "select text from units where user_id=%d and name='keywords'"%int(userid) + cur = conn.cursor() + cur.execute(sql) + results = cur.fetchall() + conn.commit() + if len(results): + return results[0][0] + else: + return "error" + except Exception as e: + print repr(e) + finally: + cur.close() + conn.close() + + + def update_keyword_unit_by_userid(self,userid,keyword_str): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "update units set text = '%s' where name='keywords' and user_id=%d"%(keyword_str,userid) + cur = conn.cursor(cursor=pymysql.cursors.DictCursor) + effect_row = cur.execute(sql) + conn.commit() + return effect_row + except Exception as e: + print repr(e) + finally: + cur.close() + conn.close() def update_action_text_by_userid(self,userid,action_str): try: @@ -33,11 +87,26 @@ class SQLHelper: conn.commit() return effect_row except Exception as e: - raise e + print repr(e) finally: cur.close() conn.close() + def update_url(self,bot_id,url): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "update users set url = '%s' where id= %d"%(url,bot_id) + cur = conn.cursor(cursor=pymysql.cursors.DictCursor) + effect_row = cur.execute(sql) + conn.commit() + return effect_row + except Exception as e: + print repr(e) + finally: + cur.close() + conn.close() + + ''' def create_new_bot(self,userName,botName) try: diff --git a/GenerateAction/action_service.py b/GenerateAction/action_service.py index 6e18554..9985ce4 100644 --- a/GenerateAction/action_service.py +++ b/GenerateAction/action_service.py @@ -25,10 +25,13 @@ def save_action(): action = Action() dc = json.loads(request.get_data().decode("utf8")) flag = action.generate_action(dc) + print dc if flag == 1: - auth = request.headers['Authorization'] action.save_action(dc,auth) + if(dc["botId"] != ""): + bg_config = BackgroundConfig() + bg_config.change_bg_config(dc["userName"],dc["botName"],dc["conditionList"]) print flag if flag == 1: return "success" @@ -60,10 +63,11 @@ def save_background_config(): if request.method == 'POST': bg_config = BackgroundConfig() parameters = json.loads(request.get_data().decode("utf8")) + print parameters flag = bg_config.save_background_config(parameters) if flag == 1: - flag = bg_config.post_bg_config(parameters["userName"]) + flag = bg_config.post_bg_config(parameters["botName"]) print flag if flag == 1: diff --git a/GenerateAction/edit_distance.py b/GenerateAction/edit_distance.py new file mode 100644 index 0000000..1b7f755 --- /dev/null +++ b/GenerateAction/edit_distance.py @@ -0,0 +1,38 @@ + + + + + +def min_ed(sent1,sent2): + l1 = len(sent1) + l2 = len(sent2) + matrix = [[0 for j in range(l2)] for i in range(l1)] + matrix[0][0] = 0 + for i in range(1,l1): + matrix[i][0] = i + for j in range(1,l2): + matrix[0][j] = j + for i in range(1,l1): + for j in range(1,l2): + d = 1 if sent1[i] != sent2[j] else 0 + matrix[i][j] = min(matrix[i][j-1]+1,matrix[i-1][j]+1,matrix[i-1][j-1]+d) + for i in range(l1): + for j in range(l2): + print matrix[i][j], + print "" + + + + + + + + + + + + + + +if __name__ == "__main__": + min_ed("#abc","#dcb") diff --git a/GenerateAction/global_config.txt b/GenerateAction/global_config.txt index fd0ed81..75e8e72 100644 --- a/GenerateAction/global_config.txt +++ b/GenerateAction/global_config.txt @@ -1,12 +1,15 @@ -action=select -strategythreshold= -automatchthreshold= -automatchurl= -serviceurl= -pattern= -conflict= -importance= -style= -backend_url=http://192.168.1.178:8081/bot/update -engine_url=http://192.168.1.81:6636/api/post/actions +action|select +strategythreshold| +automatchthreshold|0.5 +pattern| +conflict| +importance| +style| +config_update_url|http://192.168.1.178:8081/bot/update +serviceURL|http://192.168.1.178:8081/bot/test +engine_url|http://192.168.1.81:6636/api/post/actions +options|disable_knowledge_qa,fast_understanding,no_parser +AutoMatchURL|http://dev01.centaurstech.com:5700/mermaid/?model=auto-train + + diff --git a/GenerateAction/post_test.py b/GenerateAction/post_test.py index 15aaa75..879dd9e 100644 --- a/GenerateAction/post_test.py +++ b/GenerateAction/post_test.py @@ -25,5 +25,10 @@ def login(): if __name__ == '__main__': app.run(host="0.0.0.0", port=8888,) + + + + +{u'userName': u'aaa', u'cdt_name_ls': [[250, u'rule0find0daikuan'], [251, u'rule0find0zhuangxiu'], [252, u'rule0find0dianti']], u'botName_yhm': u'xx', u'cate': [14], u'botId': u'275', u'conditionList': [{u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u8d2d\u4e70\u8d37\u6b3e', u'repeatKeywords': u'\u8d37\u6b3e-\u4e0d\u8d37\u6b3e'}], u'relationName': u'rule-find-daikuan', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u8d37\u6b3e\u653f\u7b56\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'daikuan', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}, {u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u623f\u5b50\u88c5\u4fee', u'repeatKeywords': u'\u6bdb\u576f\u623f+\u7cbe\u88c5+\u88c5\u4fee'}], u'relationName': u'rule-find-zhuangxiu', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u623f\u5b50\u88c5\u4fee\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'zhuangxiu', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}, {u'idx': 0, u'repeatList': [{u'repeatString': u'#visitorname\u95ee\u623f\u5b50\u7535\u68af', u'repeatKeywords': u'\u7535\u68af'}], u'relationName': u'rule-find-dianti', u'question': [{u'que_start_time': u'1', u'base': 1, u'que_stop_time': u'100', u'que_sen': u'\u5bf9\u4e8e\u7535\u68af\u60a8\u8fd8\u6709\u4ec0\u4e48\u7591\u95ee\uff1f'}], u'conditionName': u'dianti', u'relationHead': u'#visitorname', u'active': True, u'relationTail': u'?'}], u'botName': u'4183891231'} diff --git a/src/entity/Condition.java b/src/entity/Condition.java index 4c3e055..910be4e 100644 --- a/src/entity/Condition.java +++ b/src/entity/Condition.java @@ -13,10 +13,10 @@ public class Condition { public HashSet keywordSet = new HashSet(); public HashMap> historyPremise = new HashMap>(); public HashMap> currentPremise = new HashMap>(); - public String Answer; - public String nextStep; - public String feature; - public String indexName; + public String[] answer = {"",}; + public String nextStep = ""; + public String feature = ""; + public String indexName = ""; //public ArrayList indexName = new ArrayList(); public Condition(int priority) { diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java index 7b50a5c..1580769 100644 --- a/src/entity/UserInfo.java +++ b/src/entity/UserInfo.java @@ -11,10 +11,16 @@ public class UserInfo { this.conditionTable = new HashMap>(); this.configStr = ""; this.userName = userName; + this.extraInfo = new HashMap(){ + { + put("activeAction",""); + } + }; } public HashMap> conditionTable; public String configStr; public String userName; + public HashMap extraInfo; } diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java index c583abe..a6bbf18 100644 --- a/src/processing/MyFunc.java +++ b/src/processing/MyFunc.java @@ -7,6 +7,7 @@ import java.io.UnsupportedEncodingException; public class MyFunc { + /** * 将后台返回的数据转成json格式 */ @@ -17,6 +18,11 @@ public class MyFunc { jobj.put("process", ans.getNext()); return jobj.toString(); } + public static String toJson(String returnStr){ + JSONObject jobj = new JSONObject(); + jobj.put("returnString",returnStr); + return jobj.toString(); + } /** * 通过get方法传递参数时需要对参数的编码进行转换 diff --git a/src/processing/ProcessQuestion.java b/src/processing/ProcessQuestion.java index 7801a86..8bb96d5 100644 --- a/src/processing/ProcessQuestion.java +++ b/src/processing/ProcessQuestion.java @@ -73,13 +73,13 @@ public class ProcessQuestion { public static Condition buildCondition(Condition condition,String line){ String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[]; - element = line.trim().split("\\|=\\>\\|"); + element = line.replace("\n","").split("\\|=\\>\\|"); premises = element[0].split("\\|"); feature = premises[2]; cur_premises = premises[0].split(","); history_premises = premises[1].split(","); next = element[1].split("\\|"); - condition.Answer = next[0]; + condition.answer = next[0].split("~"); //condition.nextStep = next[1]; //第二处 condition.nextStep = next[1].split("=")[1]; @@ -104,7 +104,7 @@ public class ProcessQuestion { * 逐行读取用户配置文件,并保存在userinfo.conditionTable中 */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo) throws IOException { - String line; + String line,infoName,extraElements[]; HashMap> conditionTable = new HashMap>(); List conditionList = null; @@ -112,15 +112,21 @@ public class ProcessQuestion { while ((line = br.readLine()) != null) { if (line.trim().equals("")) continue; + line = line.replace("\n",""); + //在用户信息中添加额外信息,如设为active的action + if(line.indexOf("-extraInfo-") != -1){ + extraElements = line.split("\\|"); + userinfo.extraInfo.put(extraElements[1],extraElements[2]); + }else { + Condition condition = new Condition(); + condition = buildCondition(condition, line); + conditionList = conditionTable.get(condition.indexName); + if (conditionList == null) + conditionList = new ArrayList(); + conditionList.add(condition); + conditionTable.put(condition.indexName, conditionList); + } userinfo.configStr += line + '\n'; - Condition condition = new Condition(); - condition = buildCondition(condition, line); - conditionList = conditionTable.get(condition.indexName); - if (conditionList == null) - conditionList = new ArrayList(); - conditionList.add(condition); - conditionTable.put(condition.indexName, conditionList); - } userinfo.conditionTable = conditionTable; @@ -282,11 +288,14 @@ public class ProcessQuestion { Iterator it = curInfoPoint.keySet().iterator(); String actionName; AnswerNextStep ans = new AnswerNextStep(); - ans.setAnswer(ansCondition.Answer); + + //如果一条配置文件有多个答案,则随机选择一个答案 + int randNum = (int) (Math.random() * ansCondition.answer.length); + ans.setAnswer(ansCondition.answer[randNum]); //System.out.println(ans.getAnswer()); System.out.println("feature="+ansCondition.feature); if(ansCondition.feature.indexOf("post") != -1){ - postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); + ans = postToServer(ans,ansCondition,curInfoPoint,historyInfoPoint); } try { @@ -310,6 +319,9 @@ public class ProcessQuestion { } } + + //保存即将跳转的action名以供下一轮使用 + historyInfoPoint.put("currentAction",ansCondition.nextStep); ChatCacheController.updateChatCache4Insert(curInfoPoint, historyInfoPoint, context); //context.setAttribute("chat_key+"+userinfo.userName,historyInfoPoint); @@ -362,7 +374,10 @@ public class ProcessQuestion { keyName = kit.next(); if(keyName.equals("process")){ ans.setNext("nextStep="+jobj.get(keyName)); - }else{ + }else if(keyName.equals("solution")) { + ans.setAnswer((String) jobj.get(keyName)); + } + else{ ans.setAnswer(ans.getAnswer().replace("{"+keyName+"}",jobj.getString(keyName))); } } diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index eb3f58d..e7c5d09 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -18,22 +18,25 @@ import java.io.OutputStream; import java.sql.SQLException; import java.util.*; -/** - * GetAnswerServlet就是处理post请求并返回答案的入口 - */ + @WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"}) public class GetAnswerServlet extends HttpServlet { + /** + * GetAnswerServlet就是处理post请求并返回答案的入口 + */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); - Map curInfoPoint = request.getParameterMap(); + Map curInfoPoint = new HashMap<>(request.getParameterMap()); Map historyInfoPoint = null; AnswerNextStep bestMatch = null; Condition ansCondition = null; - String ansJ,return_str=""; + String ansJ,return_str="",state = ""; String chatKey = curInfoPoint.get("chat_key")[0]; ProcessQuestion process = new ProcessQuestion(); OutputStream out = response.getOutputStream(); ServletContext context = this.getServletContext(); + //获得用户历史信息 + historyInfoPoint = ChatCacheController.getChatCache(chatKey,context); UserInfo userinfo = null; @@ -42,13 +45,12 @@ public class GetAnswerServlet extends HttpServlet { //从servlet根据用户名查询用户信息 userinfo = process.userInfoQuery(request.getParameter("bot_name"),context); } catch (SQLException e) { + state = "没找到bot名?"; e.printStackTrace(); } - //获得用户历史信息 - historyInfoPoint = ChatCacheController.getChatCache(chatKey,context); - + //如果historyInfoPoint不存在,就新建一个 if(historyInfoPoint == null) { String k; historyInfoPoint = new HashMap(); @@ -65,35 +67,67 @@ public class GetAnswerServlet extends HttpServlet { Iterator iit = curInfoPoint.keySet().iterator(); while(iit.hasNext()){ String k = iit.next(); + // System.out.print(k+": "); String values[] = curInfoPoint.get(k); if(values != null && !values[0].equals(" ") && !values[0].equals("") && !k.equals("chat_key") && !k.equals("action_name") && !k.equals("bot_name")) - return_str = return_str + " " + k + ":" + values[0] + " "; + //return_str = return_str + " " + k + ":" + values[0] + " "; for(String v:values) { System.out.print(v + " "); } System.out.println(); } - + //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown + iit = curInfoPoint.keySet().iterator(); + boolean unknown_flag = true; + while(iit.hasNext()){ + String k = iit.next(); + String values[] = curInfoPoint.get(k); + if(k.equals("chat_key") || k.equals("action_name") || k.equals("bot_name")) + continue; + if(values != null && !values[0].equals("")) { + unknown_flag = false; + break; + } + } + String currentAction = ""; + if(historyInfoPoint.containsKey("currentAction")) + currentAction = historyInfoPoint.get("currentAction"); + else if(userinfo.extraInfo.containsKey("activeAction")) + currentAction = userinfo.extraInfo.get("activeAction"); + else + currentAction = ""; + + + if(unknown_flag && currentAction != ""){ + String i[] = {"unknown",}; + curInfoPoint.put(currentAction,i); + } /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ //process.removeTimeoutChatkey(context); //System.out.println(userinfo.conditionTable); //测试 ansCondition = process.getAnswer(curInfoPoint,historyInfoPoint,userinfo.conditionTable); - bestMatch = process.updateInfoGetBestMatch(ansCondition,curInfoPoint,historyInfoPoint,context,userinfo); - //process.updateDB(kw); - //System.out.println("Current time:" + System.currentTimeMillis()); - if(context.getAttribute("cacheUpdateTime") == null) - context.setAttribute("cacheUpdateTime",System.currentTimeMillis()); - if(System.currentTimeMillis() - (long)context.getAttribute("cacheUpdateTime") > 300000) { - ChatCacheController.updateChatCache4Delete(context); - context.setAttribute("cacheUpdateTime",System.currentTimeMillis()); + if (state == "" && ansCondition.priority == 0) + state = "你好像哪里写错了"; + if (state == "") { + bestMatch = process.updateInfoGetBestMatch(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); + //process.updateDB(kw); + //System.out.println("Current time:" + System.currentTimeMillis()); + if (context.getAttribute("cacheUpdateTime") == null) + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > 300000) { + ChatCacheController.updateChatCache4Delete(context); + context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); + } + bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); + }else{ + bestMatch = new AnswerNextStep(0,state,"nextStep=error"); } - bestMatch.setAnswer(" \n"+return_str+"\n " + bestMatch.getAnswer()); ansJ = MyFunc.toJson(bestMatch); - //System.out.println(ansJ); + System.out.println(ansJ); out.write(ansJ.getBytes()); out.flush(); diff --git a/src/servlet/ReloadConfigServlet.java b/src/servlet/ReloadConfigServlet.java index 7c3e473..9a65b8c 100644 --- a/src/servlet/ReloadConfigServlet.java +++ b/src/servlet/ReloadConfigServlet.java @@ -12,13 +12,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; + +/** + * 发请求从本地文件夹重新加载某用户的配置文件 + */ @WebServlet(name = "ReloadConfigServlet",urlPatterns = {"/reload","/reload/"}) public class ReloadConfigServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); String userName = request.getParameter("userName"); boolean flag = true; UserInfo userinfo = new UserInfo(userName); File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt"); + System.out.println(configFile.getAbsolutePath()); ServletContext context = this.getServletContext(); if(!configFile.exists()) { response.setCharacterEncoding("utf-8"); @@ -47,6 +53,7 @@ public class ReloadConfigServlet extends HttpServlet { //request.setAttribute("returnMessage","更新失败,以下行有误:
" + errorStr +"
"+ "返回重新输入。"); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); + response.setStatus(111); PrintWriter out = response.getWriter(); out.println("更新失败配置文件有误:" + userName +".txt\\\n"); @@ -55,7 +62,7 @@ public class ReloadConfigServlet extends HttpServlet { response.setCharacterEncoding("utf-8"); response.setContentType( "text/plain"); PrintWriter out = response.getWriter(); - out.println("更新成功+ “ "); + out.println("重新加载成功"); out.flush(); out.close(); diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index e10265c..a2c57b4 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -24,7 +24,8 @@ import java.util.List; public class UpdateServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。 - String actionName,feature,line,element[],pair[],next[],cur_premises[],history_premises[],premises[]; + request.setCharacterEncoding("UTF-8"); + String line,extraElements[]; ArrayList errorList = new ArrayList(); ServletContext context = this.getServletContext(); String userName = request.getParameter("userName"); @@ -41,9 +42,18 @@ public class UpdateServlet extends HttpServlet { while((line = br.readLine()) != null){ + System.out.println(line); if(line.trim().equals("")) continue; + line = line.replace("\n",""); + //在用户信息中添加额外信息,如设为active的action + if(line.indexOf("-extraInfo-") != -1){ + extraElements = line.split("\\|"); + userinfo.extraInfo.put(extraElements[1],extraElements[2]); + userinfo.configStr += line+"\n"; + continue; + } //line = MyFunc.convert2Utf8(line.trim()); userinfo.configStr += line+"\n"; Condition condition = new Condition(); @@ -59,8 +69,6 @@ public class UpdateServlet extends HttpServlet { userinfo.conditionTable.put() } */ - - } catch(Exception e ){ System.out.println("配置文件有误!"); flag = false; @@ -82,6 +90,7 @@ public class UpdateServlet extends HttpServlet { out.println("---"+error); out.flush(); out.close(); + System.out.println("error"); } else{ @@ -91,12 +100,13 @@ public class UpdateServlet extends HttpServlet { out.println("更新成功+ “ "); out.flush(); out.close(); - + System.out.println("success"); //request.setAttribute("returnMessage","更新成功"+userinfo.configStr); context.setAttribute(userName,userinfo); String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt"; File file = new File(path); File dir = new File(System.getProperty("user.dir")+"/config"); + if(!dir.exists()) dir.mkdir(); if(!file.exists()){ @@ -110,7 +120,6 @@ public class UpdateServlet extends HttpServlet { } - //request.; } -- libgit2 0.27.1