Compare commits

...

3 Commits

Author SHA1 Message Date
用户CI Test ba91361b64 fix: CosyVoice 音色名 v3 后缀修复(418错误)
根因:cosyvoice-v3.5-plus 模型要求系统音色使用 _v3 后缀命名
(如 longxiaochun_v3),旧名 longxiaochun 导致引擎返回 418 音色不支持。

修复:
- config.py: 默认音色 longxiaochun → longxiaochun_v3
- preset_voices.py: 8个预置音色全部加 _v3 后缀
- cosyvoice_service.py: docstring 示例更新
- 相关测试文件 voice_id 全部同步更新
- 188个单元测试全绿
2026-07-11 01:04:10 +08:00
用户CI Test 1d2aaad52f fix: PR #212 P0+P1 问题修复
CI/CD Pipeline / Validate Code Quality And Tests (pull_request) Failing after 13s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 2m46s
CI/CD Pipeline / Build & Push Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Build Production Runtime Images (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
- P0: 修复 process_synthesis_failure docstring 语法错误(三引号位置错误)
- P1: _resynthesize_and_complete 补上 speed/volume 参数传递(从metadata读取)
- P1: _poll_segment_tasks 适配新同步接口,缺失分段重新同步合成而非轮询
  - 移除 time 依赖(不再轮询)
  - 并发重新合成缺失 audio_url 的分段
  - 已有 audio_url 的分段直接复用
- 新增 1 个分段复用测试用例
2026-07-10 22:40:20 +08:00
用户CI Test 506eae98f1 fix: CosyVoice全量重写 - 适配DashScope百炼API
CI/CD Pipeline / Validate Code Quality And Tests (pull_request) Failing after 4s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 4m18s
CI/CD Pipeline / Build & Push Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Build Production Runtime Images (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
- 配置更新:base_url改为api/v1,model改为cosyvoice-v3.5-plus,新增clone_model=voice-enrollment
- 音色克隆:适配customization接口 + voice-enrollment模型 + create_voice action
- 状态查询:适配同路径query_voice action(POST),返回DEPLOYING/OK/UNDEPLOYED
- 语音合成:适配SpeechSynthesizer非流式同步接口,直接返回audio_url
- 新增audio_url_signer钩子:对私有bucket音频URL预签名(slash_safe=True)
- voice_clone workflow适配:voice_id替代task_id,status=OK标记ready
- tts_job workflow适配:同步接口直接返回,无task_id时自动重新合成兜底
- API端+Worker端依赖注入OSS预签名函数
- 单元测试:36个service测试 + 18个workflow测试,全部通过
2026-07-10 22:17:07 +08:00
12 changed files with 973 additions and 943 deletions
+13 -2
View File
@@ -201,7 +201,18 @@ def get_voice_clone_profile_repository(
def get_cosyvoice_service():
"""Provide the CosyVoice service instance."""
"""Provide the CosyVoice service instance.
注入 OSS 音频URL预签名函数,确保私有bucket下的参考音频
能被 CosyVoice 服务器下载。
"""
from app.core.storage import get_storage_service
from packages.application.cosyvoice_service import CosyVoiceService
return CosyVoiceService()
storage = get_storage_service()
def _sign_audio_url(url: str) -> str:
"""对音频URL做预签名,私有bucket下 CosyVoice 服务器才能下载."""
return storage.get_download_url(url, expires_seconds=86400)
return CosyVoiceService(audio_url_signer=_sign_audio_url)
+4 -1
View File
@@ -16,6 +16,7 @@ from packages.application.cosyvoice_service import (
CosyVoiceTimeoutError,
)
from packages.application.voice_clone.workflow import VoiceCloneWorkflowService
from video_processing.oss_helpers import get_signed_download_url
logger = logging.getLogger(__name__)
@@ -48,7 +49,9 @@ def process_voice_clone(self: Task, profile_id: str) -> dict:
repo = SQLAlchemyVoiceCloneProfileRepository(session)
workflow = VoiceCloneWorkflowService(
repository=repo,
cosyvoice_service=CosyVoiceService(),
cosyvoice_service=CosyVoiceService(
audio_url_signer=lambda url: get_signed_download_url(url, expires_seconds=86400) or url
),
)
updated_profile = workflow.poll_and_process_clone(profile_id, timeout=300)
+288 -313
View File
@@ -1,11 +1,13 @@
"""CosyVoice 语音服务 — Phase 3.
"""CosyVoice 语音服务 — 适配阿里云百炼 DashScope API.
封装阿里云 CosyVoice 语音合成 API,提供:
封装阿里云百炼 CosyVoice 语音合成 API,提供:
- 预置音色列表查询
- 音色克隆(提交任务 + 轮询状态)
- 语音合成(提交任务 + 轮询状态
- 音色克隆(提交 + 轮询状态)
- 语音合成(同步非流式调用
API 文档: https://help.aliyun.com/zh/model-studio/cosyvoice
API 文档:
- 音色克隆: https://help.aliyun.com/document_detail/3027318.html
- 语音合成: https://help.aliyun.com/zh/model-studio/cosyvoice-tts-http-api
"""
from __future__ import annotations
@@ -60,33 +62,34 @@ class SynthesizeResult:
class CosyVoiceService:
"""CosyVoice 语音服务
"""CosyVoice 语音服务.
封装阿里云 CosyVoice API,提供音色克隆和语音合成功能
支持同步和异步两种模式:
- 同步:API 直接返回结果
- 异步:API 返回 task_id,需要轮询状态
封装阿里云百炼 CosyVoice API,提供音色克隆和语音合成功能.
接口总览:
- 音色克隆: POST /services/audio/tts/customization (model=voice-enrollment)
- action=create_voice: 创建克隆音色,返回 voice_id(状态 DEPLOYING
- action=query_voice: 查询音色状态(DEPLOYING / OK / UNDEPLOYED
- 语音合成: POST /services/audio/tts/SpeechSynthesizer (model=cosyvoice-v3.5-plus)
- 非流式: 同步返回音频 URL
使用示例:
service = CosyVoiceService(
api_key="your-api-key",
base_url="https://dashscope.aliyuncs.com/api/v1/services/aigc/text2audio",
model="cosyvoice-v1",
base_url="https://dashscope.aliyuncs.com/api/v1",
model="cosyvoice-v3.5-plus",
)
# 获取预置音色
voices = service.list_preset_voices()
# 音色克隆
result = service.clone_voice(audio_url="https://example.com/audio.mp3")
# 语音合成
result = service.synthesize_speech(text="你好世界", voice_id="longxiaochun")
result = service.synthesize_speech(text="你好世界", voice_id="longxiaochun_v3")
"""
# 轮询配置
POLL_INTERVAL = 2.0 # 秒
MAX_POLL_ATTEMPTS = 60 # 最多轮询 60 次(2分钟)
# 音色状态轮询配置
CLONE_POLL_INTERVAL = 5.0 # 秒
CLONE_MAX_POLL_ATTEMPTS = 60 # 最多轮询 60 次(5分钟)
# 重试配置
MAX_RETRIES = 3
@@ -97,24 +100,34 @@ class CosyVoiceService:
api_key: str = "",
base_url: str = "",
model: str = "",
clone_model: str = "",
http_client: Optional[httpx.Client] = None,
audio_url_signer: Optional[callable] = None,
) -> None:
"""初始化 CosyVoice 服务
"""初始化 CosyVoice 服务.
Args:
api_key: CosyVoice API Key,为空时从配置读取
base_url: CosyVoice API Base URL,为空时从配置读取
model: CosyVoice 模型名称,为空时从配置读取
api_key: DashScope API Key,为空时从配置读取
base_url: DashScope API Base URL,为空时从配置读取
model: 语音合成模型名称,为空时从配置读取
clone_model: 音色克隆模型名称,为空时从配置读取
http_client: 可选的 HTTP 客户端(用于测试注入)
audio_url_signer: 可选的音频URL预签名函数,签名式 fn(url) -> str.
用于私有 bucket 下,将裸 URL 转为预签名 URL,
确保 CosyVoice 服务器能下载参考音频.
"""
settings = get_shared_settings()
self._api_key = api_key or settings.cosyvoice_api_key
self._base_url = base_url or settings.cosyvoice_base_url
self._model = model or settings.cosyvoice_model
self._clone_model = clone_model or getattr(
settings, "cosyvoice_clone_model", "voice-enrollment"
)
self._audio_url_signer = audio_url_signer
self._client = http_client or httpx.Client(
timeout=httpx.Timeout(30.0, connect=10.0),
timeout=httpx.Timeout(60.0, connect=10.0),
)
self._owns_client = http_client is None
@@ -132,7 +145,7 @@ class CosyVoiceService:
# ── 预置音色 ─────────────────────────────────────────
def list_preset_voices(self) -> list[PresetVoice]:
"""获取预置音色列表
"""获取预置音色列表.
Returns:
预置音色列表
@@ -146,20 +159,22 @@ class CosyVoiceService:
audio_url: str,
voice_name: str = "",
language: str = "zh-CN",
target_model: str = "",
) -> dict:
"""提交音色克隆任务(非阻塞)
"""提交音色克隆任务(非阻塞).
只提交任务到 CosyVoice API,不轮询结果。
返回的 dict 包含 task_id(异步)或 voice_id(同步)。
调用百炼 voice-enrollment API 创建克隆音色.
创建后音色状态为 DEPLOYING,需通过 query_voice_status 轮询直到 OK.
Args:
audio_url: 参考音频 URL
voice_name: 音色名称(可选
language: 语言代码
audio_url: 参考音频 URL(必须公网可访问)
voice_name: 音色名称前缀(字母数字,最多10字符
language: 语言代码zh-CN 会转换为 zh
target_model: 目标合成模型,默认使用当前 model
Returns:
dict: {"task_id": str, "voice_id": str, "request_id": str}
task_id 和 voice_id 至少有一个非空
dict: {"voice_id": str, "status": str, "request_id": str}
voice_id 非空,status 通常为 DEPLOYING
Raises:
CosyVoiceError: API 调用失败
@@ -171,48 +186,68 @@ class CosyVoiceService:
if not self._api_key:
raise CosyVoiceAuthError("CosyVoice API Key 未配置")
# voice_name 作为 prefix,限制字母数字,最多10字符
# 不符合要求的做清洗
prefix = self._sanitize_prefix(voice_name) if voice_name else "clone"
# 语言转换:zh-CN → zh,保留 ISO 639-1 格式
lang_code = language.split("-")[0].lower() if language else "zh"
target = target_model or self._model
# 如果配置了 audio_url_signer,对音频URL做预签名
# (私有 bucket 下 CosyVoice 服务器无法直接访问裸 URL)
signed_audio_url = audio_url
if self._audio_url_signer:
try:
signed_audio_url = self._audio_url_signer(audio_url)
logger.info("音频URL已预签名: original=%s signed_prefix=%s",
audio_url[:80], signed_audio_url[:80])
except Exception as e:
logger.warning("音频URL预签名失败,使用原始URL: %s", e)
payload = {
"model": self._model,
"model": self._clone_model,
"input": {
"audio_url": audio_url,
},
"parameters": {
"language": language,
"action": "create_voice",
"target_model": target,
"prefix": prefix,
"url": signed_audio_url,
"language_hints": [lang_code],
},
}
if voice_name:
payload["parameters"]["voice_name"] = voice_name
response = self._call_api(
method="POST",
path="/services/audio/voice-clone",
path="/services/audio/tts/customization",
json=payload,
timeout=60.0,
)
output = response.get("output", {})
task_id = output.get("task_id", "")
voice_id = output.get("voice_id", "")
status = output.get("status", "DEPLOYING")
request_id = response.get("request_id", "")
if not task_id and not voice_id:
raise CosyVoiceError(f"CosyVoice API 未返回 task_id 或 voice_id: {response}")
if not voice_id:
raise CosyVoiceError(f"CosyVoice API 未返回 voice_id: {response}")
return {
"task_id": task_id,
"voice_id": voice_id,
"status": status,
"request_id": request_id,
}
def check_task_status(self, task_id: str) -> dict:
"""查询克隆任务状态(单次查询,不轮询)
def query_voice_status(self, voice_id: str) -> dict:
"""查询音色状态(单次查询,不轮询).
Args:
task_id: 任务 ID
voice_id: 音色 ID
Returns:
dict: {"status": str, "voice_id": str, "message": str}
status 为 SUCCEEDED/FAILED/PENDING/RUNNING
dict: {"status": str, "target_model": str, "gmt_create": str,
"gmt_modified": str, "resource_link": str}
status 为 DEPLOYING / OK / UNDEPLOYED
Raises:
CosyVoiceError: API 调用失败
@@ -221,40 +256,98 @@ class CosyVoiceService:
if not self._api_key:
raise CosyVoiceAuthError("CosyVoice API Key 未配置")
if not voice_id:
raise ValueError("voice_id 不能为空")
payload = {
"model": self._clone_model,
"input": {
"action": "query_voice",
"voice_id": voice_id,
},
}
response = self._call_api(
method="GET",
path=f"/tasks/{task_id}",
method="POST",
path="/services/audio/tts/customization",
json=payload,
timeout=30.0,
)
output = response.get("output", {})
status = output.get("task_status", "").upper()
voice_id = output.get("voice_id", "")
message = output.get("message", "")
return {
"status": status,
"voice_id": voice_id,
"message": message,
"status": output.get("status", ""),
"target_model": output.get("target_model", ""),
"gmt_create": output.get("gmt_create", ""),
"gmt_modified": output.get("gmt_modified", ""),
"resource_link": output.get("resource_link", ""),
}
def poll_clone_task(self, task_id: str, timeout: float = 300.0) -> dict:
"""轮询音色克隆任务状态(公开方法)。
def check_task_status(self, task_id: str) -> dict:
"""查询克隆任务状态(兼容旧接口,实际用 voice_id 查询).
供 Celery 后台任务调用,轮询直到完成或超时。
为了兼容旧代码,task_id 参数名保留,但实际传的是 voice_id.
Args:
task_id: CosyVoice 任务 ID
task_id: 音色 ID(兼容旧接口名)
Returns:
dict: {"status": str, "voice_id": str, "message": str}
"""
result = self.query_voice_status(task_id)
return {
"status": result["status"],
"voice_id": task_id,
"message": "",
}
def poll_clone_task(self, voice_id: str, timeout: float = 300.0) -> dict:
"""轮询音色克隆状态直到完成或超时.
供 Celery 后台任务调用,轮询直到状态变为 OK 或 UNDEPLOYED.
Args:
voice_id: 音色 ID
timeout: 超时时间(秒),默认 300
Returns:
dict: {"voice_id": str}
Raises:
CosyVoiceError: 任务失败
CosyVoiceError: 任务失败(状态 UNDEPLOYED
CosyVoiceTimeoutError: 超时
"""
return self._poll_clone_task(task_id, timeout=timeout)
start_time = time.time()
attempts = 0
while attempts < self.CLONE_MAX_POLL_ATTEMPTS:
elapsed = time.time() - start_time
if elapsed > timeout:
raise CosyVoiceTimeoutError(
f"音色克隆任务超时({timeout}秒): voice_id={voice_id}"
)
result = self.query_voice_status(voice_id)
status = result.get("status", "").upper()
if status == "OK":
return {"voice_id": voice_id}
elif status == "UNDEPLOYED":
raise CosyVoiceError(
f"音色克隆任务失败(审核未通过): voice_id={voice_id}"
)
elif status in ("DEPLOYING", "PENDING", "PROCESSING", ""):
# 继续轮询
time.sleep(self.CLONE_POLL_INTERVAL)
attempts += 1
else:
logger.warning("未知的音色状态: %s (voice_id=%s)", status, voice_id)
time.sleep(self.CLONE_POLL_INTERVAL)
attempts += 1
raise CosyVoiceTimeoutError(
f"音色克隆任务轮询次数超限: voice_id={voice_id}"
)
def clone_voice(
self,
@@ -262,122 +355,45 @@ class CosyVoiceService:
voice_name: str = "",
language: str = "zh-CN",
timeout: float = 300.0,
target_model: str = "",
) -> CloneResult:
"""克隆音色
"""克隆音色(阻塞,直到完成或超时).
提交音色克隆任务到 CosyVoice API,并轮询直到完成或超时
提交音色克隆到百炼 API,并轮询直到状态变为 OK 或超时.
Args:
audio_url: 参考音频 URL
voice_name: 音色名称(可选)
audio_url: 参考音频 URL(必须公网可访问)
voice_name: 音色名称前缀
language: 语言代码
timeout: 超时时间(秒)
target_model: 目标合成模型
Returns:
CloneResult: 克隆结果,包含 voice_id
Raises:
CosyVoiceError: API 调用失败
CosyVoiceError: API 调用失败或克隆失败
CosyVoiceTimeoutError: 超时
CosyVoiceAuthError: 认证失败
ValueError: 参数无效
"""
if not audio_url:
raise ValueError("audio_url 不能为空")
if not self._api_key:
raise CosyVoiceAuthError("CosyVoice API Key 未配置")
# 构建请求
payload = {
"model": self._model,
"input": {
"audio_url": audio_url,
},
"parameters": {
"language": language,
},
}
if voice_name:
payload["parameters"]["voice_name"] = voice_name
# 调用 API
response = self._call_api(
method="POST",
path="/services/audio/voice-clone",
json=payload,
timeout=timeout,
submit_result = self.submit_clone_task(
audio_url=audio_url,
voice_name=voice_name,
language=language,
target_model=target_model,
)
# 解析响应
output = response.get("output", {})
voice_id = submit_result["voice_id"]
request_id = submit_result["request_id"]
# 检查是否有 task_id(异步模式)
task_id = output.get("task_id")
voice_id = output.get("voice_id")
# 如果创建时已经是 OK 状态,直接返回
if submit_result.get("status", "").upper() == "OK":
return CloneResult(voice_id=voice_id, request_id=request_id)
if task_id:
# 异步模式:轮询任务状态
result = self._poll_clone_task(task_id, timeout)
return CloneResult(
voice_id=result["voice_id"],
request_id=response.get("request_id", ""),
)
elif voice_id:
# 同步模式:直接返回结果
return CloneResult(
voice_id=voice_id,
request_id=response.get("request_id", ""),
)
else:
raise CosyVoiceError(f"CosyVoice API 未返回 task_id 或 voice_id: {response}")
def _poll_clone_task(self, task_id: str, timeout: float) -> dict:
"""轮询音色克隆任务状态。
Args:
task_id: 任务 ID
timeout: 超时时间(秒)
Returns:
任务结果字典
Raises:
CosyVoiceError: 任务失败
CosyVoiceTimeoutError: 超时
"""
start_time = time.time()
attempts = 0
while attempts < self.MAX_POLL_ATTEMPTS:
elapsed = time.time() - start_time
if elapsed > timeout:
raise CosyVoiceTimeoutError(f"音色克隆任务超时({timeout}秒): task_id={task_id}")
response = self._call_api(
method="GET",
path=f"/tasks/{task_id}",
timeout=30.0,
)
output = response.get("output", {})
status = output.get("task_status", "").upper()
if status == "SUCCEEDED":
voice_id = output.get("voice_id", "")
if not voice_id:
raise CosyVoiceError(f"音色克隆任务成功但未返回 voice_id: {response}")
return {"voice_id": voice_id}
elif status == "FAILED":
error_msg = output.get("message", "未知错误")
raise CosyVoiceError(f"音色克隆任务失败: {error_msg}")
elif status in ("PENDING", "RUNNING"):
# 继续轮询
time.sleep(self.POLL_INTERVAL)
attempts += 1
else:
raise CosyVoiceError(f"未知的任务状态: {status}")
raise CosyVoiceTimeoutError(f"音色克隆任务轮询次数超限: task_id={task_id}")
# 否则轮询
result = self.poll_clone_task(voice_id, timeout=timeout)
return CloneResult(voice_id=result["voice_id"], request_id=request_id)
# ── 语音合成 ─────────────────────────────────────────
@@ -388,11 +404,12 @@ class CosyVoiceService:
sample_rate: int = 0,
format: str = "",
speed: float = 1.0,
volume: int = 50,
) -> dict:
"""提交语音合成任务(非阻塞)。
"""提交语音合成任务(同步非流式,直接返回结果).
只提交任务到 CosyVoice API,不轮询结果。
返回的 dict 包含 task_id(异步)或 audio_url(同步)。
CosyVoice SpeechSynthesizer 非流式接口是同步的,
调用后直接返回音频 URL. 此方法保持与旧接口兼容.
Args:
text: 要合成的文本
@@ -400,10 +417,11 @@ class CosyVoiceService:
sample_rate: 采样率(Hz),0 表示使用配置默认值
format: 输出格式(mp3/wav/pcm),空表示使用配置默认值
speed: 语速(0.5-2.0),1.0 为正常速度
volume: 音量(0-100),默认 50
Returns:
dict: {"task_id": str, "audio_url": str, "request_id": str}
task_id 和 audio_url 至少有一个非空
dict: {"audio_url": str, "request_id": str,
"duration": float, "file_size": int}
Raises:
CosyVoiceError: API 调用失败
@@ -423,55 +441,54 @@ class CosyVoiceService:
"model": self._model,
"input": {
"text": text,
},
"parameters": {
"voice": voice_id,
"sample_rate": sample_rate or settings.cosyvoice_sample_rate,
"format": format or settings.cosyvoice_format,
"sample_rate": sample_rate or settings.cosyvoice_sample_rate,
"rate": speed,
"volume": volume,
},
}
response = self._call_api(
method="POST",
path="/services/aigc/text2audio/generation",
path="/services/audio/tts/SpeechSynthesizer",
json=payload,
timeout=60.0,
timeout=120.0,
)
output = response.get("output", {})
task_id = output.get("task_id", "")
audio_url = output.get("audio_url", "")
audio = output.get("audio", {})
audio_url = audio.get("url", "")
request_id = response.get("request_id", "")
if not task_id and not audio_url:
raise CosyVoiceError(f"CosyVoice API 未返回 task_id 或 audio_url: {response}")
if not audio_url:
raise CosyVoiceError(
f"CosyVoice API 未返回 audio_url: {response}"
)
return {
"task_id": task_id,
"task_id": "", # 同步接口无 task_id,兼容旧接口
"audio_url": audio_url,
"duration": output.get("duration", 0.0),
"file_size": output.get("file_size", 0),
"duration": 0.0, # 同步接口不返回 duration
"file_size": 0, # 同步接口不返回 file_size
"request_id": request_id,
}
def poll_synthesize_task(self, task_id: str, timeout: float = 120.0) -> dict:
"""轮询语音合成任务状态(公开方法)。
def poll_synthesize_task(
self, task_id: str, timeout: float = 120.0
) -> dict:
"""轮询合成任务(同步接口无需轮询,保留兼容).
供 Celery 后台任务调用,轮询直到完成或超时。
Args:
task_id: CosyVoice 任务 ID
timeout: 超时时间(秒),默认 120
Returns:
dict: {"audio_url": str, "duration": float, "file_size": int}
CosyVoice SpeechSynthesizer 非流式接口是同步的,
此方法仅为保持接口兼容,实际调用时 task_id 应该为空.
Raises:
CosyVoiceError: 任务失败
CosyVoiceTimeoutError: 超时
CosyVoiceError: 同步接口无需轮询
"""
return self._poll_synthesize_task(task_id, timeout=timeout)
raise CosyVoiceError(
"CosyVoice 非流式合成接口是同步的,无需轮询. "
"请直接使用 submit_synthesize_task()."
)
def synthesize_speech(
self,
@@ -480,11 +497,13 @@ class CosyVoiceService:
sample_rate: int = 0,
format: str = "",
speed: float = 1.0,
volume: int = 50,
timeout: float = 120.0,
) -> SynthesizeResult:
"""语音合成
"""语音合成(同步非流式).
提交语音合成任务到 CosyVoice API,并轮询直到完成或超时。
调用百炼 CosyVoice SpeechSynthesizer 非流式接口,
直接返回合成音频 URL.
Args:
text: 要合成的文本
@@ -492,129 +511,53 @@ class CosyVoiceService:
sample_rate: 采样率(Hz),0 表示使用配置默认值
format: 输出格式(mp3/wav/pcm),空表示使用配置默认值
speed: 语速(0.5-2.0),1.0 为正常速度
timeout: 超时时间(秒)
volume: 音量(0-100),默认 50
timeout: 超时时间(秒),保留参数兼容
Returns:
SynthesizeResult: 合成结果,包含 audio_url
Raises:
CosyVoiceError: API 调用失败
CosyVoiceTimeoutError: 超时
CosyVoiceAuthError: 认证失败
ValueError: 参数无效
"""
if not text:
raise ValueError("text 不能为空")
if not voice_id:
raise ValueError("voice_id 不能为空")
if not self._api_key:
raise CosyVoiceAuthError("CosyVoice API Key 未配置")
settings = get_shared_settings()
# 构建请求
payload = {
"model": self._model,
"input": {
"text": text,
},
"parameters": {
"voice": voice_id,
"sample_rate": sample_rate or settings.cosyvoice_sample_rate,
"format": format or settings.cosyvoice_format,
"rate": speed,
},
}
# 调用 API
response = self._call_api(
method="POST",
path="/services/aigc/text2audio/generation",
json=payload,
timeout=timeout,
result = self.submit_synthesize_task(
text=text,
voice_id=voice_id,
sample_rate=sample_rate,
format=format,
speed=speed,
volume=volume,
)
# 解析响应
output = response.get("output", {})
# 检查是否有 task_id(异步模式)
task_id = output.get("task_id")
audio_url = output.get("audio_url")
if task_id:
# 异步模式:轮询任务状态
result = self._poll_synthesize_task(task_id, timeout)
return SynthesizeResult(
audio_url=result["audio_url"],
duration=result.get("duration", 0.0),
file_size=result.get("file_size", 0),
request_id=response.get("request_id", ""),
)
elif audio_url:
# 同步模式:直接返回结果
return SynthesizeResult(
audio_url=audio_url,
duration=output.get("duration", 0.0),
file_size=output.get("file_size", 0),
request_id=response.get("request_id", ""),
)
else:
raise CosyVoiceError(f"CosyVoice API 未返回 audio_url 或 task_id: {response}")
def _poll_synthesize_task(self, task_id: str, timeout: float) -> dict:
"""轮询语音合成任务状态。
Args:
task_id: 任务 ID
timeout: 超时时间(秒)
Returns:
任务结果字典
Raises:
CosyVoiceError: 任务失败
CosyVoiceTimeoutError: 超时
"""
start_time = time.time()
attempts = 0
while attempts < self.MAX_POLL_ATTEMPTS:
elapsed = time.time() - start_time
if elapsed > timeout:
raise CosyVoiceTimeoutError(f"语音合成任务超时({timeout}秒): task_id={task_id}")
response = self._call_api(
method="GET",
path=f"/tasks/{task_id}",
timeout=30.0,
)
output = response.get("output", {})
status = output.get("task_status", "").upper()
if status == "SUCCEEDED":
audio_url = output.get("audio_url", "")
if not audio_url:
raise CosyVoiceError(f"语音合成任务成功但未返回 audio_url: {response}")
return {
"audio_url": audio_url,
"duration": output.get("duration", 0.0),
"file_size": output.get("file_size", 0),
}
elif status == "FAILED":
error_msg = output.get("message", "未知错误")
raise CosyVoiceError(f"语音合成任务失败: {error_msg}")
elif status in ("PENDING", "RUNNING"):
# 继续轮询
time.sleep(self.POLL_INTERVAL)
attempts += 1
else:
raise CosyVoiceError(f"未知的任务状态: {status}")
raise CosyVoiceTimeoutError(f"语音合成任务轮询次数超限: task_id={task_id}")
return SynthesizeResult(
audio_url=result["audio_url"],
duration=result.get("duration", 0.0),
file_size=result.get("file_size", 0),
request_id=result.get("request_id", ""),
)
# ── 内部方法 ─────────────────────────────────────────
def _sanitize_prefix(self, name: str) -> str:
"""清洗音色名称为合法的 prefix(字母数字,最多10字符).
Args:
name: 原始音色名称
Returns:
清洗后的 prefix
"""
# 只保留字母和数字
cleaned = "".join(c for c in name if c.isalnum())
# 最多10字符
cleaned = cleaned[:10]
# 如果清洗后为空,用默认值
if not cleaned:
cleaned = "clone"
return cleaned
def _call_api(
self,
method: str,
@@ -622,13 +565,13 @@ class CosyVoiceService:
json: Optional[dict] = None,
timeout: float = 30.0,
) -> dict:
"""调用 CosyVoice API
"""调用 DashScope API.
支持重试和错误处理
支持重试和错误处理.
Args:
method: HTTP 方法(GET/POST
path: API 路径
path: API 路径(以 / 开头)
json: 请求体
timeout: 超时时间(秒)
@@ -662,25 +605,57 @@ class CosyVoiceService:
if response.status_code == 200:
return response.json()
elif response.status_code in (401, 403):
raise CosyVoiceAuthError(f"CosyVoice API 认证失败: HTTP {response.status_code}")
raise CosyVoiceAuthError(
f"CosyVoice API 认证失败: HTTP {response.status_code}"
)
elif response.status_code == 400:
# 客户端错误,不重试
body_text = response.text
try:
body = response.json()
code = body.get("code", "")
message = body.get("message", "")
raise CosyVoiceError(
f"CosyVoice API 参数错误: HTTP 400, "
f"code={code}, message={message}"
)
except ValueError:
raise CosyVoiceError(
f"CosyVoice API 调用失败: HTTP 400, body={body_text}"
)
elif response.status_code >= 500:
# 服务端错误,可重试
last_error = CosyVoiceError(f"CosyVoice API 服务端错误: HTTP {response.status_code}")
last_error = CosyVoiceError(
f"CosyVoice API 服务端错误: HTTP {response.status_code}"
)
logger.warning(
f"CosyVoice API 失败 (尝试 {attempt + 1}/{self.MAX_RETRIES}): " f"HTTP {response.status_code}"
"CosyVoice API 失败 (尝试 %d/%d): HTTP %d",
attempt + 1,
self.MAX_RETRIES,
response.status_code,
)
else:
# 客户端错误,不重试
# 其他客户端错误,不重试
raise CosyVoiceError(
f"CosyVoice API 调用失败: HTTP {response.status_code}, " f"body={response.text}"
f"CosyVoice API 调用失败: HTTP {response.status_code}, "
f"body={response.text}"
)
except httpx.TimeoutException as e:
last_error = CosyVoiceTimeoutError(f"请求超时: {e}")
logger.warning(f"CosyVoice API 超时 (尝试 {attempt + 1}/{self.MAX_RETRIES})")
logger.warning(
"CosyVoice API 超时 (尝试 %d/%d)",
attempt + 1,
self.MAX_RETRIES,
)
except httpx.RequestError as e:
last_error = CosyVoiceError(f"请求错误: {e}")
logger.warning(f"CosyVoice API 请求错误 (尝试 {attempt + 1}/{self.MAX_RETRIES}): {e}")
logger.warning(
"CosyVoice API 请求错误 (尝试 %d/%d): %s",
attempt + 1,
self.MAX_RETRIES,
e,
)
# 指数退避
if attempt < self.MAX_RETRIES - 1:
+156 -61
View File
@@ -14,7 +14,6 @@ import logging
import os
import shutil
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Optional
@@ -190,10 +189,13 @@ class TTSWorkflowService:
return job
def poll_and_process_synthesis(self, job_id: str, timeout: float = 120.0) -> TTSJob:
"""轮询 CosyVoice 合成任务并处理结果
"""轮询/检查 CosyVoice 合成任务并处理结果.
从 job.metadata 获取 task_id,调用 CosyVoiceService.poll_synthesize_task()
轮询状态,然后通过 process_synthesis_result / process_synthesis_failure 更新 job。
新 CosyVoice SpeechSynthesizer 非流式接口是同步的,
start_synthesis 阶段通常已经完成. 此方法用于:
1. job 已 completed → 直接返回(同步路径已处理)
2. job 仍在 processing → 重新提交合成(兜底)
3. 分段任务 → 检查分段状态
供 Celery 后台任务调用。
"""
@@ -201,22 +203,42 @@ class TTSWorkflowService:
if job is None:
raise TTSJobNotFoundError(f"TTS job {job_id} not found")
# 已完成直接返回(同步路径在 start_synthesis 里已处理)
if job.status == TTSJobStatus.COMPLETED.value:
logger.info(f"TTS 任务已完成,跳过轮询: job_id={job_id}")
return job
# 检查是否为分段合成任务
segment_task_ids = (job.metadata or {}).get("segment_task_ids", [])
if segment_task_ids:
return self._poll_segment_tasks(job)
# 单段模式:同步接口下通常不会走到这里,
# 但如果因为异常导致仍在 processing,重新提交一次
task_id = (job.metadata or {}).get("cosyvoice_task_id", "")
if not task_id:
raise ValueError(f"TTSJob {job_id} has no cosyvoice_task_id in metadata")
result = self.cosyvoice_service.poll_synthesize_task(task_id, timeout=timeout)
return self.process_synthesis_result(
job_id,
audio_url=result["audio_url"],
duration=result.get("duration", 0.0),
file_size=result.get("file_size", 0),
)
# 新接口(同步):没有 task_id,重新合成
if not task_id:
logger.info(
f"TTS 任务无 task_id,重新同步合成: job_id={job_id}"
)
return self._resynthesize_and_complete(job)
# 旧接口遗留的 task_id,尝试轮询(兼容过渡)
try:
result = self.cosyvoice_service.poll_synthesize_task(task_id, timeout=timeout)
return self.process_synthesis_result(
job_id,
audio_url=result["audio_url"],
duration=result.get("duration", 0.0),
file_size=result.get("file_size", 0),
)
except CosyVoiceError:
# 旧接口轮询失败,重新同步合成
logger.warning(
f"旧 task_id 轮询失败,重新同步合成: job_id={job_id}, task_id={task_id}"
)
return self._resynthesize_and_complete(job)
def process_synthesis_result(
self,
@@ -257,6 +279,40 @@ class TTSWorkflowService:
logger.info(f"TTS 合成成功: job_id={job_id}, audio_url={permanent_url}")
return job
def _resynthesize_and_complete(self, job: TTSJob) -> TTSJob:
"""重新同步合成并完成任务(兜底路径).
当 poll_and_process_synthesis 发现 job 仍在 processing 且无 task_id 时,
重新调用同步合成接口,转存 OSS 后标记完成。
"""
try:
# 从 metadata 读取合成参数(兼容旧数据,无则用默认值)
job_metadata = job.metadata or {}
speed = float(job_metadata.get("speed", 1.0))
volume = int(job_metadata.get("volume", 50))
result = self.cosyvoice_service.submit_synthesize_task(
text=job.input_text,
voice_id=job.voice_id,
sample_rate=job.sample_rate,
format=job.format,
speed=speed,
volume=volume,
)
audio_url = result.get("audio_url", "")
if not audio_url:
raise CosyVoiceError("重新合成未返回 audio_url")
return self.process_synthesis_result(
job.id,
audio_url=audio_url,
duration=result.get("duration", 0.0),
file_size=result.get("file_size", 0),
)
except Exception as e:
logger.error(f"重新同步合成失败: job_id={job.id}, error={e}")
return self.process_synthesis_failure(job.id, str(e))
def process_synthesis_failure(self, job_id: str, error_message: str) -> TTSJob:
"""处理合成失败结果。
@@ -429,69 +485,108 @@ class TTSWorkflowService:
shutil.rmtree(temp_dir, ignore_errors=True)
def _poll_segment_tasks(self, job: TTSJob) -> TTSJob:
"""轮询所有分段异步任务,全部完成后合并音频。"""
"""分段任务完成检查(适配新同步接口).
新 CosyVoice SpeechSynthesizer 非流式接口为同步接口,
分段任务在提交时应已同步返回 audio_url。
若历史任务处于 processing 且有 segment_task_ids 但缺少 audio_url
则对缺失分段重新同步合成,全部完成后合并音频。
"""
segment_task_ids: list[str] = (job.metadata or {}).get("segment_task_ids", [])
segment_audio_urls: list[str] = (job.metadata or {}).get("segment_audio_urls", [])
segment_count = len(segment_task_ids)
poll_start = time.monotonic()
poll_timeout = 300.0 # 分段任务超时更长
poll_interval = 2.0
if segment_count == 0:
logger.warning(f"分段任务无 task_id: job_id={job.id}")
self._handle_segment_failure(job, "分段任务数据异常:无分段信息")
return self.repository.get(job.id)
while time.monotonic() - poll_start < poll_timeout:
all_done = True
results: list[dict | None] = [None] * segment_count
# 从 metadata 读取合成参数
job_metadata = job.metadata or {}
speed = float(job_metadata.get("speed", 1.0))
volume = int(job_metadata.get("volume", 50))
for idx, task_id in enumerate(segment_task_ids):
# 已经有音频的分段跳过轮询
if idx < len(segment_audio_urls) and segment_audio_urls[idx]:
results[idx] = {
"audio_url": segment_audio_urls[idx],
"duration": 0.0,
"file_size": 0,
}
continue
# 分段文本(用于缺失段重新合成)
segments = split_text(job.input_text, max_chars=_SEGMENT_THRESHOLD)
try:
result = self.cosyvoice_service.poll_synthesize_task(task_id, timeout=poll_timeout)
results[idx] = result
except Exception as e:
logger.error(f"分段任务轮询失败: job_id={job.id}, " f"segment={idx}, error={e}")
self._handle_segment_failure(job, f"分段 {idx + 1} 轮询失败: {e}")
return self.repository.get(job.id)
results: list[dict | None] = [None] * segment_count
if results[idx] is None:
all_done = False
# 已有音频的分段直接用
for idx in range(segment_count):
if idx < len(segment_audio_urls) and segment_audio_urls[idx]:
results[idx] = {
"audio_url": segment_audio_urls[idx],
"duration": 0.0,
"file_size": 0,
}
if all_done and all(r is not None for r in results):
# 所有分段完成,下载合并
try:
merged_data, total_duration = self._download_and_merge_segments(results, job)
# 找出缺失音频的分段索引
missing_indices = [i for i in range(segment_count) if results[i] is None]
# 转存 OSS
permanent_url, storage_key = self._upload_merged_to_oss(
merged_data, job.user_id, job.id, job.format
if missing_indices:
logger.info(
f"分段任务重新合成缺失段: job_id={job.id}, "
f"缺失={len(missing_indices)}/{segment_count}"
)
# 并发重新合成缺失分段
max_workers = min(len(missing_indices), _MAX_SEGMENT_WORKERS)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_idx = {}
for idx in missing_indices:
segment_text = segments[idx] if idx < len(segments) else ""
future = executor.submit(
self.cosyvoice_service.submit_synthesize_task,
text=segment_text,
voice_id=job.voice_id,
sample_rate=job.sample_rate,
format=job.format,
speed=speed,
volume=volume,
)
future_to_idx[future] = idx
job.mark_completed(
output_audio_url=permanent_url,
output_audio_key=storage_key,
duration=total_duration,
file_size=len(merged_data),
)
job = self.repository.update(job)
logger.info(f"分段合成轮询完成: job_id={job.id}, " f"merged_size={len(merged_data)}")
return job
for future in as_completed(future_to_idx):
idx = future_to_idx[future]
try:
results[idx] = future.result()
except Exception as e:
logger.error(
f"分段重新合成失败: job_id={job.id}, "
f"segment={idx}, error={e}"
)
self._handle_segment_failure(
job, f"分段 {idx + 1} 重新合成失败: {e}"
)
return self.repository.get(job.id)
except Exception as e:
self._handle_segment_failure(job, f"分段合并失败: {e}")
return self.repository.get(job.id)
# 所有分段完成,下载合并
if all(r is not None for r in results):
try:
merged_data, total_duration = self._download_and_merge_segments(results, job)
# 等待后重试
time.sleep(poll_interval)
permanent_url, storage_key = self._upload_merged_to_oss(
merged_data, job.user_id, job.id, job.format
)
# 超时
self._handle_segment_failure(job, "分段合成轮询超时(300 秒)")
job.mark_completed(
output_audio_url=permanent_url,
output_audio_key=storage_key,
duration=total_duration,
file_size=len(merged_data),
)
job = self.repository.update(job)
logger.info(
f"分段合成完成(重新合成路径): job_id={job.id}, "
f"merged_size={len(merged_data)}"
)
return job
except Exception as e:
self._handle_segment_failure(job, f"分段合并失败: {e}")
return self.repository.get(job.id)
# 理论上不会到这里(全部重新合成要么成功要么失败)
self._handle_segment_failure(job, "分段合成结果不完整")
return self.repository.get(job.id)
def _handle_segment_failure(self, job: TTSJob, error_message: str) -> None:
+10 -7
View File
@@ -115,14 +115,16 @@ class VoiceCloneWorkflowService:
language=language,
)
# 4. 保存 task_id / voice_id 到 metadata
# 4. 保存 voice_id / request_id 到 metadata
# 注意:key 保留 cosyvoice_task_id 以兼容旧数据,实际存的是 voice_id
task_metadata = dict(profile.metadata)
task_metadata["cosyvoice_task_id"] = submit_result.get("task_id", "")
task_metadata["cosyvoice_task_id"] = submit_result.get("voice_id", "")
task_metadata["cosyvoice_request_id"] = submit_result.get("request_id", "")
# 如果 CosyVoice 同步返回了 voice_id,直接标记 ready
# 如果 CosyVoice 直接返回了 OK 状态,直接标记 ready
voice_id = submit_result.get("voice_id", "")
if voice_id:
status = submit_result.get("status", "").upper()
if voice_id and status == "OK":
profile.mark_ready(voice_id)
profile.metadata = task_metadata
profile = self.repository.update(profile)
@@ -131,7 +133,7 @@ class VoiceCloneWorkflowService:
profile.metadata = task_metadata
profile = self.repository.update(profile)
logger.info(f"音色克隆任务已提交: profile_id={profile.id}, " f"task_id={submit_result.get('task_id')}")
logger.info(f"音色克隆任务已提交: profile_id={profile.id}, " f"voice_id={submit_result.get('voice_id')}")
except (CosyVoiceError, CosyVoiceAuthError) as e:
# CosyVoice 提交失败,标记为 failed
@@ -248,11 +250,12 @@ class VoiceCloneWorkflowService:
)
task_metadata = dict(profile.metadata)
task_metadata["cosyvoice_task_id"] = submit_result.get("task_id", "")
task_metadata["cosyvoice_task_id"] = submit_result.get("voice_id", "")
task_metadata["cosyvoice_request_id"] = submit_result.get("request_id", "")
voice_id = submit_result.get("voice_id", "")
if voice_id:
status = submit_result.get("status", "").upper()
if voice_id and status == "OK":
profile.mark_ready(voice_id)
profile.metadata = task_metadata
profile = self.repository.update(profile)
Regular → Executable
+9 -9
View File
@@ -16,7 +16,7 @@ class PresetVoice:
"""预置音色定义。
Attributes:
voice_id: CosyVoice 模型音色名(如 longxiaochun
voice_id: CosyVoice 模型音色名(如 longxiaochun_v3
name: 中文展示名
description: 音色描述
gender: 性别(male/female
@@ -49,7 +49,7 @@ class PresetVoice:
# 预置音色列表(阿里云 CosyVoice 真实可用音色)
PRESET_VOICES: list[PresetVoice] = [
PresetVoice(
voice_id="longxiaochun",
voice_id="longxiaochun_v3",
name="龙小淳",
description="温柔女声,适合情感类内容",
gender="female",
@@ -57,7 +57,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["温柔", "女声", "情感"],
),
PresetVoice(
voice_id="longxiaoxia",
voice_id="longxiaoxia_v3",
name="龙小夏",
description="知性女声,适合新闻播报",
gender="female",
@@ -65,7 +65,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["知性", "女声", "播报"],
),
PresetVoice(
voice_id="longxiaochen",
voice_id="longxiaochen_v3",
name="龙小晨",
description="磁性男声,适合有声书",
gender="male",
@@ -73,7 +73,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["磁性", "男声", "有声书"],
),
PresetVoice(
voice_id="longyue",
voice_id="longyue_v3",
name="龙悦",
description="甜美女声,适合广告配音",
gender="female",
@@ -81,7 +81,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["甜美", "女声", "广告"],
),
PresetVoice(
voice_id="longshu",
voice_id="longshu_v3",
name="龙书",
description="沉稳男声,适合教育讲解",
gender="male",
@@ -89,7 +89,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["沉稳", "男声", "教育"],
),
PresetVoice(
voice_id="longjing",
voice_id="longjing_v3",
name="龙静",
description="优雅女声,适合纪录片解说",
gender="female",
@@ -97,7 +97,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["优雅", "女声", "纪录片"],
),
PresetVoice(
voice_id="longbo",
voice_id="longbo_v3",
name="龙博",
description="浑厚男声,适合科技类内容",
gender="male",
@@ -105,7 +105,7 @@ PRESET_VOICES: list[PresetVoice] = [
tags=["浑厚", "男声", "科技"],
),
PresetVoice(
voice_id="longtian",
voice_id="longtian_v3",
name="龙甜",
description="活泼女声,适合短视频配音",
gender="female",
Regular → Executable
+6 -4
View File
@@ -29,13 +29,15 @@ class SharedSettings(BaseSettings):
oss_access_key_secret: str = ""
oss_bucket_name: str = "xiaoxia-autocut"
# CosyVoice (阿里云语音合成)
# CosyVoice (阿里云百炼语音合成)
cosyvoice_api_key: str = ""
cosyvoice_base_url: str = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2audio"
cosyvoice_model: str = "cosyvoice-v1"
cosyvoice_voice: str = "longxiaochun" # 默认音色
cosyvoice_base_url: str = "https://dashscope.aliyuncs.com/api/v1"
cosyvoice_model: str = "cosyvoice-v3.5-plus"
cosyvoice_voice: str = "longxiaochun_v3" # 默认音色
cosyvoice_sample_rate: int = 22050
cosyvoice_format: str = "mp3" # 输出格式:mp3/wav/pcm
# 音色克隆模型名(固定为 voice-enrollment
cosyvoice_clone_model: str = "voice-enrollment"
# Environment
environment: str = "development"
File diff suppressed because it is too large Load Diff
+15 -15
View File
@@ -64,7 +64,7 @@ class TestPresetVoice:
def test_preset_voice_to_dict(self) -> None:
"""序列化。"""
voice = PresetVoice(
voice_id="longxiaochun",
voice_id="longxiaochun_v3",
name="龙小淳",
description="温柔女声",
gender="female",
@@ -73,7 +73,7 @@ class TestPresetVoice:
result = voice.to_dict()
assert result["voice_id"] == "longxiaochun"
assert result["voice_id"] == "longxiaochun_v3"
assert result["name"] == "龙小淳"
assert result["description"] == "温柔女声"
assert result["gender"] == "female"
@@ -127,14 +127,14 @@ class TestPresetVoicesConfig:
def test_cosyvoice_voice_ids(self) -> None:
"""音色 ID 应为 CosyVoice 真实可用的音色名。"""
expected_ids = {
"longxiaochun",
"longxiaoxia",
"longxiaochen",
"longyue",
"longshu",
"longjing",
"longbo",
"longtian",
"longxiaochun_v3",
"longxiaoxia_v3",
"longxiaochen_v3",
"longyue_v3",
"longshu_v3",
"longjing_v3",
"longbo_v3",
"longtian_v3",
}
actual_ids = {v.voice_id for v in PRESET_VOICES}
assert actual_ids == expected_ids
@@ -164,10 +164,10 @@ class TestPresetVoiceHelpers:
def test_get_preset_voice_by_id_found(self) -> None:
"""按 ID 查找存在的音色。"""
voice = get_preset_voice_by_id("longxiaochun")
voice = get_preset_voice_by_id("longxiaochun_v3")
assert voice is not None
assert voice.name == "龙小淳"
assert voice.voice_id == "longxiaochun"
assert voice.voice_id == "longxiaochun_v3"
def test_get_preset_voice_by_id_not_found(self) -> None:
"""按 ID 查找不存在的音色。"""
@@ -176,9 +176,9 @@ class TestPresetVoiceHelpers:
def test_is_preset_voice_true(self) -> None:
"""判断预置音色返回 True。"""
assert is_preset_voice("longxiaochun") is True
assert is_preset_voice("longxiaoxia") is True
assert is_preset_voice("longbo") is True
assert is_preset_voice("longxiaochun_v3") is True
assert is_preset_voice("longxiaoxia_v3") is True
assert is_preset_voice("longbo_v3") is True
def test_is_preset_voice_false(self) -> None:
"""判断非预置音色返回 False。"""
+4 -4
View File
@@ -15,7 +15,7 @@ class TestTTSJobCreate:
job = TTSJob.create(
user_id="user_001",
input_text="这是一段测试文本",
voice_id="longxiaochun",
voice_id="longxiaochun_v3",
voice_model="cosyvoice-v1",
project_id="project_001",
voice_clone_profile_id="profile_001",
@@ -26,7 +26,7 @@ class TestTTSJobCreate:
assert job.id
assert job.user_id == "user_001"
assert job.input_text == "这是一段测试文本"
assert job.voice_id == "longxiaochun"
assert job.voice_id == "longxiaochun_v3"
assert job.voice_model == "cosyvoice-v1"
assert job.project_id == "project_001"
assert job.voice_clone_profile_id == "profile_001"
@@ -291,7 +291,7 @@ class TestTTSJobToDict:
job = TTSJob.create(
user_id="user_001",
input_text="测试文本",
voice_id="longxiaochun",
voice_id="longxiaochun_v3",
voice_model="cosyvoice-v1",
project_id="project_001",
voice_clone_profile_id="profile_001",
@@ -306,7 +306,7 @@ class TestTTSJobToDict:
assert result["id"] == job.id
assert result["user_id"] == "user_001"
assert result["input_text"] == "测试文本"
assert result["voice_id"] == "longxiaochun"
assert result["voice_id"] == "longxiaochun_v3"
assert result["voice_model"] == "cosyvoice-v1"
assert result["project_id"] == "project_001"
assert result["voice_clone_profile_id"] == "profile_001"
+57 -16
View File
@@ -353,16 +353,11 @@ class TestHandleSegmentFailure:
class TestPollSegmentTasks:
"""测试 _poll_segment_tasks 异步轮询"""
"""测试 _poll_segment_tasks 分段缺失重新合成(适配同步接口)"""
@patch("packages.application.tts_job.workflow.time")
@patch("packages.application.tts_job.workflow.httpx")
def test_all_segments_done(self, mock_httpx: MagicMock, mock_time: MagicMock) -> None:
"""所有分段完成后合并标记完成。"""
# Mock time.monotonic 让循环只执行一次
mock_time.monotonic.side_effect = [0.0, 1.0, 2.0]
mock_time.sleep = MagicMock()
def test_all_segments_done(self, mock_httpx: MagicMock) -> None:
"""所有分段缺少 audio_url 时重新同步合成,合并标记完成。"""
# Mock 下载分段音频
mock_resp = MagicMock()
mock_resp.content = b"seg audio"
@@ -370,7 +365,7 @@ class TestPollSegmentTasks:
mock_httpx.get.return_value = mock_resp
service = MagicMock(spec=CosyVoiceService)
service.poll_synthesize_task.side_effect = [
service.submit_synthesize_task.side_effect = [
{"audio_url": "https://temp.com/seg1.mp3", "duration": 2.0, "file_size": 100},
{"audio_url": "https://temp.com/seg2.mp3", "duration": 3.0, "file_size": 200},
]
@@ -381,6 +376,8 @@ class TestPollSegmentTasks:
repo = MagicMock()
job = _make_job(
status=TTSJobStatus.PROCESSING,
# 长文本触发分段,用于重新合成时切分
input_text="这是一段很长的测试文本。" * 30,
metadata={
"segment_task_ids": ["task_1", "task_2"],
"segment_audio_urls": ["", ""],
@@ -400,19 +397,18 @@ class TestPollSegmentTasks:
result = workflow._poll_segment_tasks(job)
assert result.status == TTSJobStatus.COMPLETED
# 两个缺失分段都重新合成了
assert service.submit_synthesize_task.call_count == 2
@patch("packages.application.tts_job.workflow.time")
def test_segment_poll_failure(self, mock_time: MagicMock) -> None:
"""分段轮询失败时标记 job failed。"""
mock_time.monotonic.side_effect = [0.0, 1.0]
mock_time.sleep = MagicMock()
def test_segment_resynthesis_failure(self) -> None:
"""分段重新合成失败时标记 job failed。"""
service = MagicMock(spec=CosyVoiceService)
service.poll_synthesize_task.side_effect = CosyVoiceError("Poll failed")
service.submit_synthesize_task.side_effect = CosyVoiceError("Synthesis failed")
repo = MagicMock()
job = _make_job(
status=TTSJobStatus.PROCESSING,
input_text="这是一段很长的测试文本。" * 30,
metadata={
"segment_task_ids": ["task_1"],
"segment_audio_urls": [""],
@@ -426,6 +422,51 @@ class TestPollSegmentTasks:
assert result.status == TTSJobStatus.FAILED
@patch("packages.application.tts_job.workflow.httpx")
def test_partial_audio_urls_reuse_existing(self, mock_httpx: MagicMock) -> None:
"""部分分段已有 audio_url 时直接复用,缺失的重新合成。"""
mock_resp = MagicMock()
mock_resp.content = b"seg audio"
mock_resp.raise_for_status.return_value = None
mock_httpx.get.return_value = mock_resp
service = MagicMock(spec=CosyVoiceService)
# 只有 1 个分段需要重新合成
service.submit_synthesize_task.return_value = {
"audio_url": "https://temp.com/seg2.mp3",
"duration": 3.0,
"file_size": 200,
}
storage = MagicMock()
storage.upload_file.return_value = "https://oss.example.com/merged.mp3"
repo = MagicMock()
job = _make_job(
status=TTSJobStatus.PROCESSING,
input_text="这是一段很长的测试文本。" * 30,
metadata={
"segment_task_ids": ["task_1", "task_2"],
"segment_audio_urls": ["https://temp.com/seg1.mp3", ""],
"segment_format": "mp3",
},
)
repo.get.return_value = job
repo.update.side_effect = lambda j: j
workflow = _make_workflow(cosyvoice_service=service, repo=repo, storage=storage)
with patch("packages.application.tts_job.workflow.AudioMerger") as MockMerger:
mock_merger = MagicMock()
mock_merger.merge.return_value = b"merged data"
MockMerger.return_value = mock_merger
result = workflow._poll_segment_tasks(job)
assert result.status == TTSJobStatus.COMPLETED
# 只有 1 个缺失分段被重新合成
assert service.submit_synthesize_task.call_count == 1
class TestPollAndProcessSynthesisSegmentDetection:
"""测试 poll_and_process_synthesis 正确识别分段任务。"""
+16 -16
View File
@@ -57,15 +57,15 @@ def _make_service(
class TestStartClone:
"""测试 start_clone 方法。"""
def test_start_clone_with_async_task(self) -> None:
"""异步模式:提交任务后返回 processing 状态的 profile"""
def test_start_clone_with_deploying(self) -> None:
"""提交克隆后返回 DEPLOYING 状态,profile 保持 processing"""
mock_repo = MagicMock()
mock_cosyvoice = MagicMock(spec=CosyVoiceService)
# CosyVoice 返回 task_id(异步模式
# CosyVoice 返回 voice_id + DEPLOYING 状态(需轮询
mock_cosyvoice.submit_clone_task.return_value = {
"task_id": "task-abc",
"voice_id": "",
"voice_id": "voice-abc",
"status": "DEPLOYING",
"request_id": "req-123",
}
@@ -81,21 +81,21 @@ class TestStartClone:
)
assert profile.status == VoiceCloneStatus.PROCESSING
assert profile.metadata["cosyvoice_task_id"] == "task-abc"
assert profile.metadata["cosyvoice_task_id"] == "voice-abc"
assert profile.metadata["cosyvoice_request_id"] == "req-123"
mock_cosyvoice.submit_clone_task.assert_called_once()
assert mock_repo.create.call_count == 1
# update 至少调用 2 次:mark_processing + 保存 task_id
# update 至少调用 2 次:mark_processing + 保存 voice_id
assert mock_repo.update.call_count >= 2
def test_start_clone_with_sync_result(self) -> None:
"""同步模式:CosyVoice 直接返回 voice_idprofile 变为 ready。"""
def test_start_clone_with_ok_status(self) -> None:
"""CosyVoice 直接返回 OK 状态profile 变为 ready。"""
mock_repo = MagicMock()
mock_cosyvoice = MagicMock(spec=CosyVoiceService)
mock_cosyvoice.submit_clone_task.return_value = {
"task_id": "",
"voice_id": "voice-sync-123",
"status": "OK",
"request_id": "req-456",
}
@@ -244,8 +244,8 @@ class TestRetryClone:
mock_repo.update.side_effect = lambda p: p
mock_cosyvoice.submit_clone_task.return_value = {
"task_id": "task-retry",
"voice_id": "",
"voice_id": "voice-retry",
"status": "DEPLOYING",
"request_id": "req-retry",
}
@@ -253,11 +253,11 @@ class TestRetryClone:
result = service.retry_clone(profile.id, "user-123")
assert result.status == VoiceCloneStatus.PROCESSING
assert result.metadata["cosyvoice_task_id"] == "task-retry"
assert result.metadata["cosyvoice_task_id"] == "voice-retry"
assert result.retry_count == 2 # prepare_retry 增加了一次
def test_retry_clone_with_sync_result(self) -> None:
"""重试成功,同步模式"""
def test_retry_clone_with_ok_status(self) -> None:
"""重试成功,直接返回 OK 状态"""
mock_repo = MagicMock()
mock_cosyvoice = MagicMock(spec=CosyVoiceService)
@@ -266,8 +266,8 @@ class TestRetryClone:
mock_repo.update.side_effect = lambda p: p
mock_cosyvoice.submit_clone_task.return_value = {
"task_id": "",
"voice_id": "voice-retry-sync",
"status": "OK",
"request_id": "req-retry",
}