Commit d175d8db by hxw

update code of generate action

parent dde940cb
#coding:utf8
import sys;
reload(sys);
from SQLHelper import *
sys.setdefaultencoding('utf8');
import pickle
class Action:
def __init__(self):
self.waiting_str = ""
self.listening_str = ""
self.http_str = "#actions\r\nname=pivot_httppost\r\naction=select\r\nstatus=waiting\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.sql_helper = SQLHelper()
def load_global_config(self,engine_config_file):
config = open(engine_config_file,'r')
for line in config:
if line.strip() == "":
continue
name,value = line.split("=")
self.CONFIG_DIC[name] = value.strip()
def save_action(self,parameters):
flag = 1
try:
userName = parameters["userName"]#.encode("utf-8")
conditionList = parameters["conditionList"]
for condition in conditionList:
conditionName = condition["conditionName"]#.encode("utf-8")
relation = condition["relation"]#.encode("utf-8")
question = condition["question"]#.encode("utf-8")
repeatList = condition["repeatList"]
active_flag = condition["active"]
for i in range(3):
self.insert_action_info(conditionName,active_flag,i)
self.insert_condition(conditionName,relation,question,repeatList,i)
self.insert_process(conditionName,repeatList,i)
except KeyError:
return 2
userFile = open(userName+".txt",'w')
userData = open(userName+".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()
user_id = self.sql_helper.query_userid_by_username(userName)
print user_id
if user_id != -1:
effect_row = self.sql_helper.update_action_text_by_userid(int(user_id),final_str)
if not effect_row:
flag = 3
else:
flag = 4
return flag
def reload_action(self,userName):
userFile = open(userName+'.data','r')
'''
actionList = []
action = {}
for line in userFile:
name = line.strip().split("=")[0]
if name == "" :
if action != {}:
actionList.append(action)
action = {}
else:
self.FUNC_MAP[name](line,action)
'''
data = pickle.load(userFile)
userFile.close()
return {"actionList":data}
def parse_name(self,text,action):
_,name = text.split("=")
action["actionName"] = name
def parse_status(self,text,action):
_,status = text.split("=")
action["status"] = status
def parse_conflict(self,text,action):
_,conflictStr = text.split("=")
conflictList = conflictStr.split(",")
action["conflictList"] = []
for conflict in conflictList:
action["conflictList"].append(conflict)
def parse_condition(self,text,action):
condition,relation,question,repeatStr = text.split("|")
_,conditionName = condition.split("=")
action["conditionName"] = conditionName
action["relation"] = relation
action["question"] = question
repeatList = repeatStr.split(",")
action["repeatList"] = []
for repeat in repeatList:
repeatDic = {}
re,keywords = repeat.split("=")
repeatDic["repeatString"] = re
repeatDic["repeatKeywords"] = keywords
action["repeatList"].append(repeatDic)
def parse_process(self,text,action):
processStr,nextAction,reply = text.split("|")
_,proName,keywords = processStr.split("=")
process = {}
if action["processList"] == None:
action["processList"] = []
process["processName"] = proName
process["processKeyWords"] = keywords
process["nextAction"] = nextAction
process["reply"] = reply
action["processList"].append(process)
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\n"
for key in self.ACTION_HEAD_INFO:
if(self.CONFIG_DIC[key] != ""):
self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n'
self.waiting_str += "fellow=pivot_httppost\r\n"
if flag == 1:
status = "active" if active_flag==True else "listening"
self.listening_str += "\r\n\r\nname=" + conditionName + "\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"
def insert_condition(self,conditionName,relation,question,repeatList,flag):
if not flag:
self.waiting_str += "condition="+conditionName+"|#visitorname,"+relation+",?|"+question+"|"
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+"|#visitorname,"+relation+",?|"+question+"|"
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+"|#visitorname,"+relation+",?|"+question+"|"
repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList]
reS = "~".join(repeat_str)
self.http_str += reS + "\r\n"
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"
elif flag == 1:
for repeat in repeatList:
self.listening_str += "process="+conditionName+"=+"+repeat["repeatKeywords"]+"|pivot_httppost=active|\r\n"
elif flag == 2:
self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n"
#coding:utf8
import requests
import json
from Action import *
import sys;
reload(sys);
sys.setdefaultencoding('utf8');
class BackgroundConfig():
'''
根据post的参数保存成配置文件的形式
'''
def __init__(self):
self.config_string = ""
self.CONFIG_DIC = {} #存储全局配置文件的信息
self.load_global_config("global_config.txt")
def load_global_config(self,engine_config_file):
config = open(engine_config_file,'r')
for line in config:
if line.strip() == "":
continue
name,value = line.split("=")
self.CONFIG_DIC[name] = value.strip()
def save_background_config(self,parameters):
flag = 1
try:
userName = parameters["userName"].strip()
configList = parameters["configList"]
for config in configList:
currentPremiseList = config["currentPremiseList"]
reply = config["reply"].strip() if config["reply"] != "" else " "
nextStep = config["nextStep"].strip()
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])
if historyPremiseList != [] and historyPremiseList[0]["keywords"] != "":
hisPreStr = ','.join([historyPremise["actionName"]+"="+historyPremise["keywords"] for historyPremise in historyPremiseList])
else:
hisPreStr = ""
if hisPreStr == "":
config_line = curPreStr + "| |"+"match|=>|"+reply+"|nextStep="+nextStep+'\n'
else:
config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n'
self.config_string += config_line
print self.config_string
except KeyError:
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}
ret= requests.post(url,data=payload)
if(ret.status_code == 200):
return 1
elif(ret.status_code == 111):
return 2
else:
return 4
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")
def query_userid_by_username(self,username):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "select id from users where username='%s'"%username
parameters = (username)
cur = conn.cursor()
cur.execute(sql)
#cur.execute(sql,username)
results = cur.fetchall()
conn.commit()
if len(results):
return results[0][0]
else :
return -1
except Exception as e:
raise e
finally:
cur.close()
conn.close()
def update_action_text_by_userid(self,userid,action_str):
try:
conn = pymysql.connect(**self.conn_dict)
sql = "update units set text = '%s' where name='actions' and user_id=%d"%(action_str,userid)
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
effect_row = cur.execute(sql)
conn.commit()
return effect_row
except Exception as e:
raise e
finally:
cur.close()
conn.close()
#coding:utf8
from flask import Flask
from flask import request
from flask import jsonify
from flask import make_response
from flask_cors import *
import json
from functools import wraps
from Action import *
from BackgroundConfig import *
import sys;
reload(sys);
sys.setdefaultencoding('utf8');
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/saveAction', methods=[ 'POST',"OPTIONS"])
def save_action():
if request.method == 'POST':
action = Action()
dc = json.loads(request.get_data().decode("utf8"))
flag = action.save_action(dc)
print flag
if flag == 1:
return "success"
elif flag == 2:
return "lack parameter"
elif flag == 3:
return "sql error"
elif flag == 4:
return "no such user"
elif request.method == "OPTIONS":
return "do it"
@app.route("/reloadAction", methods=["GET","POST"])
def reload_action():
if request.method == "POST":
action = Action()
dc = json.loads(request.get_data().decode("utf8"))
userName = dc["userName"]
return jsonify(action.reload_action(userName))
if request.method == "GET":
action = Action()
userName = request.values.get("userName")
return jsonify(action.reload_action(userName))
@app.route("/saveBackgroundConfig", methods=["POST","OPTIONS"])
def save_background_config():
if request.method == 'POST':
bg_config = BackgroundConfig()
parameters = json.loads(request.get_data().decode("utf8"))
flag = bg_config.save_background_config(parameters)
if flag == 1:
flag = bg_config.post_bg_config(parameters["userName"])
print flag
if flag == 1:
return "success"
elif flag == 2:
return "lack parameter"
elif flag == 3:
return "current information is empty"
elif flag == 4:
return "post fail"
elif request.method == "OPTIONS":
return "do it"
@app.route("/reloadBackgroundConfig",methods=["GET"])
def reload_action_config():
if request.method == "GET":
action = Action()
return jsonify(action.reload_action_config())
if __name__ == '__main__':
app.run(threaded=True,host="0.0.0.0",
port=1111,)
# coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import time
from locust import HttpLocust,TaskSet,task
import json
class UserBehavior(TaskSet):
def on_start(self):
pass
'''
@task(1)
def index2(self):
data = {"userName":"hxw2303632"
,"conditionList":[ {"conditionName":u"xihuan","relation":u"relation-find-xihuan","question":u"你玩多久了?",
"repeatList":[{"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":u"+dota+王者荣耀"}, {"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":u"+手游+休闲游戏+你管我"}]
},
{"conditionName":u"buxihuan","relation":u"relation-find-buxihuan","question":u"你管我玩多久了?",
"repeatList":[{"repeatString":u"#visitorname不喜欢玩[]",u"repeatKeywords":str(time.time())}]
}
]}
self.client.post('/saveAction',data=None,json=data)
'''
@task(1)
def index(self):
data = {"userName":"hxw","configList":[
{"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}],
"historyPremiseList":[{"actionName":"","keywords":""}] },
{"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}],
"historyPremiseList":[{"actionName":"","keywords":""}]
}
]}
self.client.post('/saveBackgroundConfig',data=None,json=data)
class WebsiteUser(HttpLocust):
task_set = UserBehavior
host = "http://192.168.1.178:1111"
min_wait = 1000
max_wait = 1000
#coding:utf-8
from flask import Flask
from flask import request
from flask import jsonify
import json
app = Flask(__name__)
@app.route('/test', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
dc = json.loads(request.get_data().decode("utf8"))
if(dc.has_key("curInfoPoint")):
return jsonify({"parameter":"捷豹"})
else:
return jsonify(dc)
else:
return "incorrect method,use POST instead!"
if __name__ == '__main__':
app.run(host="0.0.0.0",
port=8888,)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment