diff --git a/main/manager-api/src/main/resources/db/changelog/202609021000.sql b/main/manager-api/src/main/resources/db/changelog/202609021000.sql new file mode 100644 index 000000000..0a72b695e --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202609021000.sql @@ -0,0 +1,42 @@ +-- 阿里百炼流式 TTS 支持业务空间 WebSocket 地址 + +UPDATE `ai_model_provider` +SET `fields` = JSON_ARRAY( + JSON_OBJECT('key', 'api_key', 'type', 'string', 'label', 'API密钥'), + JSON_OBJECT( + 'key', 'ws_url', + 'type', 'string', + 'label', 'WebSocket地址(含Workspace ID)', + 'default', 'wss://dashscope.aliyuncs.com/api-ws/v1/inference/' + ), + JSON_OBJECT('key', 'output_dir', 'type', 'string', 'label', '输出目录'), + JSON_OBJECT('key', 'model', 'type', 'string', 'label', '模型'), + JSON_OBJECT('key', 'voice', 'type', 'string', 'label', '音色'), + JSON_OBJECT('key', 'format', 'type', 'string', 'label', '音频格式'), + JSON_OBJECT('key', 'sample_rate', 'type', 'number', 'label', '采样率'), + JSON_OBJECT('key', 'volume', 'type', 'number', 'label', '音量'), + JSON_OBJECT('key', 'rate', 'type', 'number', 'label', '语速'), + JSON_OBJECT('key', 'pitch', 'type', 'number', 'label', '音调') +) +WHERE `id` = 'SYSTEM_TTS_AliBLStreamTTS'; + +UPDATE `ai_model_config` +SET `config_json` = JSON_SET( + `config_json`, + '$.ws_url', + COALESCE( + NULLIF(JSON_UNQUOTE(JSON_EXTRACT(`config_json`, '$.ws_url')), ''), + 'wss://dashscope.aliyuncs.com/api-ws/v1/inference/' + ) +) +WHERE `id` = 'TTS_AliBLStreamTTS'; + +UPDATE `ai_model_config` +SET `remark` = '阿里百炼流式 TTS 配置说明: +1. API密钥填写当前业务空间可用的 DashScope API Key +2. 公有模式可使用 wss://dashscope.aliyuncs.com/api-ws/v1/inference/ +3. 华北2(北京)业务空间填写 wss://.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference +4. 新加坡业务空间填写 wss://.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference +5. 将 替换为真实业务空间 ID;仅支持阿里云官方 WSS 推理地址 +6. 支持 CosyVoice 流式合成及音量、语速、音调配置' +WHERE `id` = 'TTS_AliBLStreamTTS'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 17d4fb741..71c7c4bd6 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -739,3 +739,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202608131030.sql + - changeSet: + id: 202609021000 + author: JacobNg1 + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202609021000.sql diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 85435bb8a..eefb85db0 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -1139,6 +1139,8 @@ TTS: # cosyvoice-v3和部分音色需要申请开通 type: alibl_stream api_key: 你的api_key + # 默认兼容旧地址;业务空间请替换为 wss://.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference + ws_url: wss://dashscope.aliyuncs.com/api-ws/v1/inference/ model: "cosyvoice-v2" voice: "longcheng_v2" output_dir: tmp/ diff --git a/main/xiaozhi-server/core/providers/tts/alibl_stream.py b/main/xiaozhi-server/core/providers/tts/alibl_stream.py index bd0d2f839..65477bd3a 100644 --- a/main/xiaozhi-server/core/providers/tts/alibl_stream.py +++ b/main/xiaozhi-server/core/providers/tts/alibl_stream.py @@ -11,6 +11,8 @@ from asyncio import Task from typing import Callable, Any from config.logger import setup_logging from core.utils.tts import MarkdownCleaner +from core.utils.alibl_endpoint import build_ws_connect_options, resolve_ws_url +from core.utils.alibl_event import extract_sentence_start_text from core.providers.tts.base import TTSProviderBase from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType @@ -36,11 +38,13 @@ class TTSProvider(TTSProviderBase): self.report_on_last = True # WebSocket配置 - self.ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/" + self.ws_url = resolve_ws_url(config.get("ws_url")) + self.ws_connect_options = build_ws_connect_options(self.tts_timeout) self.ws = None self._monitor_task = None self.activate_session = False self.last_active_time = None + self._legacy_subtitle_sent = False # 模型和音色配置 self.model = config.get("model", "cosyvoice-v2") @@ -89,6 +93,7 @@ class TTSProvider(TTSProviderBase): ping_interval=30, ping_timeout=10, close_timeout=10, + **self.ws_connect_options, ) logger.bind(tag=TAG).debug("WebSocket连接建立成功") @@ -129,6 +134,9 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.FIRST: # 重置流式处理状态 self.reset_stream_state() + self.current_sentence_id = message.sentence_id + self.tts_audio_first_sentence = True + self._legacy_subtitle_sent = False # 初始化会话 try: if not getattr(self.conn, "sentence_id", None): @@ -356,25 +364,31 @@ class TTSProvider(TTSProviderBase): if event == "task-started": logger.bind(tag=TAG).debug("TTS任务启动成功~") - self.tts_audio_queue.put((SentenceType.FIRST, [], None)) elif event == "result-generated": - # 发送缓存的数据 - tts_text = self.get_tts_text(self.conn.sentence_id) + output = data.get("payload", {}).get("output", {}) + output_type = output.get("type") + tts_text = extract_sentence_start_text(data) + if tts_text: + tts_text = self._restore_original_text(tts_text) + elif not output_type and not self._legacy_subtitle_sent: + tts_text = self.get_tts_text(task_id) + self._legacy_subtitle_sent = bool(tts_text) if tts_text: logger.bind(tag=TAG).info( f"句子语音生成成功: {tts_text}" ) self.tts_audio_queue.put( - (SentenceType.FIRST, [], tts_text) + (SentenceType.FIRST, [], tts_text, task_id) ) - self.clear_tts_text(self.conn.sentence_id) elif event == "task-finished": logger.bind(tag=TAG).debug("TTS任务完成~") self.activate_session = False + self.clear_tts_text(task_id) self._process_before_stop_play_files() elif event == "task-failed": error_code = header.get("error_code", "unknown") error_message = header.get("error_message", "未知错误") + self.clear_tts_text(task_id) logger.bind(tag=TAG).error( f"TTS任务失败: {error_code} - {error_message}" ) @@ -403,6 +417,7 @@ class TTSProvider(TTSProviderBase): self.ws = None # 监听任务退出时清理引用 finally: + self.clear_tts_text(getattr(self, "current_sentence_id", None)) self.activate_session = False self._monitor_task = None @@ -444,6 +459,7 @@ class TTSProvider(TTSProviderBase): ping_timeout=10, close_timeout=10, max_size=10 * 1024 * 1024, + **self.ws_connect_options, ) try: @@ -556,4 +572,4 @@ class TTSProvider(TTSProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") - return [] \ No newline at end of file + return [] diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 2ff779c03..586b32635 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -439,9 +439,9 @@ class TTSProviderBase(ABC): if sentence_type is not SentenceType.MIDDLE: if self.report_on_last: # 累积模式:适用于全程只有一个语音流的TTS(如seed-tts-2.0) - # FIRST时只记录文本,音频持续累积,仅在LAST时统一上报 + # FIRST时累积文本,音频持续累积,仅在LAST时统一上报 if text: - enqueue_text = text + enqueue_text = f"{enqueue_text or ''}{text}" if sentence_type == SentenceType.LAST: enqueue_tts_report(self.conn, enqueue_text, enqueue_audio) enqueue_audio = [] diff --git a/main/xiaozhi-server/core/utils/alibl_endpoint.py b/main/xiaozhi-server/core/utils/alibl_endpoint.py new file mode 100644 index 000000000..ef13bf065 --- /dev/null +++ b/main/xiaozhi-server/core/utils/alibl_endpoint.py @@ -0,0 +1,48 @@ +import re +from urllib.parse import urlsplit + + +DEFAULT_WS_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/" +INFERENCE_PATH = "/api-ws/v1/inference" +HOSTNAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$") +HAPPY_EYEBALLS_DELAY = 0.25 + + +def build_ws_connect_options(open_timeout): + return { + "open_timeout": open_timeout, + "happy_eyeballs_delay": HAPPY_EYEBALLS_DELAY, + "interleave": 1, + } + + +def resolve_ws_url(value): + ws_url = str(value or DEFAULT_WS_URL).strip() + parsed = urlsplit(ws_url) + hostname = (parsed.hostname or "").lower() + is_dashscope = hostname in { + "dashscope.aliyuncs.com", + "dashscope-intl.aliyuncs.com", + } + is_workspace = hostname.endswith(".maas.aliyuncs.com") + + try: + port = parsed.port + except ValueError: + port = -1 + + if ( + parsed.scheme.lower() != "wss" + or not HOSTNAME_PATTERN.fullmatch(hostname) + or not (is_dashscope or is_workspace) + or parsed.path.rstrip("/") != INFERENCE_PATH + or parsed.query + or parsed.fragment + or parsed.username + or parsed.password + or port not in {None, 443} + ): + raise ValueError( + "ws_url must be an official Alibaba Cloud WSS inference endpoint" + ) + return ws_url diff --git a/main/xiaozhi-server/core/utils/alibl_event.py b/main/xiaozhi-server/core/utils/alibl_event.py new file mode 100644 index 000000000..d0d345a2f --- /dev/null +++ b/main/xiaozhi-server/core/utils/alibl_event.py @@ -0,0 +1,6 @@ +def extract_sentence_start_text(data): + output = data.get("payload", {}).get("output", {}) + if output.get("type") != "sentence-begin": + return None + text = output.get("original_text") + return text if isinstance(text, str) and text.strip() else None diff --git a/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py b/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py index 515f2ec6d..7496b22b1 100644 --- a/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py +++ b/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py @@ -11,6 +11,10 @@ import asyncio from urllib.parse import urlparse, urlencode from tabulate import tabulate from config.settings import load_config +from core.utils.alibl_endpoint import ( + build_ws_connect_options as build_alibl_ws_connect_options, + resolve_ws_url as resolve_alibl_ws_url, +) description = "流式TTS语音合成首词耗时测试" class StreamTTSPerformanceTester: @@ -108,8 +112,11 @@ class StreamTTSPerformanceTester: voice = tts_config.get("voice", "longxiaochun_v2") format_type = tts_config.get("format", "pcm") sample_rate = int(tts_config.get("sample_rate", "24000")) + connect_options = build_alibl_ws_connect_options( + float(self.config.get("tts_timeout", 15)) + ) - ws_url = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/" + ws_url = resolve_alibl_ws_url(tts_config.get("ws_url")) headers = { "Authorization": f"Bearer {api_key}", "X-DashScope-DataInspection": "enable", @@ -124,6 +131,7 @@ class StreamTTSPerformanceTester: ping_timeout=10, close_timeout=10, max_size=10 * 1024 * 1024, + **connect_options, ) as ws: session_id = uuid.uuid4().hex @@ -669,4 +677,4 @@ async def main(): if __name__ == "__main__": import asyncio - asyncio.run(main()) \ No newline at end of file + asyncio.run(main()) diff --git a/main/xiaozhi-server/tests/test_alibl_workspace_tts.py b/main/xiaozhi-server/tests/test_alibl_workspace_tts.py new file mode 100644 index 000000000..ee636f081 --- /dev/null +++ b/main/xiaozhi-server/tests/test_alibl_workspace_tts.py @@ -0,0 +1,93 @@ +import sys +import unittest +from pathlib import Path + + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from core.utils.alibl_endpoint import ( + DEFAULT_WS_URL, + build_ws_connect_options, + resolve_ws_url, +) +from core.utils.alibl_event import extract_sentence_start_text + + +class AliBLStreamEventTests(unittest.TestCase): + def test_sentence_begin_returns_original_text(self): + event = { + "payload": { + "output": { + "type": "sentence-begin", + "original_text": "第一句。", + } + } + } + self.assertEqual(extract_sentence_start_text(event), "第一句。") + + def test_non_begin_events_do_not_return_subtitles(self): + for event_type in ("sentence-synthesis", "sentence-end"): + event = { + "payload": { + "output": { + "type": event_type, + "original_text": "第一句。", + } + } + } + self.assertIsNone(extract_sentence_start_text(event)) + + def test_empty_sentence_text_is_ignored(self): + event = { + "payload": { + "output": {"type": "sentence-begin", "original_text": " "} + } + } + self.assertIsNone(extract_sentence_start_text(event)) + + +class AliBLWorkspaceEndpointTests(unittest.TestCase): + def test_connection_uses_happy_eyeballs(self): + self.assertEqual( + build_ws_connect_options(15), + { + "open_timeout": 15, + "happy_eyeballs_delay": 0.25, + "interleave": 1, + }, + ) + + def test_default_endpoint_remains_backward_compatible(self): + self.assertEqual(resolve_ws_url(None), DEFAULT_WS_URL) + + def test_beijing_workspace_endpoint_is_supported(self): + endpoint = ( + "wss://ws-123.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference" + ) + self.assertEqual(resolve_ws_url(endpoint), endpoint) + + def test_singapore_workspace_endpoint_is_supported(self): + endpoint = ( + "wss://ws-123.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference" + ) + self.assertEqual(resolve_ws_url(endpoint), endpoint) + + def test_non_alibaba_endpoint_is_rejected(self): + with self.assertRaises(ValueError): + resolve_ws_url("wss://example.com/api-ws/v1/inference") + + def test_insecure_endpoint_is_rejected(self): + with self.assertRaises(ValueError): + resolve_ws_url( + "ws://ws-123.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference" + ) + + def test_unresolved_workspace_placeholder_is_rejected(self): + with self.assertRaises(ValueError): + resolve_ws_url( + "wss://.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference" + ) + + +if __name__ == "__main__": + unittest.main()