dsh-gsv-tts 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ export class VoiceManager {
2
+ voices = new Map();
3
+ defaultVoice;
4
+ constructor(config) {
5
+ this.defaultVoice = config.defaultVoice;
6
+ for (const v of config.voices) {
7
+ this.voices.set(v.name, v);
8
+ }
9
+ }
10
+ list() {
11
+ return Array.from(this.voices.values());
12
+ }
13
+ get(name) {
14
+ if (name && this.voices.has(name)) {
15
+ return this.voices.get(name);
16
+ }
17
+ if (this.defaultVoice && this.voices.has(this.defaultVoice)) {
18
+ return this.voices.get(this.defaultVoice);
19
+ }
20
+ return this.voices.values().next().value;
21
+ }
22
+ get defaultName() {
23
+ return this.defaultVoice;
24
+ }
25
+ }
26
+ //# sourceMappingURL=voice-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice-manager.js","sourceRoot":"","sources":["../src/voice-manager.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,YAAY;IACf,MAAM,GAA6B,IAAI,GAAG,EAAE,CAAC;IAC7C,YAAY,CAAS;IAE7B,YAAY,MAAc;QACxB,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;QACxC,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAED,IAAI;QACF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,GAAG,CAAC,IAAa;QACf,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC;YAC5D,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;IAC3C,CAAC;IAED,IAAI,WAAW;QACb,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "dsh-gsv-tts",
3
+ "version": "2.2.0",
4
+ "description": "DSH plugin for GSV-TTS-Lite: voice presets, auto-read, engine setup assistant, read-aloud button, and settings panel",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./client": {
14
+ "types": "./lib/client.d.ts",
15
+ "default": "./lib/client.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib",
21
+ "scripts",
22
+ "cordis.patch.yml"
23
+ ],
24
+ "dsh": {
25
+ "bundle": {
26
+ "patch": "./cordis.patch.yml"
27
+ },
28
+ "client": {
29
+ "inject": [
30
+ "@deepseek-ai/dsh-client-runtime",
31
+ "@deepseek-ai/dsh-client-locale",
32
+ "@deepseek-ai/dsh-client-ui-slots",
33
+ "@deepseek-ai/dsh-client-ui-conversation",
34
+ "@deepseek-ai/dsh-client-ui-settings",
35
+ "@deepseek-ai/dsh-client-modules"
36
+ ],
37
+ "platform": "web"
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsc",
42
+ "prepare": "tsc",
43
+ "clean": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\""
44
+ },
45
+ "peerDependencies": {
46
+ "@deepseek-ai/dsh-tools": ">=0.1.0-rc.6"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.0.0",
50
+ "typescript": "^5.0.0"
51
+ },
52
+ "packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621",
53
+ "dependencies": {
54
+ "@deepseek-ai/schemastery": "^3.18.1"
55
+ }
56
+ }
@@ -0,0 +1,249 @@
1
+ """dsh-gsv-tts 真流式 API 服务
2
+
3
+ 修复 personal_api.py /tts/stream 的假流式问题:
4
+ - 原实现用 list(tts.infer_stream(...)) 一次性消费完再逐块发——首包延迟≈总耗时
5
+ - 本端点用 infer_stream_async 逐块 yield,首块到达即推送
6
+
7
+ 路径处理(可移植,无机器硬编码):
8
+ - 仓库根目录(本脚本位于 <repo>/API/ 下)优先,取仓库源码 gsv_tts
9
+ - 自动探测 --target 安装的 site-packages(同级或仓库内)并追加
10
+ - 系统 site-packages 保持在默认优先级(在 --target 之前),避免依赖版本冲突
11
+ - dsh_start_wrapper.py(setup.ts 生成)也会注入路径,二者互不干扰
12
+
13
+ v2.1 变更:
14
+ - lifespan 替代已废弃的 @app.on_event("startup")
15
+ - 增加 CORS 头(便于浏览器跨源播放/调试)
16
+ - prompt_text 为空时尝试 ASR 自动转写(能力探测,不可用时返回明确错误)
17
+ - done 事件 total_duration 按逐块采样数累加(真实秒数;注意 clip.audio_len_s 是跨块累计值,不能直接求和)
18
+ """
19
+ import os
20
+ import sys
21
+ import json
22
+ import base64
23
+ import asyncio
24
+ import logging
25
+ from contextlib import asynccontextmanager
26
+ from pathlib import Path
27
+ from typing import Optional
28
+
29
+ os.environ['GSV_DISABLE_CUDA_GRAPH'] = '1'
30
+
31
+ # ─── 路径注入(可移植)───
32
+ # 仓库源码优先(支持 GSV_DISABLE_CUDA_GRAPH 环境变量,PyPI 版不支持)
33
+ repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34
+ sys.path.insert(0, repo_root)
35
+ # 自动探测 --target 安装的依赖目录(同级 site-packages 或仓库内 site-packages)
36
+ for candidate in (
37
+ os.path.join(os.path.dirname(repo_root), 'site-packages'), # D:\GSV\site-packages 式布局
38
+ os.path.join(repo_root, 'site-packages'), # 仓库内布局
39
+ ):
40
+ if os.path.isdir(candidate) and candidate not in sys.path:
41
+ sys.path.append(candidate)
42
+
43
+ try:
44
+ import transformers.utils.import_utils
45
+ import transformers.modeling_utils
46
+ transformers.utils.import_utils.check_torch_load_is_safe = lambda: None
47
+ transformers.modeling_utils.check_torch_load_is_safe = lambda: None
48
+ except Exception:
49
+ pass
50
+
51
+ from fastapi import FastAPI, HTTPException
52
+ from fastapi.middleware.cors import CORSMiddleware
53
+ from fastapi.responses import StreamingResponse
54
+ from pydantic import BaseModel
55
+ from gsv_tts import TTS
56
+
57
+ logging.basicConfig(level=logging.INFO)
58
+ logger = logging.getLogger("dsh_stream_api")
59
+
60
+ # 预热用的默认模型文件名(缺失时仅告警,不影响启动)
61
+ DEFAULT_GPT_CKPT = "s1v3.ckpt"
62
+ DEFAULT_SOVITS_PTH = "s2Gv2ProPlus.pth"
63
+ EXAMPLE_SPEAKER = "laffey.mp3"
64
+ EXAMPLE_PROMPT = "AnAn.ogg"
65
+
66
+ tts: Optional[TTS] = None
67
+ models_dir_global: Optional[Path] = None
68
+
69
+
70
+ class StreamRequest(BaseModel):
71
+ text: str
72
+ speaker_audio: str
73
+ prompt_audio: str
74
+ prompt_text: str = ""
75
+ speed: float = 1.0
76
+ stream_chunk: int = 25
77
+ boost_first_chunk: bool = True
78
+ stream_mode: str = "token"
79
+
80
+
81
+ @asynccontextmanager
82
+ async def lifespan(_: FastAPI):
83
+ global tts, models_dir_global
84
+ logger.info("正在加载 TTS 模型...")
85
+ tts = TTS(models_dir=models_dir_global, sovits_cache=[50])
86
+ # 预热:加载默认 GPT/SoVITS 模型 + 示例音频缓存,避免首请求延迟
87
+ default_gpt = str(models_dir_global / DEFAULT_GPT_CKPT)
88
+ default_sovits = str(models_dir_global / DEFAULT_SOVITS_PTH)
89
+ example_spk = str(models_dir_global.parent / "examples" / EXAMPLE_SPEAKER)
90
+ example_prompt = str(models_dir_global.parent / "examples" / EXAMPLE_PROMPT)
91
+
92
+ def _preload():
93
+ if hasattr(tts, 'load_gpt_model') and os.path.exists(default_gpt):
94
+ try:
95
+ tts.load_gpt_model(default_gpt)
96
+ except Exception as e:
97
+ logger.warning(f"预加载 GPT 失败: {e}")
98
+ if hasattr(tts, 'load_sovits_model') and os.path.exists(default_sovits):
99
+ try:
100
+ tts.load_sovits_model(default_sovits)
101
+ except Exception as e:
102
+ logger.warning(f"预加载 SoVITS 失败: {e}")
103
+ if os.path.exists(example_spk):
104
+ try:
105
+ tts.cache_spk_audio(example_spk)
106
+ except Exception as e:
107
+ logger.warning(f"预缓存 speaker 失败: {e}")
108
+ if os.path.exists(example_prompt):
109
+ try:
110
+ tts.cache_prompt_audio(example_prompt, "ちが……ちがう。レイア、貴様は間違っている。")
111
+ except Exception as e:
112
+ logger.warning(f"预缓存 prompt 失败: {e}")
113
+
114
+ await asyncio.get_running_loop().run_in_executor(None, _preload)
115
+ logger.info("TTS 模型加载完成(含预热)!")
116
+ try:
117
+ yield
118
+ finally:
119
+ logger.info("TTS 服务关闭")
120
+
121
+
122
+ app = FastAPI(title="DSH-GSV-TTS Stream API", lifespan=lifespan)
123
+
124
+ # 允许跨源访问(浏览器跨源播放/调试需要)
125
+ app.add_middleware(
126
+ CORSMiddleware,
127
+ allow_origins=["*"],
128
+ allow_methods=["*"],
129
+ allow_headers=["*"],
130
+ )
131
+
132
+
133
+ def _transcribe_prompt(tts_obj, audio_path: str) -> Optional[str]:
134
+ """对提示音频做 ASR 转写。能力探测:gsv_tts 可能以不同名字/签名暴露。
135
+
136
+ 返回转写文本;引擎不支持 ASR 时返回 None(由调用方给出明确错误)。
137
+ """
138
+ candidates = [
139
+ getattr(tts_obj, "asr", None),
140
+ getattr(tts_obj, "recognize", None),
141
+ getattr(tts_obj, "transcribe", None),
142
+ ]
143
+ for fn in candidates:
144
+ if not callable(fn):
145
+ continue
146
+ try:
147
+ result = fn(audio_path)
148
+ if isinstance(result, (list, tuple)) and result:
149
+ result = result[0]
150
+ if isinstance(result, dict):
151
+ result = result.get("text") or result.get("transcript") or result.get("result")
152
+ if isinstance(result, str) and result.strip():
153
+ return result.strip()
154
+ except Exception as e:
155
+ logger.warning(f"ASR 尝试失败({getattr(fn, '__name__', '?')}): {e}")
156
+ return None
157
+
158
+
159
+ @app.get("/")
160
+ async def root():
161
+ return {"message": "DSH-GSV-TTS Stream API", "endpoints": {"/tts/stream": "POST 真流式 SSE"}}
162
+
163
+
164
+ @app.post("/tts/stream")
165
+ async def tts_stream(request: StreamRequest):
166
+ """真流式 TTS:用 infer_stream_async 逐块 yield,首块到达即推送"""
167
+ prompt_text = request.prompt_text
168
+ if not prompt_text:
169
+ # 留空时尝试 ASR 自动转写(能力探测)
170
+ if tts is None:
171
+ raise HTTPException(status_code=503, detail="TTS 模型未加载")
172
+ try:
173
+ prompt_text = await asyncio.to_thread(_transcribe_prompt, tts, request.prompt_audio)
174
+ except Exception as e:
175
+ logger.warning(f"ASR 调用异常: {e}")
176
+ prompt_text = None
177
+ if not prompt_text:
178
+ raise HTTPException(
179
+ status_code=400,
180
+ detail="prompt_text 不能为空,且当前引擎不支持 ASR 自动转写(请在音色预设中填写 promptText)",
181
+ )
182
+ logger.info(f"ASR 转写结果: {prompt_text}")
183
+
184
+ async def generate():
185
+ try:
186
+ total_samples = 0
187
+ sample_rate = 32000
188
+ chunk_count = 0
189
+ prev_duration = 0.0
190
+ chunk_idx = 0
191
+ async for clip in tts.infer_stream_async(
192
+ spk_audio_path=request.speaker_audio,
193
+ prompt_audio_path=request.prompt_audio,
194
+ prompt_audio_text=prompt_text,
195
+ text=request.text,
196
+ stream_mode=request.stream_mode,
197
+ stream_chunk=request.stream_chunk,
198
+ boost_first_chunk=request.boost_first_chunk,
199
+ speed=request.speed,
200
+ debug=False,
201
+ ):
202
+ audio_bytes = clip.audio_data.tobytes()
203
+ audio_b64 = base64.b64encode(audio_bytes).decode('utf-8')
204
+ sample_rate = int(clip.samplerate)
205
+ # audio_len_s 是累计值(跨块累加),逐块差值才是本块时长
206
+ cumulative = float(getattr(clip, "audio_len_s", 0.0) or 0.0)
207
+ chunk_duration = max(cumulative - prev_duration, 0.0)
208
+ prev_duration = cumulative
209
+ total_samples += len(clip.audio_data)
210
+ chunk_count += 1
211
+
212
+ chunk_data = {
213
+ "audio": audio_b64,
214
+ "sample_rate": sample_rate,
215
+ "duration": round(chunk_duration, 4),
216
+ "chunk_idx": chunk_idx,
217
+ }
218
+ chunk_idx += 1
219
+ yield f"event: audio\ndata: {json.dumps(chunk_data, ensure_ascii=False)}\n\n"
220
+
221
+ if chunk_count == 0:
222
+ yield f"event: error\ndata: {json.dumps({'error': '未收到任何音频块'}, ensure_ascii=False)}\n\n"
223
+ return
224
+ yield f"event: done\ndata: {json.dumps({'total_duration': round(total_samples / sample_rate, 3)}, ensure_ascii=False)}\n\n"
225
+
226
+ except Exception as e:
227
+ logger.error(f"流式推理错误: {e}")
228
+ yield f"event: error\ndata: {json.dumps({'error': str(e)}, ensure_ascii=False)}\n\n"
229
+
230
+ return StreamingResponse(
231
+ generate(),
232
+ media_type="text/event-stream",
233
+ headers={
234
+ "Cache-Control": "no-cache",
235
+ "Connection": "keep-alive",
236
+ "X-Accel-Buffering": "no",
237
+ },
238
+ )
239
+
240
+
241
+ if __name__ == "__main__":
242
+ import argparse
243
+ import uvicorn
244
+ parser = argparse.ArgumentParser()
245
+ parser.add_argument("--models_dir", type=str, default="models")
246
+ parser.add_argument("-p", "--port", type=int, default=9880)
247
+ args = parser.parse_args()
248
+ models_dir_global = Path(args.models_dir)
249
+ uvicorn.run(app, host="0.0.0.0", port=args.port)