优化,提取工具类

dev_v1.0.1
liu 2 years ago
parent 911a83a093
commit acf4256904

@ -31,7 +31,7 @@ public class AskController {
session.sendMessage(new TextMessage(message));
}
@ApiOperation("接收页面的语音消息")
@ApiOperation("接收页面的语音消息(暂时不用这个接口,主要使用websocket进行通信)")
@PostMapping("/receiveVoiceFile")
public String receiveVoiceFile(@RequestParam("file") MultipartFile file) throws IOException {
return askService.receiveVoiceFile(file);
@ -45,8 +45,8 @@ public class AskController {
@ApiOperation("进行对话")
@GetMapping("conversation")
public List<String> conversation(String question) {
return askService.conversation(question);
public List<String> conversation(String question, String sessionId) {
return askService.conversation(question, sessionId);
}
@ApiOperation("查询对话历史")

@ -0,0 +1,44 @@
package com.supervision.paddlespeech;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.supervision.exception.BusinessException;
import com.supervision.paddlespeech.dto.req.AsrReqDTO;
import com.supervision.paddlespeech.dto.res.AsrResultDTO;
import com.supervision.paddlespeech.dto.res.PaddleSpeechResDTO;
import com.supervision.util.SpringBeanUtil;
import org.springframework.core.env.Environment;
public class AsrUtil {
private static final String ASR_URL = SpringBeanUtil.getBean(Environment.class).getProperty("paddle-speech.asr");
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String asrTransformByBytes(byte[] bytes) {
// 首先编码为base64编码
String encode = Base64.encode(bytes);
return asrTransformByBytes(encode);
}
public static String asrTransformByBytes(String voiceBase64){
// 这里调用Python的接口,将文字转换为语音
String post = HttpUtil.post(ASR_URL, JSONUtil.toJsonStr(new AsrReqDTO(voiceBase64)));
try {
PaddleSpeechResDTO<AsrResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<AsrResultDTO>>() {
});
if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
throw new BusinessException("语音转换文字失败");
}
return response.getResult().getTranscription();
} catch (Exception e) {
throw new BusinessException("语音转换文字失败");
}
}
}

@ -0,0 +1,40 @@
package com.supervision.paddlespeech;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.supervision.exception.BusinessException;
import com.supervision.paddlespeech.dto.req.TtsReqDTO;
import com.supervision.paddlespeech.dto.res.PaddleSpeechResDTO;
import com.supervision.paddlespeech.dto.res.TtsResultDTO;
import com.supervision.pojo.vo.ReplyVoiceResVO;
import com.supervision.util.SpringBeanUtil;
import org.springframework.core.env.Environment;
public class TtsUtil {
private static final String TTS_URL = SpringBeanUtil.getBean(Environment.class).getProperty("paddle-speech.tts");
private static final ObjectMapper objectMapper = new ObjectMapper();
public static ReplyVoiceResVO ttsTransform(String str) {
// 构建
String post = HttpUtil.post(TTS_URL, JSONUtil.toJsonStr(new TtsReqDTO(str)));
try {
PaddleSpeechResDTO<TtsResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<TtsResultDTO>>() {
});
if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
throw new BusinessException("文字转换语音失败");
}
ReplyVoiceResVO resVO = new ReplyVoiceResVO();
resVO.setVoice(response.getResult().getAudio());
resVO.setText(str);
return resVO;
} catch (Exception e) {
throw new BusinessException("语音转换文字失败");
}
}
}

@ -1,4 +1,4 @@
package com.supervision.pojo.paddlespeech.req;
package com.supervision.paddlespeech.dto.req;
import lombok.Data;

@ -1,4 +1,4 @@
package com.supervision.pojo.paddlespeech.req;
package com.supervision.paddlespeech.dto.req;
import lombok.Data;

@ -1,11 +0,0 @@
package com.supervision.pojo.rasa.train.intent;
import lombok.Data;
import java.util.List;
@Data
public class NluTemplate {
}

@ -0,0 +1,27 @@
package com.supervision.rasa;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.rasa.dto.RasaReqDTO;
import com.supervision.rasa.dto.RasaResDTO;
import com.supervision.util.SpringBeanUtil;
import org.springframework.core.env.Environment;
import java.util.List;
import java.util.stream.Collectors;
public class RasaUtil {
private static final String RASA_URL = SpringBeanUtil.getBean(Environment.class).getProperty("rasa.url");
public static List<String> talkRasa(String question, String sessionId) {
RasaReqDTO rasaReqDTO = new RasaReqDTO();
rasaReqDTO.setSender(sessionId);
rasaReqDTO.setMessage(question);
String post = HttpUtil.post(RASA_URL, JSONUtil.toJsonStr(rasaReqDTO));
List<RasaResDTO> list = JSONUtil.toList(post, RasaResDTO.class);
return list.stream().map(RasaResDTO::getText).collect(Collectors.toList());
}
}

@ -1,4 +1,4 @@
package com.supervision.pojo.rasa.train.intent;
package com.supervision.rasa.dto.train;
import lombok.AllArgsConstructor;
import lombok.Data;

@ -1,4 +1,4 @@
package com.supervision.pojo.rasa.train.intent;
package com.supervision.rasa.dto.train;
import lombok.Data;
import org.yaml.snakeyaml.nodes.Tag;

@ -1,4 +1,4 @@
package com.supervision.pojo.rasa.train.intent;
package com.supervision.rasa.dto.train;
import cn.hutool.core.map.MapUtil;
import lombok.AllArgsConstructor;

@ -2,6 +2,7 @@ package com.supervision.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.supervision.pojo.vo.ReplyVoiceResVO;
import com.supervision.websocket.dto.SocketMessageDTO;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@ -10,11 +11,13 @@ import java.util.List;
public interface AskService {
void handlerMessageBySocket(SocketMessageDTO socketMessageDTO);
String receiveVoiceFile(MultipartFile file) throws IOException;
ReplyVoiceResVO replyVoice();
List<String> conversation(String question);
List<String> conversation(String question, String sessionId);
}

@ -1,22 +1,17 @@
package com.supervision.service.impl;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.supervision.exception.BusinessException;
import com.supervision.pojo.paddlespeech.req.AsrReqDTO;
import com.supervision.pojo.paddlespeech.req.TtsReqDTO;
import com.supervision.pojo.paddlespeech.res.AsrResultDTO;
import com.supervision.pojo.paddlespeech.res.PaddleSpeechResDTO;
import com.supervision.pojo.paddlespeech.res.TtsResultDTO;
import com.supervision.pojo.rasa.RasaReqDTO;
import com.supervision.pojo.rasa.RasaResDTO;
import com.supervision.paddlespeech.AsrUtil;
import com.supervision.paddlespeech.TtsUtil;
import com.supervision.rasa.RasaUtil;
import com.supervision.rasa.dto.RasaReqDTO;
import com.supervision.rasa.dto.RasaResDTO;
import com.supervision.pojo.vo.ReplyVoiceResVO;
import com.supervision.service.AskService;
import com.supervision.websocket.dto.SocketMessageDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@ -24,7 +19,6 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@ -32,73 +26,43 @@ import java.util.stream.Collectors;
public class AskServiceImpl implements AskService {
@Value("${paddle-speech.tts}")
private String tts;
@Value("${paddle-speech.asr}")
private String asr;
@Override
public void handlerMessageBySocket(SocketMessageDTO socketMessageDTO) {
// 首先获取消息的类型
String text;
if (0 == socketMessageDTO.getMessageType()) {
// 如果是语音消息
// 调用百度接口,语音转文字
text = AsrUtil.asrTransformByBytes(socketMessageDTO.getVoiceMessage());
} else {
text = socketMessageDTO.getTextMessage();
}
if (StrUtil.isBlank(text)) {
throw new BusinessException("语音消息不能为空");
}
// 进行rasa对话
@Value("${rasa.url}")
private String rasa;
private final ObjectMapper objectMapper = new ObjectMapper();
}
@Override
public String receiveVoiceFile(MultipartFile file) throws IOException {
return asrTransform(file.getBytes());
// 获取音频对应的文字
String askQuestion = AsrUtil.asrTransformByBytes(file.getBytes());
// 调用rasa获取文字内容
throw new BusinessException("暂未实现");
}
@Override
public ReplyVoiceResVO replyVoice() {
String text = "测试:这是文字转语音的测试,测试是否OK";
return ttsTransform(text);
return TtsUtil.ttsTransform(text);
}
private String asrTransform(byte[] bytes) {
// 首先编码为base64编码
String encode = Base64.encode(bytes);
// 这里调用Python的接口,将文字转换为语音
String post = HttpUtil.post(asr, JSONUtil.toJsonStr(new AsrReqDTO(encode)));
try {
PaddleSpeechResDTO<AsrResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<AsrResultDTO>>() {});
if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
throw new BusinessException("语音转换文字失败");
}
return response.getResult().getTranscription();
}catch (Exception e){
throw new BusinessException("语音转换文字失败");
}
}
private ReplyVoiceResVO ttsTransform(String str) {
// 构建
String post = HttpUtil.post(tts, JSONUtil.toJsonStr(new TtsReqDTO(str)));
try {
PaddleSpeechResDTO<TtsResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<TtsResultDTO>>() {
});
if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
throw new BusinessException("文字转换语音失败");
}
ReplyVoiceResVO resVO = new ReplyVoiceResVO();
resVO.setVoice(response.getResult().getAudio());
resVO.setText(str);
return resVO;
}catch (Exception e){
throw new BusinessException("语音转换文字失败");
}
}
@Override
public List<String> conversation(String question) {
RasaReqDTO rasaReqDTO = new RasaReqDTO();
rasaReqDTO.setSender("tester1");
rasaReqDTO.setMessage(question);
String post = HttpUtil.post(rasa, JSONUtil.toJsonStr(rasaReqDTO));
List<RasaResDTO> list = JSONUtil.toList(post, RasaResDTO.class);
return list.stream().map(RasaResDTO::getText).collect(Collectors.toList());
public List<String> conversation(String question, String sessionId) {
return RasaUtil.talkRasa(question,sessionId);
}
}

@ -6,10 +6,10 @@ import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.exception.BusinessException;
import com.supervision.model.*;
import com.supervision.pojo.rasa.train.intent.DomainYmlTemplate;
import com.supervision.pojo.rasa.train.intent.Intent;
import com.supervision.pojo.rasa.train.intent.NluYmlTemplate;
import com.supervision.pojo.rasa.train.intent.RuleYmlTemplate;
import com.supervision.rasa.dto.train.DomainYmlTemplate;
import com.supervision.rasa.dto.train.Intent;
import com.supervision.rasa.dto.train.NluYmlTemplate;
import com.supervision.rasa.dto.train.RuleYmlTemplate;
import com.supervision.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;

@ -0,0 +1,127 @@
package com.supervision.util;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.util.Map;
/***
* @author ljt
* @since 2020/8/4 17:37
*
*/
@Component
@Lazy(false)
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* applicationContext
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringBeanUtil.applicationContext = applicationContext;
}
//通过name获取 Bean.
/**
* name Bean
*
* @param <T> Bean
* @param name Bean
* @return Bean
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* classBean
*
* @param <T> Bean
* @param clazz Bean
* @return Bean
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
/**
* name,ClazzBean
*
* @param <T> bean
* @param name Bean
* @param clazz bean
* @return Bean
*/
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
/**
* Bean
*
* @param <T> Bean
* @param type nullbean
* @return beankeybeannamevalueBean
* @since 5.3.3
*/
public static <T> Map<String, T> getBeansOfType(Class<T> type) {
return applicationContext.getBeansOfType(type);
}
/**
* Bean
*
* @param type nullbean
* @return bean
* @since 5.3.3
*/
public static String[] getBeanNamesForType(Class<?> type) {
return applicationContext.getBeanNamesForType(type);
}
/**
*
*
* @param key key
* @return
* @since 5.3.3
*/
public static String getProperty(String key) {
return applicationContext.getEnvironment().getProperty(key);
}
/**
* null
*
* @return
* @since 5.3.3
*/
public static String[] getActiveProfiles() {
return applicationContext.getEnvironment().getActiveProfiles();
}
/**
*
*
* @return
* @since 5.3.3
*/
public static String getActiveProfile() {
final String[] activeProfiles = getActiveProfiles();
return ArrayUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
}

@ -0,0 +1,14 @@
package com.supervision.websocket.dto;
import lombok.Data;
@Data
public class ActionDTO {
/**
* type,2,tool ancillary
*/
private String actionType;
private String actionId;
}

@ -1,13 +1,37 @@
package com.supervision.websocket.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel
public class SocketMessageDTO {
@ApiModelProperty("socket链接ID")
private String socketId;
@ApiModelProperty("当前用户ID")
private String userId;
private String data;
@ApiModelProperty("文字消息内容")
private String textMessage;
@ApiModelProperty("语音消息内容")
private String voiceMessage;
@ApiModelProperty("若有动作,这是需要执行的动作内容")
private ActionDTO action;
/**
* 使,action,0,1
*/
@ApiModelProperty("后端返回给前端时使用,表示该是消息还是action动作,0消息,1动作")
private Integer type;
/**
* action,0,1
*/
@ApiModelProperty("前端到后端使用,表示是语音还是文字,0语音,1文字")
private Integer messageType;
}

@ -1,9 +1,12 @@
package com.supervision.websocket.handler;
import cn.hutool.json.JSONUtil;
import com.supervision.service.AskService;
import com.supervision.util.SpringBeanUtil;
import com.supervision.websocket.cache.WebSocketUserCache;
import com.supervision.websocket.dto.SocketMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNullApi;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
@ -21,14 +24,17 @@ public class AskWebSocketHandler extends TextWebSocketHandler {
// 返回sessionId到前端
SocketMessageDTO socketMessageDTO = new SocketMessageDTO();
socketMessageDTO.setSocketId(id);
socketMessageDTO.setData("链接成功");
session.sendMessage(new TextMessage(JSONUtil.toJsonStr(socketMessageDTO)));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
// 处理接收到的文本消息
// 处理接收到的消息
log.info("收到消息:{}", message.toString());
// 这里反序列化消息,将消息形成固定的格式
SocketMessageDTO socketMessageDTO = JSONUtil.toBean(message.getPayload(), SocketMessageDTO.class);
AskService askService = SpringBeanUtil.getBean(AskService.class);
askService.handlerMessageBySocket(socketMessageDTO);
}
@Override

Loading…
Cancel
Save