添加功能

main
xueqingkun 4 months ago
parent a1fea304da
commit fa7430ee16

@ -54,11 +54,11 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <!--<dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.8.26</version> <version>5.8.26</version>
</dependency> </dependency>-->
</dependencies> </dependencies>
<build> <build>

@ -2,6 +2,7 @@ package com.supervision.contoller;
import com.supervision.dto.R; import com.supervision.dto.R;
import com.supervision.dto.robot.RobotTalkDTO; import com.supervision.dto.robot.RobotTalkDTO;
import com.supervision.model.RobotTalkReq;
import com.supervision.service.IChatService; import com.supervision.service.IChatService;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -21,8 +22,8 @@ public class ChatController {
private final IChatService chatService; private final IChatService chatService;
@PostMapping("/talk") @PostMapping("/talk")
public R<RobotTalkDTO> talk(@RequestParam("file") MultipartFile multipartFile) { public R<RobotTalkDTO> talk(@RequestParam("file") MultipartFile multipartFile, @ModelAttribute RobotTalkReq robotTalkReq) {
RobotTalkDTO talk = chatService.talk(multipartFile); RobotTalkDTO talk = chatService.talk(multipartFile,robotTalkReq);
return R.ok(talk); return R.ok(talk);
} }

@ -0,0 +1,18 @@
package com.supervision.dto.dify;
import lombok.Data;
@Data
public class ChatResDTO {
private String mode;
private String answer;
private String conversation_id;
private long created_at;
private String task_id;
private String message_id;
private String id;
private String event;
}

@ -1,4 +1,4 @@
package com.supervision.vo.talk; package com.supervision.model;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.Data; import lombok.Data;

@ -9,4 +9,6 @@ public class DifyChatReqVO {
private String user; private String user;
private String response_mode = CHAT_RESPONSE_MODE_BLOCKING; private String response_mode = CHAT_RESPONSE_MODE_BLOCKING;
private DIFYChatReqInputVO inputs = new DIFYChatReqInputVO(); private DIFYChatReqInputVO inputs = new DIFYChatReqInputVO();
private String query;
private String conversation_id;
} }

@ -1,14 +1,14 @@
package com.supervision.service; package com.supervision.service;
import com.supervision.dto.robot.RobotTalkDTO; import com.supervision.dto.robot.RobotTalkDTO;
import com.supervision.model.RobotTalkReq;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.IOException; import java.io.IOException;
public interface IChatService { public interface IChatService {
RobotTalkDTO talk(MultipartFile file); RobotTalkDTO talk(MultipartFile file, RobotTalkReq robotTalkReq);
void getAudio(HttpServletResponse response, String audioId) throws IOException; void getAudio(HttpServletResponse response, String audioId) throws IOException;
} }

@ -1,10 +1,12 @@
package com.supervision.service.impl; package com.supervision.service.impl;
import cn.hutool.core.codec.Base64; import cn.hutool.core.codec.Base64;
import com.supervision.dto.dify.ChatResDTO;
import com.supervision.dto.paddlespeech.res.TtsResultDTO; import com.supervision.dto.paddlespeech.res.TtsResultDTO;
import com.supervision.dto.robot.AnswerInfo; import com.supervision.dto.robot.AnswerInfo;
import com.supervision.dto.robot.AskInfo; import com.supervision.dto.robot.AskInfo;
import com.supervision.dto.robot.RobotTalkDTO; import com.supervision.dto.robot.RobotTalkDTO;
import com.supervision.model.RobotTalkReq;
import com.supervision.model.dify.DIFYChatReqInputVO; import com.supervision.model.dify.DIFYChatReqInputVO;
import com.supervision.model.dify.DifyChatReqVO; import com.supervision.model.dify.DifyChatReqVO;
import com.supervision.service.IChatService; import com.supervision.service.IChatService;
@ -34,8 +36,9 @@ public class ChatServiceImpl implements IChatService {
@Override @Override
public RobotTalkDTO talk(MultipartFile file) { public RobotTalkDTO talk(MultipartFile file, RobotTalkReq robotTalkReq) {
RobotTalkDTO.RobotTalkDTOBuilder builder = RobotTalkDTO.builder().sessionId("111"); log.info("robotTalkReq:{}", robotTalkReq);
RobotTalkDTO.RobotTalkDTOBuilder builder = RobotTalkDTO.builder();
try { try {
byte[] bytes = file.getBytes(); byte[] bytes = file.getBytes();
@ -44,21 +47,21 @@ public class ChatServiceImpl implements IChatService {
difyChatReqVO.setUser("admin"); difyChatReqVO.setUser("admin");
DIFYChatReqInputVO inputs = new DIFYChatReqInputVO(); DIFYChatReqInputVO inputs = new DIFYChatReqInputVO();
stopWatch.start("stt"); stopWatch.start("stt");
inputs.setQuery(AsrUtil.asrTransformByBytes(bytes));
stopWatch.stop(); stopWatch.stop();
String askUUid = UUID.randomUUID().toString(); difyChatReqVO.setQuery(AsrUtil.asrTransformByBytes(bytes));
builder.askInfo(AskInfo.builder().contentType(2).message(inputs.getQuery()).audioLength(100L).askId(askUUid).build()); difyChatReqVO.setConversation_id(robotTalkReq.getSessionId());
voiceCache.put(askUUid, Base64.encode(bytes));
difyChatReqVO.setInputs(inputs);
stopWatch.start("dify"); stopWatch.start("dify");
String response = difyApiUtil.chat(difyChatReqVO); ChatResDTO chatResDTO = difyApiUtil.chat(difyChatReqVO);
stopWatch.stop(); stopWatch.stop();
log.info("response:{}", response); 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));
stopWatch.start("tts"); stopWatch.start("tts");
TtsResultDTO ttsResultDTO = TtsUtil.ttsTransform(response); TtsResultDTO ttsResultDTO = TtsUtil.ttsTransform(chatResDTO.getAnswer());
stopWatch.stop(); stopWatch.stop();
String voiceBaseId = UUID.randomUUID().toString(); String voiceBaseId = UUID.randomUUID().toString();
builder.answerInfo(AnswerInfo.builder().contentType(2).message(response).voiceBaseId(voiceBaseId).voiceBase64(ttsResultDTO.getAudio()).build()); builder.answerInfo(AnswerInfo.builder().contentType(2).message(chatResDTO.getAnswer()).voiceBaseId(voiceBaseId).voiceBase64(ttsResultDTO.getAudio()).build());
builder.sessionId(chatResDTO.getConversation_id());
voiceCache.put(voiceBaseId, ttsResultDTO.getAudio()); voiceCache.put(voiceBaseId, ttsResultDTO.getAudio());
log.info("耗时:{}", stopWatch.prettyPrint()); log.info("耗时:{}", stopWatch.prettyPrint());
} catch (IOException e) { } catch (IOException e) {

@ -1,7 +1,7 @@
package com.supervision.util; package com.supervision.util;
import com.alibaba.fastjson.JSON; import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject; import com.supervision.dto.dify.ChatResDTO;
import com.supervision.model.dify.DifyChatReqVO; import com.supervision.model.dify.DifyChatReqVO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.ClientProtocolException;
@ -27,8 +27,8 @@ public class DifyApiUtil {
@Value("${dify.app-auth}") @Value("${dify.app-auth}")
private String difyAppAuth; private String difyAppAuth;
public String chat(DifyChatReqVO difyChatReqVO) { public ChatResDTO chat(DifyChatReqVO difyChatReqVO) {
String result = null; ChatResDTO execute;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(difyUrl); HttpPost httpPost = new HttpPost(difyUrl);
httpPost.setHeader(HttpHeaders.AUTHORIZATION, difyAppAuth); httpPost.setHeader(HttpHeaders.AUTHORIZATION, difyAppAuth);
@ -36,14 +36,14 @@ public class DifyApiUtil {
log.info("发起对话:{}", difyChatReqVO); log.info("发起对话:{}", difyChatReqVO);
StringEntity entity = new StringEntity(com.alibaba.fastjson.JSONObject.toJSON(difyChatReqVO).toString(), StandardCharsets.UTF_8); StringEntity entity = new StringEntity(com.alibaba.fastjson.JSONObject.toJSON(difyChatReqVO).toString(), StandardCharsets.UTF_8);
httpPost.setEntity(entity); httpPost.setEntity(entity);
result = httpClient.execute(httpPost, response -> { execute = httpClient.execute(httpPost, response -> {
final int status = response.getCode(); final int status = response.getCode();
if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) { if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
final HttpEntity responseEntity = response.getEntity(); final HttpEntity responseEntity = response.getEntity();
String responseStr = EntityUtils.toString(responseEntity); String responseStr = EntityUtils.toString(responseEntity);
JSONObject jsonObject = JSON.parseObject(responseStr); ChatResDTO chatResDTO = JSONUtil.toBean(responseStr, ChatResDTO.class);
log.info("DIFY返回{}", jsonObject.getJSONObject("data").getJSONObject("outputs").get("answerText").toString()); log.info("DIFY返回{}", chatResDTO.getAnswer());
return jsonObject.getJSONObject("data").getJSONObject("outputs").get("answerText").toString(); return chatResDTO;
} else { } else {
log.info("responseEntity {}", EntityUtils.toString(response.getEntity())); log.info("responseEntity {}", EntityUtils.toString(response.getEntity()));
throw new ClientProtocolException("Unexpected response status: " + status); throw new ClientProtocolException("Unexpected response status: " + status);
@ -51,8 +51,9 @@ public class DifyApiUtil {
}); });
} catch (Exception e) { } catch (Exception e) {
log.error("发起对话失败", e); log.error("发起对话失败", e);
throw new RuntimeException("发起对话失败");
} }
return result; return execute;
} }
} }

@ -24,7 +24,6 @@ public class TtsUtil {
try { try {
PaddleSpeechResDTO<TtsResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<TtsResultDTO>>() { PaddleSpeechResDTO<TtsResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<TtsResultDTO>>() {
}); });
log.info("response:{}", response.getResult());
if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) { if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
throw new BusinessException("文字转换语音失败"); throw new BusinessException("文字转换语音失败");
} }

@ -6,8 +6,8 @@ server:
servlet: servlet:
context-path: /speech-demo-service context-path: /speech-demo-service
dify: dify:
url: http://192.168.10.137/v1/workflows/run url: http://192.168.10.138/v1/chat-messages
app-auth: Bearer app-cSxbjvdTZQhq2p2cKinChIhj app-auth: Bearer app-79ABpRQWayX0bK9C2m7vecXe
paddle-speech: paddle-speech:
tts: http://192.168.10.138:8090/paddlespeech/tts tts: http://192.168.10.138:8090/paddlespeech/tts
asr: http://192.168.10.138:8090/paddlespeech/asr asr: http://192.168.10.138:8090/paddlespeech/asr

@ -1,11 +1,15 @@
package com.supervision; package com.supervision;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import com.supervision.dto.dify.ChatResDTO;
import com.supervision.dto.paddlespeech.res.TtsResultDTO; import com.supervision.dto.paddlespeech.res.TtsResultDTO;
import com.supervision.model.dify.DIFYChatReqInputVO;
import com.supervision.model.dify.DifyChatReqVO;
import com.supervision.util.AsrUtil; import com.supervision.util.AsrUtil;
import com.supervision.util.DifyApiUtil;
import com.supervision.util.TtsUtil; import com.supervision.util.TtsUtil;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -34,4 +38,20 @@ class SpeechDemoServiceApplicationTests {
System.out.println(text); System.out.println(text);
} }
@Resource
private DifyApiUtil difyApiUtil;
@Test
public void chatTest() {
DifyChatReqVO difyChatReqVO = new DifyChatReqVO();
difyChatReqVO.setUser("admin");
DIFYChatReqInputVO inputs = new DIFYChatReqInputVO();
difyChatReqVO.setQuery("我叫什么?");
difyChatReqVO.setInputs(inputs);
System.out.println(JSONUtil.toJsonStr(difyChatReqVO));
ChatResDTO chat = difyApiUtil.chat(difyChatReqVO);
System.out.println(JSONUtil.toJsonStr(chat));
}
} }

Loading…
Cancel
Save