Commit a0a9bad4 by hxw

修改qa

parent 864ec864
...@@ -40,6 +40,13 @@ public class GlobalVariableConstructor extends ElementConstructor { ...@@ -40,6 +40,13 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put(attrName, attrValue); varInitialMap.put(attrName, attrValue);
} }
} }
JSONObject script = gameElements.getJSONObject("speechcraft");
for(String key:script.keySet()){
attrValue = (String)script.get(key);
varInitialMap.put(key, attrValue);
}
}catch (Exception e){ }catch (Exception e){
operationStatus = 0; operationStatus = 0;
message = "全局变量处理出现异常"; message = "全局变量处理出现异常";
......
...@@ -14,6 +14,8 @@ import java.util.*; ...@@ -14,6 +14,8 @@ import java.util.*;
public class PlotConstructor extends ElementConstructor { public class PlotConstructor extends ElementConstructor {
String GAME_STEP_FORMAT = "%s_plot_%s";
JSONArray plots = null; JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
...@@ -49,7 +51,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -49,7 +51,7 @@ public class PlotConstructor extends ElementConstructor {
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put("unknownText", "你说啥?"); varInitialMap.put("unknownText", "你说啥?");
varInitialMap.put("game_step", (String) id2j.get(start).get("id")); varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id")));
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
conditionDescription.put("game_step", "QA问答游戏进度"); conditionDescription.put("game_step", "QA问答游戏进度");
...@@ -114,7 +116,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -114,7 +116,7 @@ public class PlotConstructor extends ElementConstructor {
*/ */
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName = "yaobuyao", String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName = "yaobuyao",
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
boolean newBranch, manyParent; boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null; JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null; JSONArray branch = null;
...@@ -132,7 +134,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -132,7 +134,7 @@ public class PlotConstructor extends ElementConstructor {
conditionName = (String)root.get("conditionName"); conditionName = (String)root.get("conditionName");
String startPlace = (String)root.get("place"); String startPlace = ((String)root.get("place")).split("\\+")[0];
varInitialMap.put("site", startPlace); varInitialMap.put("site", startPlace);
varInitialMap.put("任务线" + startPlace + "最后一个condition", ""); varInitialMap.put("任务线" + startPlace + "最后一个condition", "");
varInitialMap.put("任务线" + startPlace + "最后的回答", ""); varInitialMap.put("任务线" + startPlace + "最后的回答", "");
...@@ -143,15 +145,17 @@ public class PlotConstructor extends ElementConstructor { ...@@ -143,15 +145,17 @@ public class PlotConstructor extends ElementConstructor {
//用于开始游戏的配置 //用于开始游戏的配置
jConfig = new JConfig( jConfig = new JConfig(
"start_options::match-Include=+开始+开始游戏+继续游戏+继续", "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始",
"任务线" + startPlace + "最后一个condition::match-Include=+null", "任务线" + startPlace + "最后一个condition::match-Include=+null",
"match", "match",
(String)jsonObject.get("plotStartText"), (String)jsonObject.get("plotStartText"),
conditionName, conditionName,
"任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" +
"-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(taskLine, root.get("place")) + ":" + root.get("id") "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(taskLine, startPlace) + ":" + root.get("id")
); );
jConfig.setAuxiliaryPriority("1");
jConfigList.add(jConfig); jConfigList.add(jConfig);
jConfig = new JConfig( jConfig = new JConfig(
" ", " ",
"任务线" + startPlace + "最后一个condition::match-Include=+null", "任务线" + startPlace + "最后一个condition::match-Include=+null",
...@@ -160,6 +164,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -160,6 +164,7 @@ public class PlotConstructor extends ElementConstructor {
"start_options", "start_options",
"" ""
); );
jConfig.setAuxiliaryPriority("1");
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -172,7 +177,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -172,7 +177,7 @@ public class PlotConstructor extends ElementConstructor {
node = queue.remove(); node = queue.remove();
id = (String) node.get("id"); id = (String) node.get("id");
parentId = (String) node.get("parentId"); parentId = (String) node.get("parentId");
location = (String) node.get("place"); location = ((String) node.get("place")).split("\\+")[0];
conditionName = (String) node.get("conditionName"); conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText"); curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度"; taskLineName = "任务线_" + location + "进度";
...@@ -207,6 +212,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -207,6 +212,7 @@ public class PlotConstructor extends ElementConstructor {
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
nextId = (String) branchNode.get("nextPlotId"); nextId = (String) branchNode.get("nextPlotId");
reply = (String)branchNode.get("reply");
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
if(updateKnowledge.containsKey("unkonwnText")) if(updateKnowledge.containsKey("unkonwnText"))
nextUnknownText = updateKnowledge.get("unknownText"); nextUnknownText = updateKnowledge.get("unknownText");
...@@ -219,13 +225,15 @@ public class PlotConstructor extends ElementConstructor { ...@@ -219,13 +225,15 @@ public class PlotConstructor extends ElementConstructor {
nextCondition = (String) id2j.get(nextId).get("conditionName"); nextCondition = (String) id2j.get(nextId).get("conditionName");
if(nextCondition.equals("")) if(nextCondition.equals(""))
nextCondition = "yaobuyao"; nextCondition = "yaobuyao";
nextLocation = (String) id2j.get(nextId).get("place"); nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0];
nTaskLineName = "任务线_" + nextLocation + "进度"; nTaskLineName = "任务线_" + nextLocation + "进度";
} else { } else {
//如果不存在下一剧情,就将condition设为空,任务线进度不变 //如果不存在下一剧情,就将condition设为空,任务线进度不变
nTaskLineName = taskLineName; nTaskLineName = taskLineName;
nextLocation = location; nextLocation = location;
nextCondition = "yaobuyao"; nextCondition = "yaobuyao";
continue;
} }
lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; lastTaskCondition = "任务线" + nextLocation + "最后一个condition";
...@@ -235,8 +243,18 @@ public class PlotConstructor extends ElementConstructor { ...@@ -235,8 +243,18 @@ public class PlotConstructor extends ElementConstructor {
//额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null";
extraUK = nTaskLineName + ":" + nextId + "-<-site:" + nextLocation + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":var={reply-3}" + extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-game_step:" + botAccount + "_plot_" + nextId; "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId);
if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) {
extraUK += "-<-site:" + nextLocation;
}else {
if(!location.equals(nextLocation)){
//如果当前地点和下一步剧情地点不同,要提示
reply = "请到" + nextLocation + "开始下一步剧情";
}
}
List<String> curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); List<String> curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class);
...@@ -246,15 +264,21 @@ public class PlotConstructor extends ElementConstructor { ...@@ -246,15 +264,21 @@ public class PlotConstructor extends ElementConstructor {
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
updateKnowledge, updateKnowledge,
"", extraHP, extraUK, "", extraHP, extraUK,
"match", (String) branchNode.get("reply"), (String) nextCondition, "0" "match", reply, (String) nextCondition, "0"
); );
if (curPremiseList.size() == 0){ if (curPremiseList.size() == 0){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::all(http://simqa.sz.chewrobot.com:28081/game)"); jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(http://simqa.sz.chewrobot.com:28081/game)");
jConfig.setNextStep("queryskip1,queryskip2,queryskip3"); jConfig.setNextStep("queryskip1,queryskip2,queryskip3");
jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量1:"+ nextCondition +"-<-临时变量2:var={reply-3}"); jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量1:"+ nextCondition +"-<-临时变量2:var={reply-3}");
jConfig.setNextStepStatus("active"); jConfig.setNextStepStatus("active");
} }
jConfigList.add(jConfig); jConfigList.add(jConfig);
...@@ -284,7 +308,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -284,7 +308,7 @@ public class PlotConstructor extends ElementConstructor {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=unknown", conditionName + "::match-Include=unknown",
"任务线_" + location + "进度::match-Include=" + parentId, "任务线_" + location + "进度::match-Include=" + parentId,
"match,return-0,post::all(" + CHITCHAT_URL + ")", "match,return-0,post::gameQA(" + CHITCHAT_URL + ")",
" ", " ",
" ", " ",
"" ""
...@@ -401,7 +425,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -401,7 +425,7 @@ public class PlotConstructor extends ElementConstructor {
@Override @Override
public void postProcessing(List<Integer> idList, int categoryId){ public void postProcessing(List<Integer> idList, int categoryId){
if (idList.size() != 0) { if (idList.size() != 0) {
jConfig = new JConfig(" ", " ", "activate,post::all(http://simqa.sz.chewrobot.com:28081/game)", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); jConfig = new JConfig(" ", " ", "activate,post::gameQA(http://simqa.sz.chewrobot.com:28081/game)", "", "unknown4,unknown3,unknown2,unknown1,common_answer", "");
jConfig.setNextStepStatus("active"); jConfig.setNextStepStatus("active");
JSONObject json = jConfig.toJson(this.getConditionDescription()); JSONObject json = jConfig.toJson(this.getConditionDescription());
helper.insertConfigByBotId(botId, json, idList, categoryId); helper.insertConfigByBotId(botId, json, idList, categoryId);
......
...@@ -14,6 +14,7 @@ import java.sql.SQLException; ...@@ -14,6 +14,7 @@ import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -188,14 +189,44 @@ public class ChatCacheController { ...@@ -188,14 +189,44 @@ public class ChatCacheController {
try { try {
chatCache = chatCacheMap.get(chatKey); chatCache = chatCacheMap.get(chatKey);
HashSet<String> startKeySet = new HashSet<String>(){
{
add("开始");
add("开始剧情");
add("继续");
add("继续剧情");
}
};
HashSet<String> restartKeySet = new HashSet<String>(){
{
add("重新开始");
}
};
if(chatCache == null){ if(chatCache == null){
if(receiveParamters.containsKey("start_options") && (receiveParamters.get("start_options")[0].contains("开始游戏") || if(receiveParamters.containsKey("start_options")){
receiveParamters.get("start_options")[0].contains("继续游戏")|| receiveParamters.get("start_options")[0].contains("继续"))) { String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1];
if(startKeySet.contains(startKeyword)) {
chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus); chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus);
}else { }else {
chatCache = new ChatCache(userinfo); chatCache = new ChatCache(userinfo);
} }
}else {
chatCache = new ChatCache(userinfo);
}
chatCacheMap.put(chatKey, chatCache); chatCacheMap.put(chatKey, chatCache);
} else {
chatCache.setReloading(false);
if(receiveParamters.containsKey("start_options")){
String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1];
if(startKeySet.contains(startKeyword)) {
chatCache.setReloading(true);
}else if(restartKeySet.contains(startKeyword)){
chatCache = new ChatCache(userinfo);
}
}
} }
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName); //historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) { } catch (Exception e) {
......
package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.message.BasicNameValuePair;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FormsPoster {
LogWriter logWriter = null;
public FormsPoster(LogWriter logWriter) {
this.logWriter = logWriter;
}
HashSet<String> skipSet = new HashSet<String>() {
{
add("activeList");
add("currentAction");
add("lastUpdateTime");
add("lastReply");
}
};
static String TALKER = "^【(.*?)】";
/**
* 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器
* @param curInfoPoint
* @param historyInfoPoint
* @param ans
* @param URL
* @throws UnsupportedEncodingException
*/
public void postAll(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans, String URL) throws UnsupportedEncodingException {
String key, keyName;
Iterator<String> k_iter = null;
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
k_iter = curInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (curInfoPoint.get(key) != "")
//infoMap.put(key + "_cur", curInfoPoint.get(key)[0]);
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
}
k_iter = historyInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (historyInfoPoint.get(key) != "")
//infoMap.put(key + "_his", historyInfoPoint.get(key));
if (key.equals("game_step"))
pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key)));
else if(skipSet.contains(key)){}
else
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
}
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator();
while (kit.hasNext()) {
keyName = kit.next();
if (keyName.equals("process")) {
ans.setNext((String) jobj.get(keyName));
historyInfoPoint.put("process", (String) jobj.get(keyName));
} else if (keyName.equals("solution")) {
ans.setAnswer((String) jobj.get(keyName));
} else if (keyName.equals("status")){
continue;
} else{
historyInfoPoint.put(keyName, jobj.getString(keyName));
}
}
}else {
ans.setAnswer("提交表单出现异常");
}
}
/**
* 提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值
* @param curInfoPoint
* @param historyInfoPoint
* @param ans
* @param ansCondition
* @param URL
* @throws UnsupportedEncodingException
*/
public void postTerm(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans, Condition ansCondition, String URL) throws UnsupportedEncodingException {
String key, keyName;
Iterator<String> k_iter = null;
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
k_iter = ansCondition.currentPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
}
k_iter = ansCondition.historyPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (historyInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
//infoMap.put(key + "_his", historyInfoPoint.get(key));
}
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator();
while (kit.hasNext()) {
keyName = kit.next();
if (keyName.equals("process")) {
ans.setNext((String) jobj.get(keyName));
historyInfoPoint.put("process", (String) jobj.get(keyName));
} else if (keyName.equals("solution")) {
ans.setAnswer((String) jobj.get(keyName));
} else if (keyName.equals("status")){
continue;
} else{
historyInfoPoint.put(keyName, jobj.getString(keyName));
}
}
}else {
ans.setAnswer("提交表单出现异常");
}
}
/**
* 游戏专用提交表单
* @param curInfoPoint
* @param historyInfoPoint
* @param ans
* @param gameEnv
* @param worldController
* @param URL
* @throws UnsupportedEncodingException
*/
public void postGameQA(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL) throws UnsupportedEncodingException {
String key, keyName;
Iterator<String> k_iter = null;
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
String threshold = "0.9";
if (historyInfoPoint.get("qa_threshold") != null)
threshold = historyInfoPoint.get("qa_threshold");
pairList.add(new BasicNameValuePair("game_step", historyInfoPoint.get("game_step")));
pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text")));
pairList.add(new BasicNameValuePair("qa_threshold", threshold));
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
String text,score, site = historyInfoPoint.get("site"), npc;
if((Integer)jobj.get("post_status") == 1){
if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){
historyInfoPoint.put("common_answer", "未找到匹配");
historyInfoPoint.put("qa_score", "0");
List<JSONArray> candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class);
for(JSONArray pair:candidates){
List<String> textscore = JSON.toJavaObject(pair, List.class);
Pattern findTalker = Pattern.compile(TALKER);
Matcher m = findTalker.matcher(textscore.get(0));
if(m.find()) {
npc = m.group(1);
if (worldController.worldOperation(gameEnv, "NPC_query", "queryLocationByNPCName:", curInfoPoint, historyInfoPoint).equals(site)){
historyInfoPoint.put("common_answer", textscore.get(0));
historyInfoPoint.put("qa_score", textscore.get(1));
break;
}
}
}
}else{
historyInfoPoint.put("common_answer", (String)jobj.get("common_answer"));
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", (String)jobj.get("qa_status"));
}
}else {
ans.setAnswer("提交表单出现异常");
}
}
}
...@@ -21,6 +21,9 @@ import java.text.ParseException; ...@@ -21,6 +21,9 @@ import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.processing.QuestionMatcher.API_ERROR;
import static com.qiwu.chatbotbackend.processing.QuestionMatcher.POST_ERROR;
public class MyFunc { public class MyFunc {
...@@ -107,7 +110,7 @@ public class MyFunc { ...@@ -107,7 +110,7 @@ public class MyFunc {
return true; return true;
} }
public static JSONObject postJSON(String url, JSONObject data) throws UnsupportedEncodingException { public static JSONObject postJSON(String url, JSONObject data, String auth) throws UnsupportedEncodingException {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
...@@ -125,16 +128,21 @@ public class MyFunc { ...@@ -125,16 +128,21 @@ public class MyFunc {
entity.setContentType("application/json; charset=utf-8"); entity.setContentType("application/json; charset=utf-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
if(auth != null){
httpPost.setHeader("Authorization", auth);
}
try { try {
HttpResponse resp = client.execute(httpPost); HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) { if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity(); HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8"); respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent); jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else { } else {
jobj.put("status", 0); jobj.put("post_status", 0);
jobj.put("parameter", "修改condition失败"); jobj.put("parameter", "接收请求的程序出现异常");
} }
} catch (Exception e) { } catch (Exception e) {
...@@ -146,4 +154,42 @@ public class MyFunc { ...@@ -146,4 +154,42 @@ public class MyFunc {
} }
public static JSONObject postFORM(String url, List<BasicNameValuePair> pairList) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
JSONObject jobj = new JSONObject();
try {
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else {
jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常");
}
} catch (Exception e) {
e.printStackTrace();
}
return jobj;
}
} }
\ No newline at end of file
...@@ -50,7 +50,7 @@ public class QuestionMatcher { ...@@ -50,7 +50,7 @@ public class QuestionMatcher {
this.userinfo = userinfo; this.userinfo = userinfo;
this.context = context; this.context = context;
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
this.worldController = new WorldController(logWriter); this.worldController = new WorldController(logWriter, userinfo);
} }
/** /**
...@@ -145,6 +145,8 @@ public class QuestionMatcher { ...@@ -145,6 +145,8 @@ public class QuestionMatcher {
curInfoPoint.put(currentAction, i); curInfoPoint.put(currentAction, i);
} }
logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1);
return debugFlag; return debugFlag;
} }
...@@ -921,6 +923,7 @@ public class QuestionMatcher { ...@@ -921,6 +923,7 @@ public class QuestionMatcher {
Map<String, String> infoMap = new HashMap<String, String>(); Map<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
Iterator<String> k_iter = null; Iterator<String> k_iter = null;
FormsPoster poster = new FormsPoster(logWriter);
HashSet<String> skipSet = new HashSet<String>() { HashSet<String> skipSet = new HashSet<String>() {
{ {
...@@ -935,91 +938,99 @@ public class QuestionMatcher { ...@@ -935,91 +938,99 @@ public class QuestionMatcher {
url = elem[0]; url = elem[0];
postType = elem[1]; postType = elem[1];
//提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器
if (postType.equals("all")) {
k_iter = curInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (curInfoPoint.get(key) != "")
//infoMap.put(key + "_cur", curInfoPoint.get(key)[0]);
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
}
k_iter = historyInfoPoint.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next();
if (historyInfoPoint.get(key) != "")
//infoMap.put(key + "_his", historyInfoPoint.get(key));
if (key.equals("game_step"))
pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key)));
else if(skipSet.contains(key)){}
else
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
}
//提交类型为term时只会提交最佳匹配的配置条目中包含的条件和值
} else if (postType.equals("term")) {
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
k_iter = ansCondition.currentPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
}
k_iter = ansCondition.historyPremise.keySet().iterator();
while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0];
if (historyInfoPoint.get(key) != "")
pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
//infoMap.put(key + "_his", historyInfoPoint.get(key));
}
}
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); // if (postType.equals("all")) {
entity.setContentType("application/x-www-form-urlencoded"); // k_iter = curInfoPoint.keySet().iterator();
httpPost.setEntity(entity); // while (k_iter.hasNext()) {
// key = k_iter.next();
try { // if (curInfoPoint.get(key) != "")
HttpResponse resp = client.execute(httpPost); // //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]);
if (resp.getStatusLine().getStatusCode() == 200) { // pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
HttpEntity he = resp.getEntity(); // }
respContent = EntityUtils.toString(he, "UTF-8"); //
logWriter.record("提交表单接收到的数据:<br>" + respContent, 2); // k_iter = historyInfoPoint.keySet().iterator();
JSONObject jobj = JSONObject.parseObject(respContent); // while (k_iter.hasNext()) {
Iterator<String> kit = jobj.keySet().iterator(); // key = k_iter.next();
// if (historyInfoPoint.get(key) != "")
while (kit.hasNext()) { // //infoMap.put(key + "_his", historyInfoPoint.get(key));
keyName = kit.next(); // if (key.equals("game_step"))
if (keyName.equals("process")) { // pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key)));
ans.setNext((String) jobj.get(keyName)); // else if(skipSet.contains(key)){}
historyInfoPoint.put("process", (String) jobj.get(keyName)); // else
} else if (keyName.equals("solution")) { // pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
ans.setAnswer((String) jobj.get(keyName)); // }
} else if (keyName.equals("status")){ //
continue;
} else{ // } else if (postType.equals("term")) {
historyInfoPoint.put(keyName, jobj.getString(keyName)); // pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
} // pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
} // pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
} else { // k_iter = ansCondition.currentPremise.keySet().iterator();
ans.setAnswer(API_ERROR); // while (k_iter.hasNext()) {
} // key = k_iter.next().split("::")[0];
} catch (Exception e) { // if (curInfoPoint.get(key) != "")
e.printStackTrace(); // pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
// }
ans.setAnswer(POST_ERROR + url); //
return ans; // k_iter = ansCondition.historyPremise.keySet().iterator();
// while (k_iter.hasNext()) {
// key = k_iter.next().split("::")[0];
// if (historyInfoPoint.get(key) != "")
// pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key)));
// //infoMap.put(key + "_his", historyInfoPoint.get(key));
// }
// }
//
// logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
//
// HttpPost httpPost = new HttpPost(url);
// CloseableHttpClient client = HttpClients.createDefault();
// String respContent = null;
// String keyName = null;
//
//
// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
// entity.setContentType("application/x-www-form-urlencoded");
// httpPost.setEntity(entity);
//
// try {
// HttpResponse resp = client.execute(httpPost);
// if (resp.getStatusLine().getStatusCode() == 200) {
// HttpEntity he = resp.getEntity();
// respContent = EntityUtils.toString(he, "UTF-8");
// logWriter.record("提交表单接收到的数据:<br>" + respContent, 2);
// JSONObject jobj = JSONObject.parseObject(respContent);
// Iterator<String> kit = jobj.keySet().iterator();
//
// while (kit.hasNext()) {
// keyName = kit.next();
// if (keyName.equals("process")) {
// ans.setNext((String) jobj.get(keyName));
// historyInfoPoint.put("process", (String) jobj.get(keyName));
// } else if (keyName.equals("solution")) {
// ans.setAnswer((String) jobj.get(keyName));
// } else if (keyName.equals("status")){
// continue;
// } else{
// historyInfoPoint.put(keyName, jobj.getString(keyName));
// }
// }
// } else {
// ans.setAnswer(API_ERROR);
// }
// } catch (Exception e) {
// e.printStackTrace();
//
// ans.setAnswer(POST_ERROR + url);
// return ans;
// }
if(postType.equals("all")){
poster.postAll(curInfoPoint, historyInfoPoint, ans, url);
}else if(postType.equals("term")){
poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansCondition, url);
}else if(postType.equals("gameQA")){
poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url);
} }
return ans; return ans;
......
...@@ -39,6 +39,14 @@ public class GameDesignServlet extends HttpServlet { ...@@ -39,6 +39,14 @@ public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration<String> enum1 = request.getHeaderNames();
while(enum1.hasMoreElements()) {
System.out.println(enum1.nextElement());
}
//所有需要修改的词性 //所有需要修改的词性
StringBuffer POS = new StringBuffer(); StringBuffer POS = new StringBuffer();
...@@ -75,6 +83,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -75,6 +83,7 @@ public class GameDesignServlet extends HttpServlet {
JSONObject gameElements = helper.queryGameElementsByBotId(dataId); JSONObject gameElements = helper.queryGameElementsByBotId(dataId);
gameElements.put("auth", request.getHeader("authorization"));
System.out.println(gameElements.toJSONString()); System.out.println(gameElements.toJSONString());
botId = (Integer)gameElements.get("botId"); botId = (Integer)gameElements.get("botId");
botAccount = (String) gameElements.get("botAccount"); botAccount = (String) gameElements.get("botAccount");
...@@ -82,7 +91,6 @@ public class GameDesignServlet extends HttpServlet { ...@@ -82,7 +91,6 @@ public class GameDesignServlet extends HttpServlet {
System.out.println("botId:" + botId + ",botAccount:" + botAccount);
//假设重建用户信息 //假设重建用户信息
if (context.getAttribute(botAccount) == null) { if (context.getAttribute(botAccount) == null) {
...@@ -243,8 +251,9 @@ public class GameDesignServlet extends HttpServlet { ...@@ -243,8 +251,9 @@ public class GameDesignServlet extends HttpServlet {
actionPostData.put("botName", botName); actionPostData.put("botName", botName);
actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("botId", (Integer)gameElements.get("botId"));
actionPostData.put("type", "game_plot_init"); actionPostData.put("type", "game_plot_init");
actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始游戏或者继续游戏"); actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始剧情或者重新开始");
actionPostData.put("relationKeywords", relationKeywords); actionPostData.put("relationKeywords", relationKeywords);
actionPostData.put("auth", gameElements.get("auth"));
if (gameElements.containsKey("POS")) if (gameElements.containsKey("POS"))
...@@ -257,7 +266,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -257,7 +266,7 @@ public class GameDesignServlet extends HttpServlet {
userInfo.extraInfo.put("activeAction", startCondition); userInfo.extraInfo.put("activeAction", startCondition);
try { try {
returnMessage = MyFunc.postJSON(POST_URL, actionPostData); returnMessage = MyFunc.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -35,7 +35,10 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -35,7 +35,10 @@ public class GetAnswerServlet extends HttpServlet {
String ansJ = "", return_str = "", state = "", chatKey = ""; String ansJ = "", return_str = "", state = "", chatKey = "";
String botName = receiveParamters.get("bot_name")[0]; String botName = receiveParamters.get("bot_name")[0];
chatKey = receiveParamters.get("chat_key")[0].split("@")[0]; if(!receiveParamters.get("chat_key")[0].startsWith("@"))
chatKey = receiveParamters.get("chat_key")[0].split("@")[0];
else
chatKey = receiveParamters.get("chat_key")[0];
receiveParamters.get("chat_key")[0] = chatKey; receiveParamters.get("chat_key")[0] = chatKey;
OutputStream out = response.getOutputStream(); OutputStream out = response.getOutputStream();
......
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