Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ed0ffd5a8 |
+3
-8
@@ -44,14 +44,9 @@ OSS_ACCESS_KEY_SECRET=your-access-key-secret
|
||||
OSS_BUCKET_NAME=xiaoxia-autocut
|
||||
|
||||
# ==================== CosyVoice 语音合成配置 ====================
|
||||
# 注意:base_url 只需写到 /api/v1,具体路径由代码拼接
|
||||
# 模型: cosyvoice-v3-flash (推荐,支持系统音色,性价比高)
|
||||
# cosyvoice-v3-plus (高质量,系统音色少)
|
||||
# cosyvoice-v3.5-flash / cosyvoice-v3.5-plus (仅支持克隆/设计音色,无系统音色)
|
||||
# 音色: v3系列系统音色带 _v3 后缀,如 longxiaochun_v3, longxiaoxia_v3, longanyang (无后缀)
|
||||
COSYVOICE_API_KEY=your-cosyvoice-api-key
|
||||
COSYVOICE_BASE_URL=https://dashscope.aliyuncs.com/api/v1
|
||||
COSYVOICE_MODEL=cosyvoice-v3-flash
|
||||
COSYVOICE_VOICE=longxiaochun_v3
|
||||
COSYVOICE_BASE_URL=https://dashscope.aliyuncs.com/api/v1/services/aigc/text2audio
|
||||
COSYVOICE_MODEL=cosyvoice-v1
|
||||
COSYVOICE_VOICE=longxiaochun
|
||||
COSYVOICE_SAMPLE_RATE=22050
|
||||
COSYVOICE_FORMAT=mp3
|
||||
|
||||
Executable → Regular
+3
-8
@@ -42,15 +42,10 @@ OSS_DIRECT_UPLOAD_MAX_MB=2000
|
||||
OSS_DIRECT_UPLOAD_EXPIRE_SECONDS=900
|
||||
|
||||
# ==================== CosyVoice 语音合成(必须配置)====================
|
||||
# 注意:base_url 只需写到 /api/v1,具体路径由代码拼接
|
||||
# 模型: cosyvoice-v3-flash (推荐,支持系统音色,性价比高)
|
||||
# cosyvoice-v3-plus (高质量,系统音色少)
|
||||
# cosyvoice-v3.5-flash / cosyvoice-v3.5-plus (仅支持克隆/设计音色,无系统音色)
|
||||
# 音色: v3系列系统音色带 _v3 后缀,如 longxiaochun_v3, longxiaoxia_v3, longanyang (无后缀)
|
||||
COSYVOICE_API_KEY=CHANGE_ME_COSYVOICE_API_KEY
|
||||
COSYVOICE_BASE_URL=https://dashscope.aliyuncs.com/api/v1
|
||||
COSYVOICE_MODEL=cosyvoice-v3-flash
|
||||
COSYVOICE_VOICE=longxiaochun_v3
|
||||
COSYVOICE_BASE_URL=https://dashscope.aliyuncs.com/api/v1/services/aigc/text2audio
|
||||
COSYVOICE_MODEL=cosyvoice-v1
|
||||
COSYVOICE_VOICE=longxiaochun
|
||||
COSYVOICE_SAMPLE_RATE=22050
|
||||
COSYVOICE_FORMAT=mp3
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
max-line-length = 120
|
||||
exclude =
|
||||
.git,
|
||||
.cache,
|
||||
__pycache__,
|
||||
.venv,
|
||||
venv,
|
||||
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m pytest tests/unit -q \
|
||||
--cov=apps --cov-report=term --cov-report=xml --cov-fail-under=50
|
||||
--cov=apps --cov-report=term --cov-report=xml
|
||||
|
||||
- name: Start PostgreSQL for integration tests
|
||||
shell: sh
|
||||
|
||||
@@ -6,7 +6,6 @@ dist/
|
||||
coverage/
|
||||
|
||||
# Python / backend
|
||||
.cache/
|
||||
.venv/
|
||||
venv/
|
||||
.venv-ci-root/
|
||||
|
||||
@@ -4,8 +4,8 @@ import uuid
|
||||
from typing import Any
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.storage import OSSStorageService, get_storage_service
|
||||
from app.core.task_enqueue import safe_enqueue_generation_task
|
||||
from app.dependencies import (
|
||||
get_asset_library_repository,
|
||||
get_asset_repository,
|
||||
@@ -36,6 +36,44 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _safe_enqueue_generation_task(
|
||||
task: Any,
|
||||
generation_task_repository: Any,
|
||||
) -> bool:
|
||||
"""安全入队:send_task 失败时自动把任务标记为 failed,避免留下 pending 僵尸任务。
|
||||
|
||||
Returns:
|
||||
True 表示入队成功,False 表示入队失败(已标记为 failed)
|
||||
"""
|
||||
try:
|
||||
celery_app.send_task("worker.generate_video", args=[task.id])
|
||||
logger.info(
|
||||
"[生成任务] 入队成功: task_id=%s, status=%s",
|
||||
task.id,
|
||||
task.status,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[生成任务] 入队失败,标记为失败: task_id=%s error=%s",
|
||||
task.id,
|
||||
e,
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
task.mark_failed(f"任务入队失败: {e}")
|
||||
generation_task_repository.update(task)
|
||||
except Exception as update_err:
|
||||
logger.error(
|
||||
"[生成任务] 入队失败后更新状态也失败: task_id=%s error=%s",
|
||||
task.id,
|
||||
update_err,
|
||||
exc_info=True,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def _check_project_access(project_id: str, user_id: str, project_repository) -> None:
|
||||
"""检查用户是否有项目访问权限"""
|
||||
project = project_repository.find_by_id(project_id)
|
||||
@@ -249,7 +287,7 @@ def create_generation_task(
|
||||
batch_id=batch_id,
|
||||
)
|
||||
)
|
||||
if safe_enqueue_generation_task(task, generation_task_repository, log_prefix="[生成任务]", log_task_status=True):
|
||||
if _safe_enqueue_generation_task(task, generation_task_repository):
|
||||
created_tasks.append(task)
|
||||
else:
|
||||
failed_tasks.append(task)
|
||||
@@ -343,6 +381,6 @@ def retry_generation_task(
|
||||
asset_select_mode=getattr(task, "asset_select_mode", ""),
|
||||
)
|
||||
)
|
||||
if not safe_enqueue_generation_task(retried, generation_task_repository, log_prefix="[生成任务]", log_task_status=True):
|
||||
if not _safe_enqueue_generation_task(retried, generation_task_repository):
|
||||
logger.warning("[生成任务] 重试入队失败: task_id=%s", retried.id)
|
||||
return _to_generation_task_response(retried)
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.task_enqueue import safe_enqueue_generation_task
|
||||
from app.dependencies import (
|
||||
get_generation_task_repository,
|
||||
get_ingest_job_repository,
|
||||
@@ -24,10 +22,38 @@ from packages.application import (
|
||||
SubmitIngestJobUseCase,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _safe_enqueue_generation_task(
|
||||
task: Any,
|
||||
generation_task_repository: Any,
|
||||
) -> bool:
|
||||
"""安全入队:send_task 失败时自动把任务标记为 failed,避免留下 pending 僵尸任务。"""
|
||||
try:
|
||||
celery_app.send_task("worker.generate_video", args=[task.id])
|
||||
logger.info("[任务中心] 生成任务入队成功: task_id=%s", task.id)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[任务中心] 生成任务入队失败,标记为失败: task_id=%s error=%s",
|
||||
task.id,
|
||||
e,
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
task.mark_failed(f"任务入队失败: {e}")
|
||||
generation_task_repository.update(task)
|
||||
except Exception as update_err:
|
||||
logger.error(
|
||||
"[任务中心] 入队失败后更新状态也失败: task_id=%s error=%s",
|
||||
task.id,
|
||||
update_err,
|
||||
exc_info=True,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def _humanize_task_error(error_message: str) -> str:
|
||||
raw = (error_message or "").strip()
|
||||
if not raw:
|
||||
@@ -156,7 +182,7 @@ def retry_task_by_id(
|
||||
created_by_user_id=authenticated_user.user.id,
|
||||
)
|
||||
)
|
||||
if not safe_enqueue_generation_task(retried, generation_task_repository, log_prefix="[任务中心]"):
|
||||
if not _safe_enqueue_generation_task(retried, generation_task_repository):
|
||||
logger.warning("[任务中心] 用户级重试入队失败: task_id=%s", retried.id)
|
||||
return UserTaskResponse(
|
||||
id=f"generation:{retried.id}",
|
||||
@@ -239,7 +265,7 @@ def retry_project_task(
|
||||
created_by_user_id=authenticated_user.user.id,
|
||||
)
|
||||
)
|
||||
if not safe_enqueue_generation_task(retried, generation_task_repository, log_prefix="[任务中心]"):
|
||||
if not _safe_enqueue_generation_task(retried, generation_task_repository):
|
||||
logger.warning("[任务中心] 项目级重试用队失败: task_id=%s", retried.id)
|
||||
return _generation_task_to_project_response(retried)
|
||||
if task_type == "ingest":
|
||||
|
||||
Executable → Regular
+6
-17
@@ -7,7 +7,6 @@ from typing import Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import (
|
||||
get_audio_url_signer,
|
||||
get_cosyvoice_service,
|
||||
get_db_session,
|
||||
get_user_repository,
|
||||
@@ -57,10 +56,7 @@ def _get_repository(session: Session = Depends(get_db_session)) -> SQLAlchemyTTS
|
||||
return SQLAlchemyTTSJobRepository(session)
|
||||
|
||||
|
||||
def _to_response(job, sign_url=None) -> TTSJobResponse:
|
||||
output_url = job.output_audio_url
|
||||
if sign_url and output_url:
|
||||
output_url = sign_url(output_url)
|
||||
def _to_response(job) -> TTSJobResponse:
|
||||
return TTSJobResponse(
|
||||
id=job.id,
|
||||
user_id=job.user_id,
|
||||
@@ -70,7 +66,7 @@ def _to_response(job, sign_url=None) -> TTSJobResponse:
|
||||
project_id=job.project_id,
|
||||
voice_clone_profile_id=job.voice_clone_profile_id,
|
||||
status=job.status,
|
||||
output_audio_url=output_url,
|
||||
output_audio_url=job.output_audio_url,
|
||||
output_audio_key=job.output_audio_key,
|
||||
duration=job.duration,
|
||||
file_size=job.file_size,
|
||||
@@ -180,7 +176,6 @@ def list_tts_jobs(
|
||||
status_filter: Optional[str] = Query(None, alias="status"),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> ListTTSJobResponse:
|
||||
"""列出用户的 TTS 合成任务。"""
|
||||
user_id = authenticated_user.user.id
|
||||
@@ -188,7 +183,7 @@ def list_tts_jobs(
|
||||
skip = (page - 1) * page_size
|
||||
items, total = use_case.execute(user_id, status=status_filter, skip=skip, limit=page_size)
|
||||
return ListTTSJobResponse(
|
||||
items=[_to_response(j, sign_url) for j in items],
|
||||
items=[_to_response(j) for j in items],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
@@ -200,7 +195,6 @@ def get_tts_job(
|
||||
job_id: str,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> TTSJobResponse:
|
||||
"""获取 TTS 任务详情。"""
|
||||
user_id = authenticated_user.user.id
|
||||
@@ -209,7 +203,7 @@ def get_tts_job(
|
||||
job = use_case.execute(job_id, user_id)
|
||||
except TTSJobNotFoundError:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="TTS job not found")
|
||||
return _to_response(job, sign_url)
|
||||
return _to_response(job)
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/status", response_model=TTSStatusResponse)
|
||||
@@ -217,7 +211,6 @@ def get_tts_job_status(
|
||||
job_id: str,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> TTSStatusResponse:
|
||||
"""查询 TTS 合成状态(用于前端轮询)。"""
|
||||
user_id = authenticated_user.user.id
|
||||
@@ -226,13 +219,10 @@ def get_tts_job_status(
|
||||
job = use_case.execute(job_id, user_id)
|
||||
except TTSJobNotFoundError:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="TTS job not found")
|
||||
output_url = job.output_audio_url
|
||||
if output_url:
|
||||
output_url = sign_url(output_url)
|
||||
return TTSStatusResponse(
|
||||
id=job.id,
|
||||
status=job.status,
|
||||
output_audio_url=output_url,
|
||||
output_audio_url=job.output_audio_url,
|
||||
error_message=job.error_message,
|
||||
duration=job.duration,
|
||||
retry_count=job.retry_count,
|
||||
@@ -268,7 +258,6 @@ def save_tts_job_to_library(
|
||||
tts_repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
voice_library_repository: SQLAlchemyVoiceLibraryRepository = Depends(get_voice_library_repository),
|
||||
user_repository: UserRepository = Depends(get_user_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> SaveToLibraryResponse:
|
||||
"""将已完成的 TTS 合成结果保存到配音库。
|
||||
|
||||
@@ -339,7 +328,7 @@ def save_tts_job_to_library(
|
||||
return SaveToLibraryResponse(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
audio_url=sign_url(item.audio_url) if item.audio_url else "",
|
||||
audio_url=item.audio_url,
|
||||
duration=item.duration,
|
||||
voice_id=item.voice_id,
|
||||
voice_name=item.voice_name,
|
||||
|
||||
Executable → Regular
+7
-14
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_audio_url_signer, get_cosyvoice_service, get_voice_clone_profile_repository
|
||||
from app.dependencies import get_cosyvoice_service, get_voice_clone_profile_repository
|
||||
from app.schemas.voice_clone import (
|
||||
CreateVoiceCloneRequest,
|
||||
ListVoiceCloneResponse,
|
||||
@@ -37,16 +37,13 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _to_response(profile, sign_url=None) -> VoiceCloneProfileResponse:
|
||||
source_url = profile.source_audio_url
|
||||
if sign_url and source_url:
|
||||
source_url = sign_url(source_url)
|
||||
def _to_response(profile) -> VoiceCloneProfileResponse:
|
||||
return VoiceCloneProfileResponse(
|
||||
id=profile.id,
|
||||
user_id=profile.user_id,
|
||||
name=profile.name,
|
||||
description=profile.description,
|
||||
source_audio_url=source_url,
|
||||
source_audio_url=profile.source_audio_url,
|
||||
voice_id=profile.voice_id,
|
||||
voice_model=profile.voice_model,
|
||||
language=profile.language,
|
||||
@@ -77,7 +74,6 @@ def create_voice_clone(
|
||||
request: CreateVoiceCloneRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
workflow: VoiceCloneWorkflowService = Depends(_get_workflow_service),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceCloneProfileResponse:
|
||||
"""创建音色克隆任务。
|
||||
|
||||
@@ -113,7 +109,7 @@ def create_voice_clone(
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Failed to mark profile as failed after dispatch error: {inner_e}")
|
||||
|
||||
return _to_response(profile, sign_url)
|
||||
return _to_response(profile)
|
||||
|
||||
|
||||
@router.get("", response_model=ListVoiceCloneResponse)
|
||||
@@ -123,14 +119,13 @@ def list_voice_clones(
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repository: SQLAlchemyVoiceCloneProfileRepository = Depends(get_voice_clone_profile_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> ListVoiceCloneResponse:
|
||||
"""获取用户的音色克隆列表。"""
|
||||
user_id = authenticated_user.user.id
|
||||
use_case = ListVoiceClonesUseCase(repository)
|
||||
items, total = use_case.execute(user_id, status=status_filter, skip=skip, limit=limit)
|
||||
return ListVoiceCloneResponse(
|
||||
items=[_to_response(p, sign_url) for p in items],
|
||||
items=[_to_response(p) for p in items],
|
||||
total=total,
|
||||
)
|
||||
|
||||
@@ -140,7 +135,6 @@ def get_voice_clone(
|
||||
clone_id: str,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
repository: SQLAlchemyVoiceCloneProfileRepository = Depends(get_voice_clone_profile_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceCloneProfileResponse:
|
||||
"""获取音色克隆详情。"""
|
||||
user_id = authenticated_user.user.id
|
||||
@@ -149,7 +143,7 @@ def get_voice_clone(
|
||||
profile = use_case.execute(clone_id, user_id)
|
||||
except VoiceCloneNotFoundError:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Voice clone not found")
|
||||
return _to_response(profile, sign_url)
|
||||
return _to_response(profile)
|
||||
|
||||
|
||||
@router.get("/{clone_id}/status", response_model=VoiceCloneStatusResponse)
|
||||
@@ -198,7 +192,6 @@ def retry_voice_clone(
|
||||
clone_id: str,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
workflow: VoiceCloneWorkflowService = Depends(_get_workflow_service),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceCloneProfileResponse:
|
||||
"""重试失败的音色克隆。
|
||||
|
||||
@@ -231,4 +224,4 @@ def retry_voice_clone(
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Failed to mark profile as failed after dispatch error: {inner_e}")
|
||||
|
||||
return _to_response(profile, sign_url)
|
||||
return _to_response(profile)
|
||||
|
||||
Executable → Regular
+10
-22
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
from typing import Literal, Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_audio_url_signer, get_db_session, get_user_repository
|
||||
from app.dependencies import get_db_session, get_user_repository
|
||||
from app.schemas.voice import (
|
||||
PresetVoiceItemResponse,
|
||||
PresetVoiceListResponse,
|
||||
@@ -50,10 +50,7 @@ def _get_clone_profile_repository(session: Session = Depends(get_db_session)) ->
|
||||
return SQLAlchemyVoiceCloneProfileRepository(session)
|
||||
|
||||
|
||||
def _to_response(item, sign_url=None) -> VoiceLibraryItemResponse:
|
||||
audio = item.audio_url
|
||||
if sign_url and audio:
|
||||
audio = sign_url(audio)
|
||||
def _to_response(item) -> VoiceLibraryItemResponse:
|
||||
return VoiceLibraryItemResponse(
|
||||
id=item.id,
|
||||
user_id=item.user_id,
|
||||
@@ -62,7 +59,7 @@ def _to_response(item, sign_url=None) -> VoiceLibraryItemResponse:
|
||||
voice_provider=item.voice_provider,
|
||||
voice_id=item.voice_id,
|
||||
voice_name=item.voice_name,
|
||||
audio_url=audio,
|
||||
audio_url=item.audio_url,
|
||||
duration=item.duration,
|
||||
file_size=item.file_size,
|
||||
status=item.status,
|
||||
@@ -73,20 +70,16 @@ def _to_response(item, sign_url=None) -> VoiceLibraryItemResponse:
|
||||
)
|
||||
|
||||
|
||||
def _to_unified_response(item, profile_id_map: dict | None = None, sign_url=None) -> UnifiedVoiceItemResponse:
|
||||
def _to_unified_response(item, profile_id_map: dict | None = None) -> UnifiedVoiceItemResponse:
|
||||
"""将数据库音色转换为统一响应格式。
|
||||
|
||||
Args:
|
||||
item: VoiceLibraryItem
|
||||
profile_id_map: voice_id → profile_id 映射,用于填充 voice_clone_profile_id
|
||||
sign_url: 音频URL预签名函数
|
||||
"""
|
||||
profile_id = None
|
||||
if profile_id_map and item.voice_id:
|
||||
profile_id = profile_id_map.get(item.voice_id)
|
||||
audio = item.audio_url
|
||||
if sign_url and audio:
|
||||
audio = sign_url(audio)
|
||||
return UnifiedVoiceItemResponse(
|
||||
id=item.id,
|
||||
type="clone",
|
||||
@@ -96,7 +89,7 @@ def _to_unified_response(item, profile_id_map: dict | None = None, sign_url=None
|
||||
language="zh-CN",
|
||||
voice_id=item.voice_id,
|
||||
voice_provider=item.voice_provider or "cosyvoice",
|
||||
audio_url=audio,
|
||||
audio_url=item.audio_url,
|
||||
duration=item.duration,
|
||||
file_size=item.file_size,
|
||||
status=item.status,
|
||||
@@ -147,7 +140,6 @@ def list_voices_unified(
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
voice_repository: SQLAlchemyVoiceLibraryRepository = Depends(_get_voice_repository),
|
||||
clone_profile_repository: SQLAlchemyVoiceCloneProfileRepository = Depends(_get_clone_profile_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> UnifiedVoiceListResponse:
|
||||
"""获取配音列表(预置音色 + 用户克隆音色)。
|
||||
|
||||
@@ -175,7 +167,7 @@ def list_voices_unified(
|
||||
# 批量查询 voice_id → profile_id 映射,填充 voice_clone_profile_id
|
||||
voice_ids = [i.voice_id for i in clone_items_raw if i.voice_id]
|
||||
profile_id_map = clone_profile_repository.find_profile_ids_by_voice_ids(voice_ids) if voice_ids else {}
|
||||
clone_items = [_to_unified_response(i, profile_id_map, sign_url) for i in clone_items_raw]
|
||||
clone_items = [_to_unified_response(i, profile_id_map) for i in clone_items_raw]
|
||||
|
||||
# 组装结果
|
||||
if type == "preset":
|
||||
@@ -232,7 +224,6 @@ def list_voices_legacy(
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
voice_repository: SQLAlchemyVoiceLibraryRepository = Depends(_get_voice_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> ListVoiceLibraryResponse:
|
||||
"""原有配音列表接口(仅返回用户克隆音色)。
|
||||
|
||||
@@ -242,7 +233,7 @@ def list_voices_legacy(
|
||||
use_case = ListVoiceLibraryUseCase(voice_repository)
|
||||
items, total = use_case.execute(user_id, status=status_filter, skip=skip, limit=limit)
|
||||
return ListVoiceLibraryResponse(
|
||||
items=[_to_response(i, sign_url) for i in items],
|
||||
items=[_to_response(i) for i in items],
|
||||
total=total,
|
||||
)
|
||||
|
||||
@@ -252,14 +243,13 @@ def get_voice(
|
||||
voice_id: str,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
voice_repository: SQLAlchemyVoiceLibraryRepository = Depends(_get_voice_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceLibraryItemResponse:
|
||||
user_id = authenticated_user.user.id
|
||||
use_case = GetVoiceLibraryUseCase(voice_repository)
|
||||
item = use_case.execute(voice_id, user_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Voice not found")
|
||||
return _to_response(item, sign_url)
|
||||
return _to_response(item)
|
||||
|
||||
|
||||
@router.post("", response_model=VoiceLibraryItemResponse, status_code=status.HTTP_201_CREATED)
|
||||
@@ -268,7 +258,6 @@ def create_voice(
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
voice_repository: SQLAlchemyVoiceLibraryRepository = Depends(_get_voice_repository),
|
||||
user_repository: UserRepository = Depends(get_user_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceLibraryItemResponse:
|
||||
user_id = authenticated_user.user.id
|
||||
plan_name = _get_user_plan(user_id, user_repository)
|
||||
@@ -294,7 +283,7 @@ def create_voice(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=f"配音库配额已满({exc.used}/{exc.limit}),请升级套餐",
|
||||
)
|
||||
return _to_response(item, sign_url)
|
||||
return _to_response(item)
|
||||
|
||||
|
||||
@router.put("/{voice_id}", response_model=VoiceLibraryItemResponse)
|
||||
@@ -303,7 +292,6 @@ def update_voice(
|
||||
request: UpdateVoiceLibraryRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
voice_repository: SQLAlchemyVoiceLibraryRepository = Depends(_get_voice_repository),
|
||||
sign_url=Depends(get_audio_url_signer),
|
||||
) -> VoiceLibraryItemResponse:
|
||||
user_id = authenticated_user.user.id
|
||||
command = UpdateVoiceLibraryCommand(
|
||||
@@ -325,7 +313,7 @@ def update_voice(
|
||||
item = use_case.execute(command)
|
||||
except NotFoundError:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Voice not found")
|
||||
return _to_response(item, sign_url)
|
||||
return _to_response(item)
|
||||
|
||||
|
||||
@router.delete("/{voice_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.celery_app import celery_app
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def safe_enqueue_generation_task(
|
||||
task: Any,
|
||||
generation_task_repository: Any,
|
||||
*,
|
||||
log_prefix: str = "[任务队列]",
|
||||
log_task_status: bool = False,
|
||||
) -> bool:
|
||||
"""安全入队:send_task 失败时自动把任务标记为 failed,避免留下 pending 僵尸任务。
|
||||
|
||||
Args:
|
||||
task: 生成任务对象,需有 id 属性和 mark_failed 方法
|
||||
generation_task_repository: 任务仓储,用于更新状态
|
||||
log_prefix: 日志前缀,便于区分调用来源
|
||||
log_task_status: 成功日志中是否额外打印任务状态
|
||||
|
||||
Returns:
|
||||
True 表示入队成功,False 表示入队失败(已标记为 failed)
|
||||
"""
|
||||
try:
|
||||
celery_app.send_task("worker.generate_video", args=[task.id])
|
||||
if log_task_status:
|
||||
logger.info(
|
||||
"%s 入队成功: task_id=%s, status=%s",
|
||||
log_prefix,
|
||||
task.id,
|
||||
task.status,
|
||||
)
|
||||
else:
|
||||
logger.info("%s 入队成功: task_id=%s", log_prefix, task.id)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"%s 入队失败,标记为失败: task_id=%s error=%s",
|
||||
log_prefix,
|
||||
task.id,
|
||||
e,
|
||||
exc_info=True,
|
||||
)
|
||||
try:
|
||||
task.mark_failed(f"任务入队失败: {e}")
|
||||
generation_task_repository.update(task)
|
||||
except Exception as update_err:
|
||||
logger.error(
|
||||
"%s 入队失败后更新状态也失败: task_id=%s error=%s",
|
||||
log_prefix,
|
||||
task.id,
|
||||
update_err,
|
||||
exc_info=True,
|
||||
)
|
||||
return False
|
||||
Regular → Executable
-19
@@ -207,7 +207,6 @@ def get_cosyvoice_service():
|
||||
能被 CosyVoice 服务器下载。
|
||||
"""
|
||||
from app.core.storage import get_storage_service
|
||||
|
||||
from packages.application.cosyvoice_service import CosyVoiceService
|
||||
|
||||
storage = get_storage_service()
|
||||
@@ -217,21 +216,3 @@ def get_cosyvoice_service():
|
||||
return storage.get_download_url(url, expires_seconds=86400)
|
||||
|
||||
return CosyVoiceService(audio_url_signer=_sign_audio_url)
|
||||
|
||||
|
||||
def get_audio_url_signer():
|
||||
"""提供音频URL预签名函数(24小时有效期)。
|
||||
|
||||
用于所有 API 返回给前端的音频 URL,确保私有 OSS bucket 下可正常访问。
|
||||
空 URL、非 OSS URL 直接原样返回;签名失败时回退到原始 URL。
|
||||
"""
|
||||
from app.core.storage import get_storage_service
|
||||
|
||||
storage = get_storage_service()
|
||||
|
||||
def sign_audio_url(url: str) -> str:
|
||||
if not url:
|
||||
return url
|
||||
return storage.get_download_url(url, expires_seconds=86400)
|
||||
|
||||
return sign_audio_url
|
||||
|
||||
@@ -314,9 +314,7 @@ class UnifiedRenderService:
|
||||
# 有效时长 = min(指定时长, 实际时长);若均未设置则跳过
|
||||
effective_duration = 0.0
|
||||
if clip.duration > 0:
|
||||
effective_duration = (
|
||||
min(clip.duration, clip.actual_duration) if clip.actual_duration > 0 else clip.duration
|
||||
)
|
||||
effective_duration = min(clip.duration, clip.actual_duration) if clip.actual_duration > 0 else clip.duration
|
||||
elif clip.actual_duration > 0:
|
||||
effective_duration = clip.actual_duration
|
||||
|
||||
|
||||
@@ -778,12 +778,14 @@ def generate_video(self, task_id: str) -> dict:
|
||||
verify_url = get_signed_download_url(file_url, expires_seconds=300) or file_url
|
||||
if not _verify_url_accessible(verify_url):
|
||||
# 预签名 URL 也访问失败时,退一步用 object_exists 确认上传成功
|
||||
from video_processing.oss_helpers import normalize_storage_key, oss_bucket
|
||||
from video_processing.oss_helpers import oss_bucket, normalize_storage_key
|
||||
|
||||
bucket = oss_bucket()
|
||||
key = normalize_storage_key(file_url)
|
||||
if bucket and bucket.object_exists(key):
|
||||
logger.info("URL 校验失败但 object_exists 确认文件存在,视为上传成功: storage_key=%s", key)
|
||||
logger.info(
|
||||
"URL 校验失败但 object_exists 确认文件存在,视为上传成功: storage_key=%s", key
|
||||
)
|
||||
if gen_task:
|
||||
gen_task.append_log("OSS上传", "URL校验降级: object_exists确认存在", level="WARN")
|
||||
else:
|
||||
|
||||
@@ -4,7 +4,6 @@ import logging
|
||||
|
||||
from celery import Task
|
||||
from celery.exceptions import Retry
|
||||
from video_processing.oss_helpers import get_signed_download_url
|
||||
from worker_app.celery_app import celery_app
|
||||
from worker_app.db import SessionLocal
|
||||
|
||||
@@ -17,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__)
|
||||
|
||||
|
||||
@@ -70,21 +70,21 @@ class CosyVoiceService:
|
||||
- 音色克隆: 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-flash)
|
||||
- 语音合成: 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",
|
||||
model="cosyvoice-v3-flash",
|
||||
model="cosyvoice-v3.5-plus",
|
||||
)
|
||||
|
||||
# 音色克隆
|
||||
result = service.clone_voice(audio_url="https://example.com/audio.mp3")
|
||||
|
||||
# 语音合成
|
||||
result = service.synthesize_speech(text="你好世界", voice_id="longxiaochun_v3")
|
||||
result = service.synthesize_speech(text="你好世界", voice_id="longxiaochun")
|
||||
"""
|
||||
|
||||
# 音色状态轮询配置
|
||||
@@ -121,49 +121,16 @@ class CosyVoiceService:
|
||||
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._clone_model = clone_model or getattr(
|
||||
settings, "cosyvoice_clone_model", "voice-enrollment"
|
||||
)
|
||||
self._audio_url_signer = audio_url_signer
|
||||
|
||||
# base_url 规范化:去掉末尾的路径残留(兼容旧版配置)
|
||||
# 旧版 .env 模板中 base_url 包含 /services/aigc/text2audio 完整路径,
|
||||
# 新版只需 /api/v1,具体路径由代码拼接。这里自动修正,避免配置滞后导致418。
|
||||
if "/services/aigc/text2audio" in self._base_url:
|
||||
old_url = self._base_url
|
||||
# 截取到 /api/v1 为止
|
||||
idx = self._base_url.find("/api/v1")
|
||||
if idx >= 0:
|
||||
self._base_url = self._base_url[: idx + len("/api/v1")]
|
||||
logger.warning(
|
||||
"[CosyVoice Config] base_url包含旧版text2audio路径,已自动修正: " "%s -> %s",
|
||||
old_url,
|
||||
self._base_url,
|
||||
)
|
||||
|
||||
self._client = http_client or httpx.Client(
|
||||
timeout=httpx.Timeout(60.0, connect=10.0),
|
||||
)
|
||||
self._owns_client = http_client is None
|
||||
|
||||
# 启动时打印配置(脱敏),方便排查环境变量覆盖问题
|
||||
if self._owns_client:
|
||||
masked_key = ""
|
||||
if self._api_key:
|
||||
if len(self._api_key) > 8:
|
||||
masked_key = f"{self._api_key[:4]}...{self._api_key[-4:]}"
|
||||
else:
|
||||
masked_key = "***"
|
||||
logger.info(
|
||||
"[CosyVoice Config] 初始化配置: "
|
||||
"model=%s, base_url=%s, default_voice=%s, "
|
||||
"sample_rate=%d, format=%s, api_key=%s",
|
||||
self._model,
|
||||
self._base_url,
|
||||
getattr(settings, "cosyvoice_voice", "(unset)"),
|
||||
settings.cosyvoice_sample_rate,
|
||||
settings.cosyvoice_format,
|
||||
masked_key or "(empty)",
|
||||
)
|
||||
|
||||
def __enter__(self) -> CosyVoiceService:
|
||||
return self
|
||||
|
||||
@@ -234,7 +201,8 @@ class CosyVoiceService:
|
||||
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])
|
||||
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)
|
||||
|
||||
@@ -355,7 +323,9 @@ class CosyVoiceService:
|
||||
while attempts < self.CLONE_MAX_POLL_ATTEMPTS:
|
||||
elapsed = time.time() - start_time
|
||||
if elapsed > timeout:
|
||||
raise CosyVoiceTimeoutError(f"音色克隆任务超时({timeout}秒): voice_id={voice_id}")
|
||||
raise CosyVoiceTimeoutError(
|
||||
f"音色克隆任务超时({timeout}秒): voice_id={voice_id}"
|
||||
)
|
||||
|
||||
result = self.query_voice_status(voice_id)
|
||||
status = result.get("status", "").upper()
|
||||
@@ -363,7 +333,9 @@ class CosyVoiceService:
|
||||
if status == "OK":
|
||||
return {"voice_id": voice_id}
|
||||
elif status == "UNDEPLOYED":
|
||||
raise CosyVoiceError(f"音色克隆任务失败(审核未通过): voice_id={voice_id}")
|
||||
raise CosyVoiceError(
|
||||
f"音色克隆任务失败(审核未通过): voice_id={voice_id}"
|
||||
)
|
||||
elif status in ("DEPLOYING", "PENDING", "PROCESSING", ""):
|
||||
# 继续轮询
|
||||
time.sleep(self.CLONE_POLL_INTERVAL)
|
||||
@@ -373,7 +345,9 @@ class CosyVoiceService:
|
||||
time.sleep(self.CLONE_POLL_INTERVAL)
|
||||
attempts += 1
|
||||
|
||||
raise CosyVoiceTimeoutError(f"音色克隆任务轮询次数超限: voice_id={voice_id}")
|
||||
raise CosyVoiceTimeoutError(
|
||||
f"音色克隆任务轮询次数超限: voice_id={voice_id}"
|
||||
)
|
||||
|
||||
def clone_voice(
|
||||
self,
|
||||
@@ -488,7 +462,9 @@ class CosyVoiceService:
|
||||
request_id = response.get("request_id", "")
|
||||
|
||||
if not audio_url:
|
||||
raise CosyVoiceError(f"CosyVoice API 未返回 audio_url: {response}")
|
||||
raise CosyVoiceError(
|
||||
f"CosyVoice API 未返回 audio_url: {response}"
|
||||
)
|
||||
|
||||
return {
|
||||
"task_id": "", # 同步接口无 task_id,兼容旧接口
|
||||
@@ -498,7 +474,9 @@ class CosyVoiceService:
|
||||
"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:
|
||||
"""轮询合成任务(同步接口无需轮询,保留兼容).
|
||||
|
||||
CosyVoice SpeechSynthesizer 非流式接口是同步的,
|
||||
@@ -507,7 +485,10 @@ class CosyVoiceService:
|
||||
Raises:
|
||||
CosyVoiceError: 同步接口无需轮询
|
||||
"""
|
||||
raise CosyVoiceError("CosyVoice 非流式合成接口是同步的,无需轮询. " "请直接使用 submit_synthesize_task().")
|
||||
raise CosyVoiceError(
|
||||
"CosyVoice 非流式合成接口是同步的,无需轮询. "
|
||||
"请直接使用 submit_synthesize_task()."
|
||||
)
|
||||
|
||||
def synthesize_speech(
|
||||
self,
|
||||
@@ -608,22 +589,6 @@ class CosyVoiceService:
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
# DEBUG: 打印完整请求信息,用于排查418错误
|
||||
import json as json_lib
|
||||
|
||||
safe_headers = {k: v for k, v in headers.items()}
|
||||
if "Authorization" in safe_headers:
|
||||
token = safe_headers["Authorization"]
|
||||
if len(token) > 20:
|
||||
safe_headers["Authorization"] = token[:13] + "..." + token[-4:]
|
||||
logger.info(
|
||||
"[CosyVoice Debug] 请求详情: " "method=%s, url=%s, headers=%s, body=%s",
|
||||
method,
|
||||
url,
|
||||
safe_headers,
|
||||
json_lib.dumps(json, ensure_ascii=False) if json else "None",
|
||||
)
|
||||
|
||||
last_error: Optional[Exception] = None
|
||||
|
||||
for attempt in range(self.MAX_RETRIES):
|
||||
@@ -636,18 +601,13 @@ class CosyVoiceService:
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
# DEBUG: 打印响应状态和完整响应体
|
||||
logger.info(
|
||||
"[CosyVoice Debug] 响应详情: " "status=%d, body=%s",
|
||||
response.status_code,
|
||||
response.text[:2000], # 最多2000字符,避免日志过大
|
||||
)
|
||||
|
||||
# 处理响应
|
||||
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
|
||||
@@ -655,12 +615,19 @@ class CosyVoiceService:
|
||||
body = response.json()
|
||||
code = body.get("code", "")
|
||||
message = body.get("message", "")
|
||||
raise CosyVoiceError(f"CosyVoice API 参数错误: HTTP 400, " f"code={code}, message={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}")
|
||||
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(
|
||||
"CosyVoice API 失败 (尝试 %d/%d): HTTP %d",
|
||||
attempt + 1,
|
||||
@@ -670,7 +637,8 @@ class CosyVoiceService:
|
||||
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:
|
||||
|
||||
@@ -219,7 +219,9 @@ class TTSWorkflowService:
|
||||
|
||||
# 新接口(同步):没有 task_id,重新合成
|
||||
if not task_id:
|
||||
logger.info(f"TTS 任务无 task_id,重新同步合成: job_id={job_id}")
|
||||
logger.info(
|
||||
f"TTS 任务无 task_id,重新同步合成: job_id={job_id}"
|
||||
)
|
||||
return self._resynthesize_and_complete(job)
|
||||
|
||||
# 旧接口遗留的 task_id,尝试轮询(兼容过渡)
|
||||
@@ -233,7 +235,9 @@ class TTSWorkflowService:
|
||||
)
|
||||
except CosyVoiceError:
|
||||
# 旧接口轮询失败,重新同步合成
|
||||
logger.warning(f"旧 task_id 轮询失败,重新同步合成: job_id={job_id}, task_id={task_id}")
|
||||
logger.warning(
|
||||
f"旧 task_id 轮询失败,重新同步合成: job_id={job_id}, task_id={task_id}"
|
||||
)
|
||||
return self._resynthesize_and_complete(job)
|
||||
|
||||
def process_synthesis_result(
|
||||
@@ -520,7 +524,10 @@ class TTSWorkflowService:
|
||||
missing_indices = [i for i in range(segment_count) if results[i] is None]
|
||||
|
||||
if missing_indices:
|
||||
logger.info(f"分段任务重新合成缺失段: job_id={job.id}, " f"缺失={len(missing_indices)}/{segment_count}")
|
||||
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:
|
||||
@@ -543,8 +550,13 @@ class TTSWorkflowService:
|
||||
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}")
|
||||
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)
|
||||
|
||||
# 所有分段完成,下载合并
|
||||
@@ -552,7 +564,9 @@ class TTSWorkflowService:
|
||||
try:
|
||||
merged_data, total_duration = self._download_and_merge_segments(results, job)
|
||||
|
||||
permanent_url, storage_key = self._upload_merged_to_oss(merged_data, job.user_id, job.id, job.format)
|
||||
permanent_url, storage_key = self._upload_merged_to_oss(
|
||||
merged_data, job.user_id, job.id, job.format
|
||||
)
|
||||
|
||||
job.mark_completed(
|
||||
output_audio_url=permanent_url,
|
||||
@@ -561,7 +575,10 @@ class TTSWorkflowService:
|
||||
file_size=len(merged_data),
|
||||
)
|
||||
job = self.repository.update(job)
|
||||
logger.info(f"分段合成完成(重新合成路径): job_id={job.id}, " f"merged_size={len(merged_data)}")
|
||||
logger.info(
|
||||
f"分段合成完成(重新合成路径): job_id={job.id}, "
|
||||
f"merged_size={len(merged_data)}"
|
||||
)
|
||||
return job
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -133,9 +133,7 @@ class VoiceCloneWorkflowService:
|
||||
|
||||
profile.metadata = task_metadata
|
||||
profile = self.repository.update(profile)
|
||||
logger.info(
|
||||
f"音色克隆任务已提交: profile_id={profile.id}, " f"voice_id={submit_result.get('voice_id')}"
|
||||
)
|
||||
logger.info(f"音色克隆任务已提交: profile_id={profile.id}, " f"voice_id={submit_result.get('voice_id')}")
|
||||
|
||||
except (CosyVoiceError, CosyVoiceAuthError) as e:
|
||||
# CosyVoice 提交失败,标记为 failed
|
||||
|
||||
Executable → Regular
+9
-9
@@ -16,7 +16,7 @@ class PresetVoice:
|
||||
"""预置音色定义。
|
||||
|
||||
Attributes:
|
||||
voice_id: CosyVoice 模型音色名(如 longxiaochun_v3)
|
||||
voice_id: CosyVoice 模型音色名(如 longxiaochun)
|
||||
name: 中文展示名
|
||||
description: 音色描述
|
||||
gender: 性别(male/female)
|
||||
@@ -49,7 +49,7 @@ class PresetVoice:
|
||||
# 预置音色列表(阿里云 CosyVoice 真实可用音色)
|
||||
PRESET_VOICES: list[PresetVoice] = [
|
||||
PresetVoice(
|
||||
voice_id="longxiaochun_v3",
|
||||
voice_id="longxiaochun",
|
||||
name="龙小淳",
|
||||
description="温柔女声,适合情感类内容",
|
||||
gender="female",
|
||||
@@ -57,7 +57,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["温柔", "女声", "情感"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longxiaoxia_v3",
|
||||
voice_id="longxiaoxia",
|
||||
name="龙小夏",
|
||||
description="知性女声,适合新闻播报",
|
||||
gender="female",
|
||||
@@ -65,7 +65,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["知性", "女声", "播报"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longxiaochen_v3",
|
||||
voice_id="longxiaochen",
|
||||
name="龙小晨",
|
||||
description="磁性男声,适合有声书",
|
||||
gender="male",
|
||||
@@ -73,7 +73,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["磁性", "男声", "有声书"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longyue_v3",
|
||||
voice_id="longyue",
|
||||
name="龙悦",
|
||||
description="甜美女声,适合广告配音",
|
||||
gender="female",
|
||||
@@ -81,7 +81,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["甜美", "女声", "广告"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longshu_v3",
|
||||
voice_id="longshu",
|
||||
name="龙书",
|
||||
description="沉稳男声,适合教育讲解",
|
||||
gender="male",
|
||||
@@ -89,7 +89,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["沉稳", "男声", "教育"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longjing_v3",
|
||||
voice_id="longjing",
|
||||
name="龙静",
|
||||
description="优雅女声,适合纪录片解说",
|
||||
gender="female",
|
||||
@@ -97,7 +97,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["优雅", "女声", "纪录片"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longbo_v3",
|
||||
voice_id="longbo",
|
||||
name="龙博",
|
||||
description="浑厚男声,适合科技类内容",
|
||||
gender="male",
|
||||
@@ -105,7 +105,7 @@ PRESET_VOICES: list[PresetVoice] = [
|
||||
tags=["浑厚", "男声", "科技"],
|
||||
),
|
||||
PresetVoice(
|
||||
voice_id="longtian_v3",
|
||||
voice_id="longtian",
|
||||
name="龙甜",
|
||||
description="活泼女声,适合短视频配音",
|
||||
gender="female",
|
||||
|
||||
Executable → Regular
+2
-2
@@ -32,8 +32,8 @@ class SharedSettings(BaseSettings):
|
||||
# CosyVoice (阿里云百炼语音合成)
|
||||
cosyvoice_api_key: str = ""
|
||||
cosyvoice_base_url: str = "https://dashscope.aliyuncs.com/api/v1"
|
||||
cosyvoice_model: str = "cosyvoice-v3-flash"
|
||||
cosyvoice_voice: str = "longxiaochun_v3" # 默认音色(v3 系列系统音色带 _v3 后缀)
|
||||
cosyvoice_model: str = "cosyvoice-v3.5-plus"
|
||||
cosyvoice_voice: str = "longxiaochun" # 默认音色
|
||||
cosyvoice_sample_rate: int = 22050
|
||||
cosyvoice_format: str = "mp3" # 输出格式:mp3/wav/pcm
|
||||
# 音色克隆模型名(固定为 voice-enrollment)
|
||||
|
||||
@@ -1,39 +1,7 @@
|
||||
[tool.black]
|
||||
line-length = 120
|
||||
target-version = ["py312"]
|
||||
extend-exclude = '''
|
||||
(
|
||||
\.git
|
||||
| \.cache
|
||||
| \.pytest_cache
|
||||
| \.mypy_cache
|
||||
| __pycache__
|
||||
| node_modules
|
||||
| \.venv
|
||||
| venv
|
||||
| build
|
||||
| dist
|
||||
| \.next
|
||||
| out
|
||||
| coverage
|
||||
)
|
||||
'''
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
line_length = 120
|
||||
extend_skip_glob = [
|
||||
".git/**",
|
||||
".cache/**",
|
||||
".pytest_cache/**",
|
||||
".mypy_cache/**",
|
||||
"__pycache__/**",
|
||||
"node_modules/**",
|
||||
".venv/**",
|
||||
"venv/**",
|
||||
"build/**",
|
||||
"dist/**",
|
||||
".next/**",
|
||||
"out/**",
|
||||
"coverage/**",
|
||||
]
|
||||
|
||||
@@ -3,7 +3,6 @@ max-line-length = 120
|
||||
extend-ignore = E203,W503,E501,E302,E402,E722,W291,W293,F401,F403,F405,F841
|
||||
exclude =
|
||||
.git,
|
||||
.cache,
|
||||
__pycache__,
|
||||
.venv,
|
||||
.venv-ci-root,
|
||||
|
||||
@@ -241,7 +241,7 @@ def client():
|
||||
class TestCreateGenerationTask:
|
||||
"""创建生成任务端点测试。"""
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_create_task_success(self, mock_celery, client):
|
||||
"""正常创建生成任务成功。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -270,7 +270,7 @@ class TestCreateGenerationTask:
|
||||
assert mock_celery.send_task.called
|
||||
assert mock_celery.send_task.call_args[0][0] == "worker.generate_video"
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_create_batch_tasks(self, mock_celery, client):
|
||||
"""批量创建多个生成任务。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -347,7 +347,7 @@ class TestListGenerationTasks:
|
||||
|
||||
def _create_task(self, client, task_suffix: str = "1"):
|
||||
"""辅助方法:创建一个生成任务。"""
|
||||
with patch("app.core.task_enqueue.celery_app") as mock_celery:
|
||||
with patch("app.api.routes.generation_tasks.celery_app") as mock_celery:
|
||||
mock_celery.send_task = MagicMock()
|
||||
resp = client.post(
|
||||
"/api/v1/generation/tasks",
|
||||
@@ -368,7 +368,7 @@ class TestListGenerationTasks:
|
||||
assert "items" in data
|
||||
assert data["items"] == []
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_list_returns_user_tasks(self, mock_celery, client):
|
||||
"""返回当前用户的生成任务列表。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -406,7 +406,7 @@ class TestGetGenerationTask:
|
||||
"""获取生成任务详情端点测试。"""
|
||||
|
||||
def _create_task(self, client) -> str:
|
||||
with patch("app.core.task_enqueue.celery_app") as mock_celery:
|
||||
with patch("app.api.routes.generation_tasks.celery_app") as mock_celery:
|
||||
mock_celery.send_task = MagicMock()
|
||||
resp = client.post(
|
||||
"/api/v1/generation/tasks",
|
||||
@@ -449,7 +449,7 @@ class TestListGenerationResults:
|
||||
"""列出生成结果端点测试。"""
|
||||
|
||||
def _create_task(self, client) -> str:
|
||||
with patch("app.core.task_enqueue.celery_app") as mock_celery:
|
||||
with patch("app.api.routes.generation_tasks.celery_app") as mock_celery:
|
||||
mock_celery.send_task = MagicMock()
|
||||
resp = client.post(
|
||||
"/api/v1/generation/tasks",
|
||||
@@ -489,7 +489,7 @@ class TestRetryGenerationTask:
|
||||
|
||||
def _create_failed_task(self, client) -> str:
|
||||
"""创建一个失败状态的任务。"""
|
||||
with patch("app.core.task_enqueue.celery_app") as mock_celery:
|
||||
with patch("app.api.routes.generation_tasks.celery_app") as mock_celery:
|
||||
mock_celery.send_task = MagicMock()
|
||||
resp = client.post(
|
||||
"/api/v1/generation/tasks",
|
||||
@@ -509,7 +509,7 @@ class TestRetryGenerationTask:
|
||||
# 让我们直接通过 retry 测试来验证
|
||||
return task_id
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_retry_failed_task(self, mock_celery, client):
|
||||
"""重试失败的任务成功。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -539,7 +539,7 @@ class TestRetryGenerationTask:
|
||||
assert resp.status_code == 404
|
||||
assert "not found" in resp.json()["detail"].lower()
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_retry_completed_task_returns_409(self, mock_celery, client):
|
||||
"""重试已完成的任务返回 409。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -568,7 +568,7 @@ class TestRetryGenerationTask:
|
||||
class TestGenerationTaskFlow:
|
||||
"""生成任务完整流程集成测试。"""
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.generation_tasks.celery_app")
|
||||
def test_create_list_detail_results_flow(self, mock_celery, client):
|
||||
"""测试创建 → 列表 → 详情 → 结果 完整流程。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
|
||||
@@ -428,7 +428,7 @@ class TestRetryProjectTask:
|
||||
assert resp.status_code == 400
|
||||
assert "Unsupported" in resp.json()["detail"]
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.task_center.celery_app")
|
||||
def test_retry_failed_generation_task(self, mock_celery, client):
|
||||
"""重试失败的 generation 任务成功。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
@@ -581,7 +581,7 @@ class TestRetryProjectTask:
|
||||
class TestTaskCenterCrossEndpoint:
|
||||
"""任务中心跨端点集成测试。"""
|
||||
|
||||
@patch("app.core.task_enqueue.celery_app")
|
||||
@patch("app.api.routes.task_center.celery_app")
|
||||
def test_list_then_retry_then_list(self, mock_celery, client):
|
||||
"""列出任务 → 重试失败任务 → 再列出验证新任务。"""
|
||||
mock_celery.send_task = MagicMock()
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
"""测试音频URL预签名逻辑。
|
||||
|
||||
验证所有 API 返回的音频 URL 都会经过 OSS 预签名(24小时有效期),
|
||||
确保私有 bucket 下的音频文件前端可正常访问。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestAudioUrlSigner:
|
||||
"""测试音频URL签名函数的行为。"""
|
||||
|
||||
def _make_signer(self, mock_storage):
|
||||
"""构造一个签名函数(模拟 get_audio_url_signer 的逻辑)。"""
|
||||
|
||||
def sign_audio_url(url: str) -> str:
|
||||
if not url:
|
||||
return url
|
||||
return mock_storage.get_download_url(url, expires_seconds=86400)
|
||||
|
||||
return sign_audio_url
|
||||
|
||||
def test_empty_url_returns_empty(self):
|
||||
"""空URL直接返回,不调用签名。"""
|
||||
mock_storage = MagicMock()
|
||||
signer = self._make_signer(mock_storage)
|
||||
|
||||
result = signer("")
|
||||
assert result == ""
|
||||
mock_storage.get_download_url.assert_not_called()
|
||||
|
||||
def test_none_url_returns_none(self):
|
||||
"""None URL直接返回(有些字段可能为None)。"""
|
||||
mock_storage = MagicMock()
|
||||
signer = self._make_signer(mock_storage)
|
||||
|
||||
result = signer(None) # type: ignore
|
||||
assert result is None
|
||||
mock_storage.get_download_url.assert_not_called()
|
||||
|
||||
def test_valid_url_gets_signed_24h(self):
|
||||
"""有效URL会调用 storage.get_download_url,有效期24小时(86400秒)。"""
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.get_download_url.return_value = (
|
||||
"https://bucket.oss-cn-hangzhou.aliyuncs.com/audio/test.mp3?signature=xxx"
|
||||
)
|
||||
signer = self._make_signer(mock_storage)
|
||||
|
||||
result = signer("https://bucket.oss-cn-hangzhou.aliyuncs.com/audio/test.mp3")
|
||||
|
||||
assert "signature=xxx" in result
|
||||
mock_storage.get_download_url.assert_called_once_with(
|
||||
"https://bucket.oss-cn-hangzhou.aliyuncs.com/audio/test.mp3",
|
||||
expires_seconds=86400,
|
||||
)
|
||||
|
||||
def test_storage_key_format_also_works(self):
|
||||
"""纯 storage key 格式也能正常签名(storage内部会处理)。"""
|
||||
mock_storage = MagicMock()
|
||||
mock_storage.get_download_url.return_value = "https://signed-url/audio.mp3?sig=xxx"
|
||||
signer = self._make_signer(mock_storage)
|
||||
|
||||
result = signer("audio/test.mp3")
|
||||
|
||||
assert result == "https://signed-url/audio.mp3?sig=xxx"
|
||||
mock_storage.get_download_url.assert_called_once_with(
|
||||
"audio/test.mp3",
|
||||
expires_seconds=86400,
|
||||
)
|
||||
|
||||
def test_signer_via_dependencies_module(self):
|
||||
"""通过 dependencies 模块获取 signer,验证集成正确。"""
|
||||
from app.core.storage import OSSStorageService
|
||||
|
||||
mock_svc = MagicMock(spec=OSSStorageService)
|
||||
mock_svc.get_download_url.return_value = "https://signed/a.mp3?sig=123"
|
||||
|
||||
# 替换全局单例
|
||||
with patch("app.core.storage._storage_service", mock_svc):
|
||||
from app.dependencies import get_audio_url_signer
|
||||
|
||||
signer = get_audio_url_signer()
|
||||
result = signer("test/audio.mp3")
|
||||
|
||||
assert result == "https://signed/a.mp3?sig=123"
|
||||
mock_svc.get_download_url.assert_called_once_with(
|
||||
"test/audio.mp3",
|
||||
expires_seconds=86400,
|
||||
)
|
||||
@@ -23,7 +23,7 @@ def _make_service(
|
||||
*,
|
||||
api_key: str = "test-api-key",
|
||||
base_url: str = "https://dashscope.aliyuncs.com/api/v1",
|
||||
model: str = "cosyvoice-v3-flash",
|
||||
model: str = "cosyvoice-v3.5-plus",
|
||||
clone_model: str = "voice-enrollment",
|
||||
http_client: httpx.Client | None = None,
|
||||
audio_url_signer=None,
|
||||
@@ -78,7 +78,7 @@ class TestSubmitCloneTask:
|
||||
200,
|
||||
{
|
||||
"output": {
|
||||
"voice_id": "cosyvoice-v3-flash-clone-abc123",
|
||||
"voice_id": "cosyvoice-v3.5-plus-clone-abc123",
|
||||
"status": "DEPLOYING",
|
||||
},
|
||||
"usage": {"count": 1},
|
||||
@@ -92,7 +92,7 @@ class TestSubmitCloneTask:
|
||||
voice_name="myvoice",
|
||||
)
|
||||
|
||||
assert result["voice_id"] == "cosyvoice-v3-flash-clone-abc123"
|
||||
assert result["voice_id"] == "cosyvoice-v3.5-plus-clone-abc123"
|
||||
assert result["status"] == "DEPLOYING"
|
||||
assert result["request_id"] == "req-001"
|
||||
|
||||
@@ -104,7 +104,7 @@ class TestSubmitCloneTask:
|
||||
payload = call_args.kwargs["json"]
|
||||
assert payload["model"] == "voice-enrollment"
|
||||
assert payload["input"]["action"] == "create_voice"
|
||||
assert payload["input"]["target_model"] == "cosyvoice-v3-flash"
|
||||
assert payload["input"]["target_model"] == "cosyvoice-v3.5-plus"
|
||||
assert payload["input"]["prefix"] == "myvoice"
|
||||
assert payload["input"]["url"] == "https://example.com/audio.wav"
|
||||
assert payload["input"]["language_hints"] == ["zh"]
|
||||
@@ -197,11 +197,7 @@ class TestSubmitCloneTask:
|
||||
|
||||
payload = mock_client.request.call_args.kwargs["json"]
|
||||
# 中文和特殊字符被过滤,剩下字母数字
|
||||
assert (
|
||||
payload["input"]["prefix"] == "2024"
|
||||
or payload["input"]["prefix"] == "clone"
|
||||
or len(payload["input"]["prefix"]) <= 10
|
||||
)
|
||||
assert payload["input"]["prefix"] == "2024" or payload["input"]["prefix"] == "clone" or len(payload["input"]["prefix"]) <= 10
|
||||
|
||||
def test_submit_auth_401_raises(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
@@ -233,7 +229,7 @@ class TestQueryVoiceStatus:
|
||||
{
|
||||
"output": {
|
||||
"status": "DEPLOYING",
|
||||
"target_model": "cosyvoice-v3-flash",
|
||||
"target_model": "cosyvoice-v3.5-plus",
|
||||
"gmt_create": "2026-01-01T00:00:00Z",
|
||||
"gmt_modified": "2026-01-01T00:01:00Z",
|
||||
"resource_link": "https://...",
|
||||
@@ -246,7 +242,7 @@ class TestQueryVoiceStatus:
|
||||
result = service.query_voice_status("voice-123")
|
||||
|
||||
assert result["status"] == "DEPLOYING"
|
||||
assert result["target_model"] == "cosyvoice-v3-flash"
|
||||
assert result["target_model"] == "cosyvoice-v3.5-plus"
|
||||
|
||||
# 验证请求
|
||||
payload = mock_client.request.call_args.kwargs["json"]
|
||||
@@ -257,7 +253,7 @@ class TestQueryVoiceStatus:
|
||||
def test_query_ok_status(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200, {"output": {"status": "OK", "target_model": "cosyvoice-v3-flash"}}
|
||||
200, {"output": {"status": "OK", "target_model": "cosyvoice-v3.5-plus"}}
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
@@ -282,7 +278,7 @@ class TestPollCloneTask:
|
||||
def test_poll_ok_on_first_check(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200, {"output": {"status": "OK", "target_model": "cosyvoice-v3-flash"}}
|
||||
200, {"output": {"status": "OK", "target_model": "cosyvoice-v3.5-plus"}}
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
@@ -309,7 +305,9 @@ class TestPollCloneTask:
|
||||
|
||||
def test_poll_undeployed_raises_error(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(200, {"output": {"status": "UNDEPLOYED"}})
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200, {"output": {"status": "UNDEPLOYED"}}
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
service.CLONE_POLL_INTERVAL = 0.01
|
||||
@@ -319,7 +317,9 @@ class TestPollCloneTask:
|
||||
|
||||
def test_poll_timeout_raises(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(200, {"output": {"status": "DEPLOYING"}})
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200, {"output": {"status": "DEPLOYING"}}
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
service.CLONE_POLL_INTERVAL = 0.01
|
||||
@@ -396,7 +396,9 @@ class TestSynthesizeSpeech:
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
result = service.synthesize_speech(text="你好世界", voice_id="longxiaochun_v3")
|
||||
result = service.synthesize_speech(
|
||||
text="你好世界", voice_id="longxiaochun"
|
||||
)
|
||||
|
||||
assert isinstance(result, SynthesizeResult)
|
||||
assert result.audio_url == "https://dashscope-result.oss.com/output.mp3"
|
||||
@@ -407,9 +409,9 @@ class TestSynthesizeSpeech:
|
||||
assert "/services/audio/tts/SpeechSynthesizer" in call_args.kwargs["url"]
|
||||
|
||||
payload = call_args.kwargs["json"]
|
||||
assert payload["model"] == "cosyvoice-v3-flash"
|
||||
assert payload["model"] == "cosyvoice-v3.5-plus"
|
||||
assert payload["input"]["text"] == "你好世界"
|
||||
assert payload["input"]["voice"] == "longxiaochun_v3"
|
||||
assert payload["input"]["voice"] == "longxiaochun"
|
||||
assert payload["input"]["format"] == "mp3"
|
||||
assert payload["input"]["sample_rate"] == 22050
|
||||
assert payload["input"]["rate"] == 1.0
|
||||
@@ -424,12 +426,8 @@ class TestSynthesizeSpeech:
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
service.synthesize_speech(
|
||||
text="test",
|
||||
voice_id="v1",
|
||||
sample_rate=44100,
|
||||
format="wav",
|
||||
speed=1.5,
|
||||
volume=80,
|
||||
text="test", voice_id="v1", sample_rate=44100,
|
||||
format="wav", speed=1.5, volume=80,
|
||||
)
|
||||
|
||||
payload = mock_client.request.call_args.kwargs["json"]
|
||||
@@ -465,8 +463,7 @@ class TestSynthesizeSpeech:
|
||||
"""同步接口的 submit_synthesize_task 返回空 task_id 字段(兼容旧接口)."""
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200,
|
||||
{"output": {"audio": {"url": "https://e.com/a.mp3"}}},
|
||||
200, {"output": {"audio": {"url": "https://e.com/a.mp3"}}},
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
@@ -493,7 +490,9 @@ class TestRetryLogic:
|
||||
mock_client.request.side_effect = [
|
||||
_mock_response(500, text="Server Error"),
|
||||
_mock_response(502, text="Bad Gateway"),
|
||||
_mock_response(200, {"output": {"audio": {"url": "https://e.com/a.mp3"}}}),
|
||||
_mock_response(
|
||||
200, {"output": {"audio": {"url": "https://e.com/a.mp3"}}}
|
||||
),
|
||||
]
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
@@ -548,7 +547,9 @@ class TestSanitizePrefix:
|
||||
class TestCheckTaskStatus:
|
||||
def test_check_task_status_uses_query_voice(self) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client.request.return_value = _mock_response(200, {"output": {"status": "OK"}})
|
||||
mock_client.request.return_value = _mock_response(
|
||||
200, {"output": {"status": "OK"}}
|
||||
)
|
||||
|
||||
service = _make_service(http_client=mock_client)
|
||||
result = service.check_task_status("voice-123")
|
||||
@@ -559,40 +560,3 @@ class TestCheckTaskStatus:
|
||||
# 验证走的是 query_voice 路径
|
||||
payload = mock_client.request.call_args.kwargs["json"]
|
||||
assert payload["input"]["action"] == "query_voice"
|
||||
|
||||
|
||||
# ── 配置与初始化 ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestServiceConfiguration:
|
||||
"""测试 CosyVoiceService 配置与初始化逻辑."""
|
||||
|
||||
def test_base_url_old_text2audio_path_auto_fixed(self) -> None:
|
||||
"""旧版 base_url 包含 text2audio 路径时,应自动修正为 /api/v1."""
|
||||
service = CosyVoiceService(
|
||||
api_key="test-key",
|
||||
base_url="https://dashscope.aliyuncs.com/api/v1/services/aigc/text2audio",
|
||||
model="cosyvoice-v3-flash",
|
||||
)
|
||||
# 应自动去掉 text2audio 后缀,保留到 /api/v1
|
||||
assert service._base_url == "https://dashscope.aliyuncs.com/api/v1"
|
||||
|
||||
def test_base_url_normal_unchanged(self) -> None:
|
||||
"""正常的 base_url 不应被修改."""
|
||||
url = "https://dashscope.aliyuncs.com/api/v1"
|
||||
service = CosyVoiceService(
|
||||
api_key="test-key",
|
||||
base_url=url,
|
||||
model="cosyvoice-v3-flash",
|
||||
)
|
||||
assert service._base_url == url
|
||||
|
||||
def test_base_url_workspace_domain_unchanged(self) -> None:
|
||||
"""工作空间专属域名的 base_url 不应被修改."""
|
||||
url = "https://workspace-xxx.cn-beijing.maas.aliyuncs.com/api/v1"
|
||||
service = CosyVoiceService(
|
||||
api_key="test-key",
|
||||
base_url=url,
|
||||
model="cosyvoice-v3-flash",
|
||||
)
|
||||
assert service._base_url == url
|
||||
|
||||
@@ -15,6 +15,7 @@ from video_processing.ffmpeg_utils import build_xfade_filter_chain
|
||||
# ── P0-3: build_xfade_filter_chain 安全钳制 ──────────────────────────────────
|
||||
|
||||
|
||||
|
||||
class TestBuildXfadeFilterChainSafetyClamp:
|
||||
"""验证 xfade 滤镜链的安全钳制逻辑,防止 exit 234。"""
|
||||
|
||||
@@ -123,7 +124,9 @@ class TestBuildXfadeFilterChainSafetyClamp:
|
||||
durations_found.append(float(m.group(1)))
|
||||
|
||||
# 第一个 xfade: td 必须 ≤ 0.3 (第二个输入 clip_durations[1]=0.3)
|
||||
assert durations_found[0] <= 0.3 + 0.001, f"第一个 xfade td={durations_found[0]} 超过 clip_durations[1]=0.3"
|
||||
assert durations_found[0] <= 0.3 + 0.001, (
|
||||
f"第一个 xfade td={durations_found[0]} 超过 clip_durations[1]=0.3"
|
||||
)
|
||||
# 第二个 xfade: td 可以 = 0.5 (clip_durations[2]=5.0)
|
||||
assert durations_found[1] <= 0.5 + 0.001
|
||||
assert dur > 0
|
||||
@@ -170,9 +173,9 @@ class TestBuildXfadeFilterChainSafetyClamp:
|
||||
assert dur_val >= 0.001 # 至少 1ms
|
||||
# P1 修复验证: td 不能超过第二个输入片段时长
|
||||
second_input_idx = xfade_idx + 1
|
||||
assert (
|
||||
dur_val <= durations[second_input_idx] + 0.001
|
||||
), f"td={dur_val} > clip_durations[{second_input_idx}]={durations[second_input_idx]}"
|
||||
assert dur_val <= durations[second_input_idx] + 0.001, (
|
||||
f"td={dur_val} > clip_durations[{second_input_idx}]={durations[second_input_idx]}"
|
||||
)
|
||||
xfade_idx += 1
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ── oss_bucket endpoint scheme 修复 ──────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -24,19 +25,17 @@ class TestOSSBucketEndpointScheme:
|
||||
from video_processing.oss_helpers import oss_bucket
|
||||
|
||||
mock_bucket_instance = MagicMock()
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth") as mock_auth,
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance) as mock_bucket_cls,
|
||||
):
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth") as mock_auth, patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance
|
||||
) as mock_bucket_cls:
|
||||
# 清除缓存,确保重新创建
|
||||
import video_processing.oss_helpers as oss_mod
|
||||
|
||||
@@ -46,7 +45,9 @@ class TestOSSBucketEndpointScheme:
|
||||
# 验证 endpoint 传的是带 https:// 的
|
||||
call_args = mock_bucket_cls.call_args
|
||||
endpoint_arg = call_args[0][1] # 第 2 个位置参数是 endpoint
|
||||
assert endpoint_arg.startswith("https://"), f"endpoint 应该带 https:// 前缀,实际为: {endpoint_arg}"
|
||||
assert endpoint_arg.startswith("https://"), (
|
||||
f"endpoint 应该带 https:// 前缀,实际为: {endpoint_arg}"
|
||||
)
|
||||
assert "oss-cn-hangzhou.aliyuncs.com" in endpoint_arg
|
||||
|
||||
def test_endpoint_with_https_keeps_as_is(self):
|
||||
@@ -54,19 +55,17 @@ class TestOSSBucketEndpointScheme:
|
||||
from video_processing.oss_helpers import oss_bucket
|
||||
|
||||
mock_bucket_instance = MagicMock()
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "https://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance) as mock_bucket_cls,
|
||||
):
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "https://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance
|
||||
) as mock_bucket_cls:
|
||||
import video_processing.oss_helpers as oss_mod
|
||||
|
||||
bucket = oss_bucket()
|
||||
@@ -82,19 +81,17 @@ class TestOSSBucketEndpointScheme:
|
||||
from video_processing.oss_helpers import oss_bucket
|
||||
|
||||
mock_bucket_instance = MagicMock()
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "http://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance) as mock_bucket_cls,
|
||||
):
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "http://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket_instance
|
||||
) as mock_bucket_cls:
|
||||
import video_processing.oss_helpers as oss_mod
|
||||
|
||||
bucket = oss_bucket()
|
||||
@@ -136,18 +133,16 @@ class TestGetSignedDownloadUrl:
|
||||
mock_bucket = MagicMock()
|
||||
mock_bucket.sign_url.return_value = "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/generated/test.mp4?OSSAccessKeyId=xxx&Expires=xxx&Signature=xxx"
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket),
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket
|
||||
):
|
||||
result = get_signed_download_url("generated/test.mp4", expires_seconds=3600)
|
||||
|
||||
@@ -160,24 +155,22 @@ class TestGetSignedDownloadUrl:
|
||||
from video_processing.oss_helpers import get_signed_download_url
|
||||
|
||||
mock_bucket = MagicMock()
|
||||
mock_bucket.sign_url.return_value = (
|
||||
"https://test-bucket.oss-cn-hangzhou.aliyuncs.com/generated/test.mp4?sign=xxx"
|
||||
)
|
||||
mock_bucket.sign_url.return_value = "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/generated/test.mp4?sign=xxx"
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket),
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket
|
||||
):
|
||||
result = get_signed_download_url("https://test-bucket.oss-cn-hangzhou.aliyuncs.com/generated/test.mp4")
|
||||
result = get_signed_download_url(
|
||||
"https://test-bucket.oss-cn-hangzhou.aliyuncs.com/generated/test.mp4"
|
||||
)
|
||||
|
||||
mock_bucket.sign_url.assert_called_once()
|
||||
# 验证传给 sign_url 的是纯 storage key,不是完整 URL
|
||||
@@ -200,18 +193,16 @@ class TestGetSignedDownloadUrl:
|
||||
mock_bucket = MagicMock()
|
||||
mock_bucket.sign_url.side_effect = Exception("sign failed")
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket),
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket
|
||||
):
|
||||
result = get_signed_download_url("generated/test.mp4")
|
||||
assert result is None
|
||||
@@ -232,18 +223,16 @@ class TestUploadToOSSReturnsHTTPS:
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket),
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket
|
||||
):
|
||||
result = upload_to_oss(Path("/tmp/test.mp4"), "generated/test.mp4")
|
||||
|
||||
@@ -260,18 +249,16 @@ class TestUploadToOSSReturnsHTTPS:
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "https://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
),
|
||||
patch("video_processing.oss_helpers.oss2.Auth"),
|
||||
patch("video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket),
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OSS_ACCESS_KEY_ID": "test-key",
|
||||
"OSS_ACCESS_KEY_SECRET": "test-secret",
|
||||
"OSS_ENDPOINT": "https://oss-cn-hangzhou.aliyuncs.com",
|
||||
"OSS_BUCKET_NAME": "test-bucket",
|
||||
},
|
||||
), patch("video_processing.oss_helpers.oss2.Auth"), patch(
|
||||
"video_processing.oss_helpers.oss2.Bucket", return_value=mock_bucket
|
||||
):
|
||||
result = upload_to_oss(Path("/tmp/test.mp4"), "generated/test.mp4")
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ class TestPresetVoice:
|
||||
def test_preset_voice_to_dict(self) -> None:
|
||||
"""序列化。"""
|
||||
voice = PresetVoice(
|
||||
voice_id="longxiaochun_v3",
|
||||
voice_id="longxiaochun",
|
||||
name="龙小淳",
|
||||
description="温柔女声",
|
||||
gender="female",
|
||||
@@ -73,7 +73,7 @@ class TestPresetVoice:
|
||||
|
||||
result = voice.to_dict()
|
||||
|
||||
assert result["voice_id"] == "longxiaochun_v3"
|
||||
assert result["voice_id"] == "longxiaochun"
|
||||
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_v3",
|
||||
"longxiaoxia_v3",
|
||||
"longxiaochen_v3",
|
||||
"longyue_v3",
|
||||
"longshu_v3",
|
||||
"longjing_v3",
|
||||
"longbo_v3",
|
||||
"longtian_v3",
|
||||
"longxiaochun",
|
||||
"longxiaoxia",
|
||||
"longxiaochen",
|
||||
"longyue",
|
||||
"longshu",
|
||||
"longjing",
|
||||
"longbo",
|
||||
"longtian",
|
||||
}
|
||||
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_v3")
|
||||
voice = get_preset_voice_by_id("longxiaochun")
|
||||
assert voice is not None
|
||||
assert voice.name == "龙小淳"
|
||||
assert voice.voice_id == "longxiaochun_v3"
|
||||
assert voice.voice_id == "longxiaochun"
|
||||
|
||||
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_v3") is True
|
||||
assert is_preset_voice("longxiaoxia_v3") is True
|
||||
assert is_preset_voice("longbo_v3") is True
|
||||
assert is_preset_voice("longxiaochun") is True
|
||||
assert is_preset_voice("longxiaoxia") is True
|
||||
assert is_preset_voice("longbo") is True
|
||||
|
||||
def test_is_preset_voice_false(self) -> None:
|
||||
"""判断非预置音色返回 False。"""
|
||||
|
||||
@@ -15,7 +15,7 @@ class TestTTSJobCreate:
|
||||
job = TTSJob.create(
|
||||
user_id="user_001",
|
||||
input_text="这是一段测试文本",
|
||||
voice_id="longxiaochun_v3",
|
||||
voice_id="longxiaochun",
|
||||
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_v3"
|
||||
assert job.voice_id == "longxiaochun"
|
||||
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_v3",
|
||||
voice_id="longxiaochun",
|
||||
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_v3"
|
||||
assert result["voice_id"] == "longxiaochun"
|
||||
assert result["voice_model"] == "cosyvoice-v1"
|
||||
assert result["project_id"] == "project_001"
|
||||
assert result["voice_clone_profile_id"] == "profile_001"
|
||||
|
||||
Regular → Executable
@@ -435,7 +435,8 @@ class TestBuildFilterComplex:
|
||||
last_setpts = max(setpts_positions)
|
||||
first_fps = min(fps_positions)
|
||||
assert last_setpts < first_fps, (
|
||||
f"单视频: setpts(position={last_setpts}) 应该在 fps(position={first_fps}) 之前。" f"滤镜链: {chain_str}"
|
||||
f"单视频: setpts(position={last_setpts}) 应该在 fps(position={first_fps}) 之前。"
|
||||
f"滤镜链: {chain_str}"
|
||||
)
|
||||
|
||||
def test_empty_layers_raises(self):
|
||||
|
||||
Regular → Executable
Reference in New Issue
Block a user