You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

144 lines
5.9 KiB
Java

package com.supervision.service.impl;
import cn.hutool.core.codec.Base64;
2 months ago
import com.supervision.dto.dify.ChatResDTO;
2 months ago
import com.supervision.dto.paddlespeech.res.TtsResultDTO;
import com.supervision.dto.robot.AnswerInfo;
import com.supervision.dto.robot.AskInfo;
import com.supervision.dto.robot.RobotTalkDTO;
2 months ago
import com.supervision.model.RobotTalkReq;
2 months ago
import com.supervision.model.dify.DIFYChatReqInputVO;
import com.supervision.model.dify.DifyChatReqVO;
import com.supervision.service.IChatService;
2 months ago
import com.supervision.util.AsrUtil;
import com.supervision.util.DifyApiUtil;
import com.supervision.util.TtsUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
2 months ago
import lombok.extern.slf4j.Slf4j;
2 months ago
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
2 months ago
import org.springframework.stereotype.Service;
2 months ago
import org.springframework.util.StopWatch;
2 months ago
import org.springframework.web.multipart.MultipartFile;
2 months ago
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
2 months ago
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2 months ago
@Slf4j
@Service
public class ChatServiceImpl implements IChatService {
2 months ago
@Resource
private DifyApiUtil difyApiUtil;
2 months ago
Map<String, String> voiceCache = new HashMap<>();
2 months ago
@Override
2 months ago
public RobotTalkDTO talk(MultipartFile file, RobotTalkReq robotTalkReq) {
log.info("robotTalkReq:{}", robotTalkReq);
RobotTalkDTO.RobotTalkDTOBuilder builder = RobotTalkDTO.builder();
2 months ago
2 months ago
try {
2 months ago
byte[] bytes = file.getBytes();
StopWatch stopWatch = new StopWatch();
2 months ago
DifyChatReqVO difyChatReqVO = new DifyChatReqVO();
difyChatReqVO.setUser("admin");
DIFYChatReqInputVO inputs = new DIFYChatReqInputVO();
2 months ago
stopWatch.start("stt");
stopWatch.stop();
2 months ago
difyChatReqVO.setQuery(replaceTown(AsrUtil.asrTransformByBytes(bytes)));
2 months ago
difyChatReqVO.setConversation_id(robotTalkReq.getSessionId());
2 months ago
stopWatch.start("dify");
2 months ago
ChatResDTO chatResDTO = difyApiUtil.chat(difyChatReqVO);
2 months ago
stopWatch.stop();
2 months ago
log.info("response:{}", chatResDTO.getAnswer());
builder.askInfo(AskInfo.builder().contentType(2).message(inputs.getQuery()).audioLength(100L).askId(chatResDTO.getMessage_id()).build());
voiceCache.put(chatResDTO.getMessage_id(), Base64.encode(bytes));
2 months ago
stopWatch.start("tts");
2 months ago
TtsResultDTO ttsResultDTO = TtsUtil.ttsTransform(chatResDTO.getAnswer());
2 months ago
stopWatch.stop();
String voiceBaseId = UUID.randomUUID().toString();
2 months ago
builder.answerInfo(AnswerInfo.builder().contentType(2).message(chatResDTO.getAnswer()).voiceBaseId(voiceBaseId).voiceBase64(ttsResultDTO.getAudio()).build());
builder.sessionId(chatResDTO.getConversation_id());
2 months ago
voiceCache.put(voiceBaseId, ttsResultDTO.getAudio());
log.info("耗时:{}", stopWatch.prettyPrint());
2 months ago
} catch (IOException e) {
throw new RuntimeException(e);
}
2 months ago
return builder.build();
}
@Override
public void getAudio(HttpServletResponse response, String audioId) throws IOException {
2 months ago
log.info("audioId:{}", audioId);
Base64.decodeToStream(voiceCache.get(audioId), response.getOutputStream(), false);
2 months ago
}
2 months ago
/**
* menghe
* true
*
* @param text
* @return
*/
public static String replaceTown(String text) {
// 正则模式:匹配两个汉字紧跟“小镇”
Pattern pattern = Pattern.compile("([\u4e00-\u9fa5]{2})小镇");
Matcher matcher = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
// 配置拼音输出格式:小写、无声调
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
while (matcher.find()) {
String twoChars = matcher.group(1);
StringBuilder pinyinStr = new StringBuilder();
boolean valid = true;
// 遍历两个汉字,转换为拼音并拼接
for (int i = 0; i < twoChars.length(); i++) {
char ch = twoChars.charAt(i);
try {
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch, format);
if (pinyinArray != null && pinyinArray.length > 0) {
pinyinStr.append(pinyinArray[0]);
} else {
valid = false;
break;
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
valid = false;
break;
}
}
// 如果转换后的拼音为 "menghe",则替换为 "勐赫小镇"
if (valid && "menghe".contentEquals(pinyinStr)) {
matcher.appendReplacement(sb, "勐赫小镇");
} else {
matcher.appendReplacement(sb, matcher.group(0));
}
}
matcher.appendTail(sb);
return sb.toString();
}
// 示例测试
public static void main(String[] args) {
String sampleText = "欢迎来到孟河小镇,体验独特的小镇风情;另外,还有梦和小镇等待你探访。";
System.out.println(replaceTown(sampleText));
}
}