TTSStreamController.java
10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package com.xly.web;
import com.xly.runner.AppStartupRunner;
import com.xly.service.UserSceneSessionService;
import com.xly.tool.DynamicToolProvider;
import com.xly.tts.bean.*;
import com.xly.tts.service.PythonTtsProxyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Slf4j
@RestController
@RequestMapping("/api/tts")
@RequiredArgsConstructor
public class TTSStreamController {
private final PythonTtsProxyService pythonTtsProxyService;
private final DynamicToolProvider dynamicToolProvider;
private final UserSceneSessionService userSceneSessionService;
private final AppStartupRunner appStartupRunner;
/***
* @Author 钱豹
* @Date 14:32 2026/2/10
* @Param [request]
* @return org.springframework.http.ResponseEntity<com.xly.tts.bean.TTSResponseDTO>
* @Description 初始化AI所有变量 热启动
**/
@PostMapping("/initTool")
public ResponseEntity<TTSResponseDTO> initTool(@RequestBody TTSRequestDTO request) {
appStartupRunner.cleanAllInit();
userSceneSessionService.cleanAllSession();
dynamicToolProvider.cleanAllToolProvider();
//方法重新初始化
dynamicToolProvider.init();
return pythonTtsProxyService.initTool(request);
}
/**
* 提取报修结构化信息
*/
@PostMapping("/init")
public ResponseEntity<TTSResponseDTO> init(@RequestBody TTSRequestDTO request) {
return pythonTtsProxyService.init(request);
}
@PostConstruct
public void init() {
log.info("TTS Stream Controller initialized");
log.info("Python TTS Service URL: http://localhost:8000");
}
@PreDestroy
public void cleanup() {
log.info("TTS Stream Controller shutting down");
pythonTtsProxyService.shutdown();
}
/**
* 流式合成语音(代理到Python服务)
*/
@PostMapping("/stream/query")
public ResponseEntity<TTSResponseDTO> stream(@RequestBody TTSRequestDTO request) {
return pythonTtsProxyService.synthesizeStreamAi(request);
}
/**
* 流式合成语音(代理到Python服务)
*/
@PostMapping("/cleanMemory")
public ResponseEntity<TTSResponseDTO> cleanMemory(@RequestBody TTSRequestDTO request) {
return pythonTtsProxyService.cleanMemory(request);
}
/**
* 流式合成语音(异步)
*/
@PostMapping("/async-stream")
public CompletableFuture<ResponseEntity<InputStreamResource>> asyncStreamSynthesize(
@RequestBody TTSRequestDTO request) {
log.info("收到异步流式合成请求");
return pythonTtsProxyService.synthesizeStreamAsync(request);
}
/**
* 直接调用Python服务合成
*/
@PostMapping("/direct-stream")
public ResponseEntity<InputStreamResource> directStreamSynthesize(@RequestBody TTSRequestDTO request) {
log.info("收到直接合成请求");
return pythonTtsProxyService.synthesizeDirect(request);
}
/**
* 简化的流式接口
*/
@PostMapping("/quick-stream")
public ResponseEntity<InputStreamResource> quickStream(
@RequestParam String text,
@RequestParam(defaultValue = "zh-CN-XiaoxiaoNeural") String voice) {
log.info("收到快速合成请求: voice={}, text={}", voice,
text.length() > 50 ? text.substring(0, 50) + "..." : text);
return pythonTtsProxyService.quickSynthesize(text, voice);
}
/**
* GET方式的快速合成接口
*/
@GetMapping("/quick-stream")
public ResponseEntity<InputStreamResource> quickStreamGet(
@RequestParam String text,
@RequestParam(defaultValue = "zh-CN-XiaoxiaoNeural") String voice) {
return quickStream(text, voice);
}
/**
* 获取所有可用语音
*/
@GetMapping("/voices")
public ResponseEntity<List<VoiceInfoDTO>> getVoices() {
log.info("收到获取语音列表请求");
List<VoiceInfoDTO> voices = pythonTtsProxyService.getAvailableVoices();
return ResponseEntity.ok(voices);
}
/**
* 获取特定语音详情
*/
@GetMapping("/voices/{name}")
public ResponseEntity<VoiceInfoDTO> getVoiceDetail(@PathVariable String name) {
log.info("收到获取语音详情请求: {}", name);
VoiceInfoDTO voice = pythonTtsProxyService.getVoiceDetail(name);
if (voice != null) {
return ResponseEntity.ok(voice);
} else {
return ResponseEntity.notFound().build();
}
}
/**
* 健康检查(同时检查Java服务和Python服务)
*/
@GetMapping("/health")
public ResponseEntity<Object> healthCheck() {
boolean pythonServiceHealthy = pythonTtsProxyService.healthCheck();
HealthStatus healthStatus = new HealthStatus();
healthStatus.setJavaService("healthy");
healthStatus.setPythonService(pythonServiceHealthy ? "healthy" : "unhealthy");
healthStatus.setTimestamp(System.currentTimeMillis());
healthStatus.setMessage(pythonServiceHealthy ?
"所有服务运行正常" : "Python TTS服务不可用");
if (pythonServiceHealthy) {
return ResponseEntity.ok(healthStatus);
} else {
return ResponseEntity.status(503).body(healthStatus);
}
}
/**
* 简单健康检查(仅返回状态)
*/
@GetMapping("/health/simple")
public ResponseEntity<String> healthCheckSimple() {
boolean pythonServiceHealthy = pythonTtsProxyService.healthCheck();
if (pythonServiceHealthy) {
return ResponseEntity.ok("TTS服务运行正常");
} else {
return ResponseEntity.status(503).body("Python TTS服务不可用");
}
}
/**
* 批处理合成
*/
@PostMapping("/batch")
public ResponseEntity<List<ResponseEntity<InputStreamResource>>> batchSynthesize(
@RequestBody List<TTSRequestDTO> requests) {
log.info("收到批量合成请求,数量: {}", requests.size());
List<ResponseEntity<InputStreamResource>> results = pythonTtsProxyService.batchSynthesize(requests);
return ResponseEntity.ok(results);
}
/**
* SSE流式输出(Server-Sent Events)
*/
@GetMapping(value = "/sse-stream", produces = "text/event-stream")
public ResponseEntity<StreamingResponseBody> sseStream(
@RequestParam String text,
@RequestParam(defaultValue = "zh-CN-XiaoxiaoNeural") String voice) {
log.info("收到SSE流式请求: voice={}", voice);
TTSRequestDTO request = new TTSRequestDTO();
request.setText(text);
request.setVoice(voice);
StreamingResponseBody responseBody = outputStream -> {
try {
outputStream.write(("event: audio-start\ndata: \n\n").getBytes());
outputStream.flush();
// 调用Python服务获取音频
ResponseEntity<InputStreamResource> response = pythonTtsProxyService.synthesizeStream(request);
if (response.getBody() != null) {
InputStream inputStream = response.getBody().getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
int totalBytes = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
totalBytes += bytesRead;
// 发送进度事件
String progressEvent = String.format(
"event: progress\ndata: {\"bytes\":%d}\n\n", totalBytes);
outputStream.write(progressEvent.getBytes());
outputStream.flush();
// 发送音频数据(base64编码)
String base64Data = java.util.Base64.getEncoder().encodeToString(
java.util.Arrays.copyOfRange(buffer, 0, bytesRead));
String audioEvent = String.format(
"event: audio-data\ndata: {\"chunk\":\"%s\"}\n\n", base64Data);
outputStream.write(audioEvent.getBytes());
outputStream.flush();
}
// 发送完成事件
String completeEvent = String.format(
"event: audio-complete\ndata: {\"total_bytes\":%d}\n\n", totalBytes);
outputStream.write(completeEvent.getBytes());
outputStream.flush();
} else {
outputStream.write(("event: error\ndata: {\"message\":\"合成失败\"}\n\n").getBytes());
outputStream.flush();
}
} catch (Exception e) {
// log.error("SSE流式输出异常: {}", e.getMessage(), e);
try {
outputStream.write(("event: error\ndata: {\"message\":\"" +
e.getMessage().replace("\"", "\\\"") + "\"}\n\n").getBytes());
outputStream.flush();
} catch (Exception ex) {
// 忽略关闭错误
}
}
};
return ResponseEntity.ok()
.header("Content-Type", "text/event-stream")
.header("Cache-Control", "no-cache")
.header("X-Accel-Buffering", "no") // 禁用Nginx缓冲
.body(responseBody);
}
/**
* 测试接口
*/
@GetMapping("/test")
public ResponseEntity<InputStreamResource> testSynthesis() {
log.info("收到测试请求");
TTSRequestDTO request = new TTSRequestDTO();
request.setText("这是一个测试语音,用于验证Edge-TTS服务是否正常工作。");
request.setVoice("zh-CN-XiaoxiaoNeural");
return pythonTtsProxyService.synthesizeStream(request);
}
/**
* 状态接口
*/
@GetMapping("/status")
public ResponseEntity<Object> getStatus() {
ServiceStatus status = new ServiceStatus();
status.setJavaService(true);
status.setPythonService(pythonTtsProxyService.healthCheck());
status.setServiceUrl("http://localhost:8000");
status.setJavaApiUrl("/api/tts");
status.setTimestamp(new java.util.Date());
return ResponseEntity.ok(status);
}
}