mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Merge pull request #3366 from xinnan-tech/feat-tts-alibl
Feat tts alibl
This commit is contained in:
commit
6afc54a17d
6 changed files with 123 additions and 17 deletions
|
|
@ -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://<WorkspaceId>.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
|
||||
4. 新加坡业务空间填写 wss://<WorkspaceId>.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
|
||||
5. 将 <WorkspaceId> 替换为真实业务空间 ID;仅支持阿里云官方 WSS 推理地址
|
||||
6. 支持 CosyVoice 流式合成及音量、语速、音调配置'
|
||||
WHERE `id` = 'TTS_AliBLStreamTTS';
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -1139,6 +1139,8 @@ TTS:
|
|||
# cosyvoice-v3和部分音色需要申请开通
|
||||
type: alibl_stream
|
||||
api_key: 你的api_key
|
||||
# 默认兼容旧地址;业务空间请替换为 wss://<WorkspaceId>.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/
|
||||
|
|
|
|||
|
|
@ -7,10 +7,10 @@ import asyncio
|
|||
import traceback
|
||||
import websockets
|
||||
|
||||
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.providers.tts.base import TTSProviderBase
|
||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
||||
|
||||
|
|
@ -33,10 +33,10 @@ class TTSProvider(TTSProviderBase):
|
|||
self.api_key = config.get("api_key")
|
||||
if not self.api_key:
|
||||
raise ValueError("api_key is required for CosyVoice TTS")
|
||||
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
|
||||
|
|
@ -89,6 +89,7 @@ class TTSProvider(TTSProviderBase):
|
|||
ping_interval=30,
|
||||
ping_timeout=10,
|
||||
close_timeout=10,
|
||||
**self.ws_connect_options,
|
||||
)
|
||||
|
||||
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
|
||||
|
|
@ -356,18 +357,15 @@ 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)
|
||||
if tts_text:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"句子语音生成成功: {tts_text}"
|
||||
)
|
||||
self.tts_audio_queue.put(
|
||||
(SentenceType.FIRST, [], tts_text)
|
||||
)
|
||||
self.clear_tts_text(self.conn.sentence_id)
|
||||
output = data.get("payload", {}).get("output", {})
|
||||
if output.get("type") == "sentence-begin":
|
||||
original_text = output.get("original_text")
|
||||
self.tts_text = self._restore_original_text(original_text)
|
||||
logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
|
||||
self.tts_audio_queue.put((SentenceType.FIRST, [], self.tts_text))
|
||||
elif output.get("type") == "sentence-end":
|
||||
logger.bind(tag=TAG).info(f"句子语音生成成功: {self.tts_text}")
|
||||
elif event == "task-finished":
|
||||
logger.bind(tag=TAG).debug("TTS任务完成~")
|
||||
self.activate_session = False
|
||||
|
|
@ -444,6 +442,7 @@ class TTSProvider(TTSProviderBase):
|
|||
ping_timeout=10,
|
||||
close_timeout=10,
|
||||
max_size=10 * 1024 * 1024,
|
||||
**self.ws_connect_options,
|
||||
)
|
||||
|
||||
try:
|
||||
|
|
@ -556,4 +555,4 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
||||
return []
|
||||
return []
|
||||
|
|
|
|||
48
main/xiaozhi-server/core/utils/alibl_endpoint.py
Normal file
48
main/xiaozhi-server/core/utils/alibl_endpoint.py
Normal file
|
|
@ -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
|
||||
|
|
@ -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())
|
||||
asyncio.run(main())
|
||||
|
|
|
|||
Loading…
Reference in a new issue