Commit f8b3597c by 苗权威

11.22

parent fc461663
......@@ -68,7 +68,7 @@ public class OkHttp3Utils {
* @return json信息
* @throws IOException
*/
private static String doGet(String url, Map<String, String> params, Map<String, String> header) throws IOException {
public static String doGet(String url, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
HttpUrl.Builder urlBuild = request.url().newBuilder();
......
......@@ -4,6 +4,7 @@ import ai.qiwu.com.tts_service.common.TTSUtils;
import ai.qiwu.com.tts_service.pojo.*;
import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.LieHuSchedule;
import ai.qiwu.com.tts_service.service.TTService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
......@@ -35,9 +36,12 @@ public class TTSController {
*/
private final TTService ttService;
private final LieHuSchedule lieHuSchedule;
@Autowired
public TTSController(TTService ttService) {
public TTSController(TTService ttService, LieHuSchedule lieHuSchedule) {
this.ttService = ttService;
this.lieHuSchedule = lieHuSchedule;
}
/**
......@@ -219,4 +223,9 @@ public class TTSController {
ttService.offlineCallback(file, response);
}
@GetMapping("/api/update/Liehu")
public void updateToken(String secret) {
if ("miao".equals(secret)) lieHuSchedule.scheduleLieHuToken();
}
}
......@@ -21,18 +21,29 @@ import java.util.HashMap;
public class LieHuSchedule {
private static final HashMap<String, String> LIE_HU_TOKEN_PARAMS;
// private static final HashMap<String, String> LIE_HU_TOKEN_HEADER;
private static String LIE_HU_TOKEN;
static {
LIE_HU_TOKEN_PARAMS = new HashMap<>();
// LIE_HU_TOKEN_HEADER = new HashMap<>();
LIE_HU_TOKEN_PARAMS.put("client_id", TTSConstants.LIE_HU.CLIENT_ID);
LIE_HU_TOKEN_PARAMS.put("client_secret", TTSConstants.LIE_HU.CLIENT_SECRET);
// LIE_HU_TOKEN_HEADER.put("Access-Control-Allow-Origin", "*");
// LIE_HU_TOKEN_HEADER.put("Content-Length", "215");
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
@Scheduled(fixedDelay = 6600000)
public void scheduleLieHuToken() {
new Thread(() -> {
int count = 0;
boolean success = false;
do {
try {
// String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS,
// LIE_HU_TOKEN_HEADER);
String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS);
if (StringUtils.isBlank(liehuTokenRes)) {
log.error("对猎户Token发起的请求出错");
......@@ -40,14 +51,23 @@ public class LieHuSchedule {
}
LieHuTokenResponse response = JSON.parseObject(liehuTokenRes, LieHuTokenResponse.class);
if ("success".equals(response.getCode())) {
success = true;
LIE_HU_TOKEN = response.getToken();
return;
//log.info("成功获取到猎户Token:{}", LIE_HU_TOKEN);
}else {
log.error("请求猎户Token失败:{}", response.getError());
log.error("第次{}尝试请求猎户Token失败:{}", count+1,response.getError());
}
} catch (Exception e) {
log.error("第次{}尝试获取猎户Token异常:{},", count+1,e.toString());
}
count++;
try {
Thread.sleep(2*count);
} catch (Exception e) {
log.error("获取猎户Token失败:{}", e.toString());
}
} while (!success && count < 10);
}).start();
}
......
......@@ -254,13 +254,15 @@ public class Test {
}
public static void main(String[] args) throws IOException, ParseException {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71");
System.out.println(Arrays.toString(arrr));
Date date = new Date(1572522571234L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(date));
List<String> paths = new ArrayList<>();
for (int i = 1; i < 6; i++) {
paths.add("/home/yf01/下载/tts/"+i+".mp3");
}
System.out.println(URLDecoder.decode("http://didi-gz4.jiaoyou365.com:9663/api/tts/get_audio?dirs=%5B39474830%2Crecord%2C%E6%9E%97%E8%80%81%E5%B8%88%5D&filename=2693006153fb900642c931d9304e650a.mp3"));
System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :黄河入海流。 当前体力值为"));
System.out.println(TTSUtils.buildMP3Filename("98"));
System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :疑是地上霜。 当前体力值为 "));
}
}
......@@ -107,6 +107,8 @@ public class ThirdPartyService {
HashMap<String, String> headers = new HashMap<>();
//headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", TTSConstants.LIE_HU.AUTHORIZATION+LieHuSchedule.getLieHuToken());
// headers.put("Access-Control-Allow-Origin", "*");
// headers.put("Content-Type", "application/json");
HashMap<String, String> params = new HashMap<>();
params.put("tex", text);
params.put("sn", new StringBuilder(RandomStringUtils.randomAlphabetic(5)).append(System.currentTimeMillis()).toString());
......
......@@ -111,6 +111,7 @@ public interface Constants {
interface ErrorMsg {
String SORRY_UNCATCH = "不好意思我没听清,请再说一遍吧";
String TERMINATE_RETURN_EMPTY = "中控返回了空的链接";
String INTERNAL_ERROR = "其他DuerOS系统错误";
String INVALID_RESPONSE = "技能返回了无效的响应,可能技能响应数据量超过24KB,或是技能在request的dialogState为COMPLETED时仍然发送Dialog.Delegate指令等";
String DEVICE_COMMUNICATION_ERROR = "DuerOS与端通信异常";
......
......@@ -50,7 +50,7 @@ public class XiaoDuHomeController {
try {
//log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest());
log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
......
......@@ -16,6 +16,8 @@ import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
import ai.qiwu.com.xiaoduhome.pojo.*;
import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.data.request.IntentRequest;
......@@ -44,6 +46,7 @@ import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Response;
import com.baidu.dueros.nlu.Intent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.domain.Example;
......@@ -67,6 +70,8 @@ import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.ERROR_SEND_FLO
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.FAIL_COLLECT;
import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.*;
import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK;
import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.OUTTIME_TYPE_0;
/**
* @author 苗权威
......@@ -82,7 +87,6 @@ public class DplBotService extends BaseBot {
// private static final ThreadLocal<Integer> CACHE_THREAD_INDEX = new ThreadLocal<>();
// private static final ThreadLocal<>
// 用来处理短时间内的多次请求
private static final ConcurrentHashMap<String, List<IntentRequest>> CACHE_XIAODU_REQUEST = new ConcurrentHashMap<>();
......@@ -100,6 +104,8 @@ public class DplBotService extends BaseBot {
@Override
public Response onLaunch(LaunchRequest launchRequest) {
if (getRequest().getContext().getScreen() == null) {
LAST_OUTTIME_MARK.remove(getDeviceId());
LAST_OUTTIME_RESULT.remove(getDeviceId());
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.WELCOME);
return new Response(outputSpeech);
}
......@@ -123,7 +129,16 @@ public class DplBotService extends BaseBot {
final String userId = getUserId();
if (getRequest().getContext().getScreen() == null) {
final String deviceUserId = getDeviceId();
OverTimeDetail lastData = LAST_OUTTIME_RESULT.remove(deviceUserId);
Byte overTimeType;
if ((overTimeType = LAST_OUTTIME_MARK.get(deviceUserId)) != null) {
try {
//log.info("开始等待");
Thread.sleep(2000);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
}
OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(deviceUserId);
if (lastData != null) {
for (Directive directive : lastData.getDirectives()) {
//log.info("上次超时保存的Directive:{}",directive.getClass().getName());
......@@ -133,9 +148,17 @@ public class DplBotService extends BaseBot {
//log.info("上次超时保存的key:{}",key);
this.setSessionAttribute(key, lastData.getAttributes().get(key));
}
LAST_OUTTIME_MARK.remove(deviceUserId);
LAST_OUTTIME_RESULT.remove(deviceUserId);
return lastData.getResponse();
}
else {
if (overTimeType != 3) {
LAST_OUTTIME_MARK.put(deviceUserId, (byte) (overTimeType+1));
return buildErrorResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2);
}
LAST_OUTTIME_MARK.remove(deviceUserId);
}
try {
Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntent(intentRequest, deviceUserId));
future.get(2500, TimeUnit.MILLISECONDS);
......@@ -144,13 +167,15 @@ public class DplBotService extends BaseBot {
return buildErrorResponse(SORRY_UNCATCH);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
LAST_OUTTIME_MARK.put(deviceUserId, OUTTIME_TYPE_0);
return buildErrorResponse(SORRY_UNCATCH);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH);
}
return LAST_OUTTIME_RESULT.remove(deviceUserId).getResponse();
}
OverTimeDetail detail;
if ((detail = LAST_OUTTIME_RESULT.remove(deviceUserId)) != null) return detail.getResponse();
return new Response();
}
OverTimeDetail detail;
if ((detail = LAST_OUTTIME_RESULT.remove(userId)) != null) {
......@@ -183,7 +208,9 @@ public class DplBotService extends BaseBot {
log.error("任务执行发生了错误:{}", ExceptionUtils.getStackTrace(all));
return buildErrorResponse(SORRY_UNCATCH);
}
return LAST_OUTTIME_RESULT.remove(getUserId()).getResponse();
OverTimeDetail data = LAST_OUTTIME_RESULT.remove(getUserId());
if (data == null) return new Response();
return data.getResponse();
}
private void dealNoScreenIntent(IntentRequest intentRequest, String userId) {
......@@ -224,10 +251,9 @@ public class DplBotService extends BaseBot {
// log.warn("小度重复现象出现:{},requestId:{}",intentRequest.getQuery().getOriginal(), intentRequest.getRequestId());
log.warn("小度重复现象出现:{},",getStrRequest());
synchronized (requestList) {
requestList.wait(5000);
requestList.wait(10000);
log.info("等待线程苏醒");
}
data.setResponse(new Response());
return;
}
final Query query = intentRequest.getQuery();
......@@ -246,7 +272,11 @@ public class DplBotService extends BaseBot {
} else {
response = RequestTerminal.requestTerminateDU2(userWord, getDeviceId());
}
log.info("小度,小悟返回:{}",response.getText());
log.info("小度,小悟返回:{}, audioUrl:{}",response.getText(),response.getAudio());
if (StringUtils.isBlank(response.getAudio())) {
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return;
}
if (!ScheduleService.getExceptBotAccount().contains(response.getAipioneerUsername())) {
String beforeBotAccount = getSessionAttribute("botAcc");
if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(response.getAipioneerUsername())) {
......@@ -265,8 +295,8 @@ public class DplBotService extends BaseBot {
DplbotServiceUtil.getPOOL().submit(() -> WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
.append(response.getText()).toString(), "du2"));
}
data.setResponse(new Response());
} catch (Exception e) {
log.warn("中控返回结果为空");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
}
finally {
......@@ -328,7 +358,7 @@ public class DplBotService extends BaseBot {
String name = ScheduleService.PRODUCT_ID_DETAIL.get(botId).getName();
if (name != null) desc = new StringBuilder("感谢您赏赐给").append(name)
.append("的").append(num).append("朵鲜花").toString();
Charge charge = new Charge(amount, orderId, "鲜花", desc);
Charge charge = new Charge(amount, orderId, num+"朵鲜花", desc);
charge.setToken(new StringBuilder(botId).append(File.separator).append(num).toString());
addDirective(charge);
data.setResponse(buildErrorResponse("请到小度APP上完成支付"));
......@@ -590,9 +620,15 @@ public class DplBotService extends BaseBot {
case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
}
if (getRequest().getContext().getScreen() == null) {
LAST_OUTTIME_MARK.remove(getDeviceId());
LAST_OUTTIME_RESULT.remove(getDeviceId());
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, EndMsg.BYE_BYE);
try {
RequestTerminal.requestTerminate("退出", getDeviceId());
if (DU_DEVICE_ID.equals(getDeviceId())) {
RequestTerminal.backRequest(DU_DEVICE_ID);
} else {
RequestTerminal.backRequestDU2(getDeviceId());
}
} catch (Exception e) {
log.warn("用户退出向中控发出退出指令出错");
}
......
......@@ -57,6 +57,15 @@ class RequestTerminal {
OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr);
}
static void backRequestDU2(String userId) {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg("退出");
String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.backPostAsync(Constants.INTERFACE_DI, requestJsonStr);
}
public static void main(String[] args) throws IOException {
String url = "http://didi-gz5.jiaoyou365.com:18082/api/works";
HashMap<String, String> params = new HashMap<>();
......
......@@ -7,7 +7,7 @@ package ai.qiwu.com.xiaoduhome.xiaoai.common;
*/
public interface XiaoAiConstants {
String QI_WU_TERMINATE_DIDI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_nx2 = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2";
String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8";
String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished";
......@@ -26,5 +26,9 @@ public interface XiaoAiConstants {
String END_WORD = "退出";
String USER_IDLE = "小悟在等你的回复";
String ANOTHER_USER_IDLE = "再不回复我,那我可退出喽";
String WAIT_WORD_1 = "请稍微等下,小悟正在努力的获取您刚才的返回结果,";
String WAIT_WORD_2 = "由于网络的原因,您可能需要稍稍等等";
String WAIT_WORD_3 = "由于网络原因小悟正在加倍努力获取结果,不过您现在得快些对我说些什么,要不然您就退出我们的技能了";
}
}
......@@ -13,6 +13,7 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Dire
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;
......@@ -23,6 +24,7 @@ import java.util.Random;
import java.util.concurrent.*;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WAIT_WORD_3;
/**
* @author 苗权威
......@@ -44,6 +46,10 @@ public class XiaoAiService {
* 缓存上次超时的响应结果,下次返回给用户
*/
private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
public static final Byte OUTTIME_TYPE_0 = 0;
public static final Byte OUTTIME_TYPE_1 = 1;
public static final String deviceId = "oIOWfYEFbZGFHB5DzoMA==";
......@@ -171,6 +177,8 @@ public class XiaoAiService {
// deviceId = getUserId(request);
// log.info("didi-gz3 deviceId:"+deviceId);
// }
LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.remove(getUserId(request));
return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD);
}
......@@ -183,23 +191,50 @@ public class XiaoAiService {
*/
private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) {
Boolean idle = request.getRequest().getNo_response();
Byte waitType;
if ((waitType=LAST_OUTTIME_MARK.get(userId)) != null) {
boolean firstTime = waitType == 0;
try {
//log.info("开始等待");
Thread.sleep(1600);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
}
if (LAST_OUTTIME_RESULT.get(userId) == null) {
if (Boolean.TRUE.equals(idle)) {
if (firstTime) {
LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_1);
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2);
} else {
return buildTextResponse(WAIT_WORD_3);
}
}
LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2);
}
LAST_OUTTIME_MARK.remove(userId);
return LAST_OUTTIME_RESULT.remove(userId);
}
if (idle != null && idle) {
try {
//log.info("开始等待");
Thread.sleep(1800);
Thread.sleep(1900);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
}
XiaoAiResponse response = getLastResult(userId);
if (response != null) return response;
// XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response;
//log.info("用户没说话");
//return buildTextResponse(".");
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
}
XiaoAiResponse response = getLastResult(userId);
if (response != null) return response;
// XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response;
try {
Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery()));
future.get(2100, TimeUnit.MILLISECONDS);
......@@ -208,6 +243,7 @@ public class XiaoAiService {
return buildTextResponse(SORRY_REPEAT);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
return buildTextResponse(XiaoAiConstants.ERROR_MSG.TIME_OUT);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", all.toString());
......@@ -229,6 +265,7 @@ public class XiaoAiService {
log.error("向终端发出的退出请求失败:{}", e.toString());
}
});
LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(userId);
return buildTextResponse(XiaoAiConstants.TTS.END_BYE);
}
......@@ -280,10 +317,11 @@ public class XiaoAiService {
log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestTerminateFail(e.toString());
}
if (response == null) {
if (response == null || StringUtils.isBlank(response.getAudio())) {
log.error("中控返回结果或是url链接为空");
xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
} else {
log.info("小爱,小悟返回:{}", response.getText());
log.info("小爱,小悟返回:{}, audio:{}", response.getText(),response.getAudio());
final String audioUrl = response.getAudio();
xiaoAiResponse = buildAudioResponse(audioUrl);
final String word = userWord;
......
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