Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e8baa68e0 | |||
| 96b12c9b68 | |||
| 49e9791746 | |||
| 1381f94fad |
@@ -196,10 +196,3 @@ DOUBAO_MODEL=doubao-seed-1-6-250615
|
||||
DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
|
||||
DOUBAO_TIMEOUT=30
|
||||
DOUBAO_MAX_RETRIES=2
|
||||
|
||||
# ==================== 积分/会员系统 (#1895) ====================
|
||||
# 积分扣点总开关:默认 false(对现有用户零影响)。
|
||||
# P2 阶段各业务路由逐个接入 @points_gate 时,用
|
||||
# `if settings.points_enabled: ...`
|
||||
# 包裹扣点逻辑;所有路由接入完成并验证通过后再在 staging/prod 打开。
|
||||
POINTS_ENABLED=false
|
||||
|
||||
@@ -29,8 +29,6 @@ from app.services.ai_avatar_render_service import (
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -44,12 +42,10 @@ def _get_service(db: Session = Depends(get_db_session)) -> AiAvatarRenderService
|
||||
|
||||
|
||||
@router.post("", response_model=AiAvatarRenderJobResponse, status_code=201)
|
||||
@points_gate("ai_digital_human", per_unit=15)
|
||||
def create_render_job(
|
||||
body: CreateAiAvatarRenderRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
svc: AiAvatarRenderService = Depends(_get_service),
|
||||
db: Session = Depends(get_db_session),
|
||||
):
|
||||
"""提交 AI 数字人渲染任务.
|
||||
|
||||
|
||||
@@ -27,7 +27,6 @@ from packages.adapters.sqlalchemy_impl.generation_task_repository import (
|
||||
)
|
||||
from packages.application import ListGeneratedVideosByTaskUseCase
|
||||
from packages.domain.config_schemas import normalize_plan_config
|
||||
from packages.middleware.points_gate import points_gate
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
|
||||
from .templates_editor.dependencies import get_draft_plan_id, get_editor_services
|
||||
@@ -332,7 +331,6 @@ def _is_trusted_media_url(url: str) -> bool:
|
||||
|
||||
|
||||
@router.post("/generate-cover", response_model=GenerateCoverResponse)
|
||||
@points_gate("ai_cover")
|
||||
def generate_cover(
|
||||
body: GenerateCoverRequest,
|
||||
template_id: str = Query(..., description="模板 ID"),
|
||||
|
||||
@@ -43,7 +43,6 @@ from packages.application import (
|
||||
GetGenerationTaskUseCase,
|
||||
ListGeneratedVideosByTaskUseCase,
|
||||
)
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -272,7 +271,6 @@ def _variant_value(values: list[str], index: int, fallback: str = "") -> str:
|
||||
|
||||
|
||||
@router.post("/preview", response_model=BatchPreviewGenerationTaskResponse, status_code=201)
|
||||
@points_gate("ai_video", quantity_field="preview_count")
|
||||
def create_preview_generation_task(
|
||||
request: CreatePreviewGenerationTaskRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
|
||||
@@ -42,7 +42,6 @@ from packages.application import (
|
||||
ListGeneratedVideosByTaskUseCase,
|
||||
)
|
||||
from packages.domain.smart_match import smart_select_assets
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -212,7 +211,6 @@ def _resolve_project_and_library(
|
||||
|
||||
|
||||
@router.post("/tasks", response_model=BatchGenerationTaskResponse)
|
||||
@points_gate("ai_video", quantity_field="count")
|
||||
def create_generation_task(
|
||||
request: CreateGenerationTaskRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
|
||||
@@ -12,11 +12,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from datetime import UTC
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.dependencies import (
|
||||
get_db_session,
|
||||
get_voice_clone_profile_repository,
|
||||
@@ -32,9 +30,6 @@ from app.services.mediakit_client import MediaKitError
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -58,40 +53,8 @@ def _get_service(
|
||||
def create_lipsync_job(
|
||||
body: CreateLipsyncJobRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
user_id = current_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_digital_human"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
# 口型同步:TTS 模式按 script_text 估时长(240字/分钟);音频直传按 audio_duration(秒→分钟)
|
||||
if body.audio_url and body.audio_duration and body.audio_duration > 0:
|
||||
est_minutes = max(1.0, math.ceil(body.audio_duration / 60.0))
|
||||
elif body.script_text:
|
||||
est_minutes = max(1.0, math.ceil(len(body.script_text) / 240))
|
||||
else:
|
||||
est_minutes = 1.0
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(current_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(current_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
"""提交对口型任务.
|
||||
|
||||
三种模式:
|
||||
@@ -103,7 +66,7 @@ def create_lipsync_job(
|
||||
"""
|
||||
try:
|
||||
job = svc.create_job(
|
||||
user_id=user_id,
|
||||
user_id=current_user.user.id,
|
||||
video_url=body.video_url,
|
||||
audio_url=body.audio_url,
|
||||
audio_duration=body.audio_duration,
|
||||
@@ -116,18 +79,8 @@ def create_lipsync_job(
|
||||
project_id=body.project_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型 ValueError 退积分异常: err={refund_err}")
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except MediaKitError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型 MediaKitError 退积分异常: err={refund_err}")
|
||||
status_code = 502
|
||||
if exc.code in ("VoiceForbidden",):
|
||||
status_code = 403
|
||||
@@ -143,24 +96,11 @@ def create_lipsync_job(
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.error("创建对口型任务异常: %s", exc, exc_info=True)
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型异常退积分异常: err={refund_err}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"创建对口型任务失败: {exc}",
|
||||
) from exc
|
||||
|
||||
# 创建成功但状态为 failed(同步路径失败已抛异常到上面 except;此处处理 Celery 调度失败等)
|
||||
# 若任务已创建且状态为 failed,退费
|
||||
if _points_deducted > 0 and _points_svc is not None and getattr(job, "status", None) == "failed":
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"对口型任务失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
return job
|
||||
|
||||
|
||||
@@ -171,34 +111,8 @@ def create_lipsync_job(
|
||||
def preview_tts(
|
||||
body: AiAvatarTtsPreviewRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
user_id = current_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_digital_human"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(body.script_text or "") / 240)) if body.script_text else 1.0
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(current_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(current_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
"""步骤1「生成配音」同步 TTS 预合成.
|
||||
|
||||
同步执行 TTS 合成 → 下载音频 → ffprobe 时长 → 句子时间戳计算,
|
||||
@@ -207,18 +121,13 @@ def preview_tts(
|
||||
"""
|
||||
try:
|
||||
result = svc.preview_tts(
|
||||
user_id=user_id,
|
||||
user_id=current_user.user.id,
|
||||
voice_id=body.voice_id,
|
||||
script_text=body.script_text,
|
||||
speed=body.speed,
|
||||
emotion=body.emotion,
|
||||
)
|
||||
except MediaKitError as exc:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预合成 MediaKitError 退积分异常: err={refund_err}")
|
||||
status_code = 400
|
||||
if exc.code in ("VoiceForbidden",):
|
||||
status_code = 403
|
||||
@@ -233,11 +142,6 @@ def preview_tts(
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.error("TTS 预合成异常: %s", exc, exc_info=True)
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预合成异常退积分异常: err={refund_err}")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"TTS 合成失败: {exc}",
|
||||
|
||||
@@ -13,7 +13,6 @@ import re
|
||||
import tempfile
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import get_db_session
|
||||
from app.schemas.scripts_ai import (
|
||||
AiGenerateTitlesRequest,
|
||||
AiGenerateTitlesResponse,
|
||||
@@ -28,9 +27,7 @@ from app.services.script_asr_service import (
|
||||
transcribe_to_text,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.middleware.points_gate import points_gate
|
||||
from packages.shared.ai_client import get_doubao_client
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -65,11 +62,9 @@ def _validate_douyin_url(url: str) -> None:
|
||||
"/extract-from-douyin",
|
||||
response_model=ExtractFromDouyinResponse,
|
||||
)
|
||||
@points_gate("douyin_extract")
|
||||
def extract_from_douyin(
|
||||
request: ExtractFromDouyinRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> ExtractFromDouyinResponse:
|
||||
"""从抖音视频下载无水印视频并通过 ASR 提取文案."""
|
||||
source_url = request.url.strip()
|
||||
@@ -143,11 +138,9 @@ def extract_from_douyin(
|
||||
"/ai-rewrite",
|
||||
response_model=AiRewriteResponse,
|
||||
)
|
||||
@points_gate("ai_rewrite")
|
||||
def ai_rewrite(
|
||||
request: AiRewriteRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> AiRewriteResponse:
|
||||
"""使用豆包大模型改写文案."""
|
||||
content = (request.content or "").strip()
|
||||
@@ -213,11 +206,9 @@ def ai_rewrite(
|
||||
"/ai-generate-titles",
|
||||
response_model=AiGenerateTitlesResponse,
|
||||
)
|
||||
@points_gate("ai_title")
|
||||
def ai_generate_titles(
|
||||
request: AiGenerateTitlesRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> AiGenerateTitlesResponse:
|
||||
"""使用现有 generate_smart_titles 生成标题."""
|
||||
content = (request.content or "").strip()
|
||||
|
||||
@@ -4,14 +4,12 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.storage import get_storage_service
|
||||
from app.dependencies import (
|
||||
@@ -53,8 +51,6 @@ from packages.application.tts_job.use_cases import (
|
||||
)
|
||||
from packages.application.tts_job.workflow import TTSWorkflowService
|
||||
from packages.domain import Asset, AssetLibrary, AssetLibraryKind, AssetStatus, ClassificationStatus
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
from packages.domain.voice_presets import list_voices
|
||||
from packages.ports.asset_library_repository import AssetLibraryRepository
|
||||
from packages.ports.asset_repository import AssetRepository
|
||||
@@ -132,7 +128,6 @@ def _to_response(job, sign_url=None) -> TTSJobResponse:
|
||||
def synthesize(
|
||||
request: TTSSynthesizeRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
repository: SQLAlchemyTTSJobRepository = Depends(_get_repository),
|
||||
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
@@ -144,31 +139,6 @@ def synthesize(
|
||||
"""
|
||||
user_id = authenticated_user.user.id
|
||||
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_voice"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
# 中文按 ~240 字/分钟粗估时长,至少按 1 分钟扣 1 分
|
||||
est_minutes = max(1.0, math.ceil(len(request.text) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
# 解析 voice_id:前端可能传克隆音色 profile UUID(而非 CosyVoice voice_id),
|
||||
# 与 /tts/preview 保持一致:命中 profile → 校验归属 → 取 CosyVoice voice_id
|
||||
actual_voice_id = request.voice_id
|
||||
@@ -228,7 +198,6 @@ def synthesize(
|
||||
cosyvoice_service=cosyvoice_service,
|
||||
)
|
||||
|
||||
synthesis_error: Exception | None = None
|
||||
try:
|
||||
job = workflow.start_synthesis(job.id)
|
||||
except Exception as e:
|
||||
@@ -236,17 +205,10 @@ def synthesize(
|
||||
# 但 DB 异常、网络异常等意外错误可能逃逸。
|
||||
# 与音色克隆接口保持一致:标记 failed,返回 201,不抛 500。
|
||||
logger.error(f"TTS 合成异常: job_id={job.id}, error={e}", exc_info=True)
|
||||
synthesis_error = e
|
||||
try:
|
||||
job = workflow.process_synthesis_failure(job.id, str(e))
|
||||
except Exception as inner_e:
|
||||
logger.error(f"标记 TTS job 失败时出错: job_id={job.id}, error={inner_e}")
|
||||
# 合成失败且已扣积分 → 退费
|
||||
if synthesis_error is not None and _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 合失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
# 若任务处于 processing 状态(异步模式),触发 Celery 后台轮询
|
||||
if job.status.value == "processing":
|
||||
@@ -261,17 +223,10 @@ def synthesize(
|
||||
celery_app.send_task("worker.process_tts_synthesis", args=[job.id])
|
||||
except Exception as e:
|
||||
# Celery 调度失败,标记 job 为 failed
|
||||
# e used below for refund context
|
||||
try:
|
||||
workflow.process_synthesis_failure(job.id, f"Celery 任务调度失败: {e}")
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Celery 调度后标记失败时出错: job_id={job.id}, error={inner_e}")
|
||||
# 调度失败退费
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db, ref_id=job.id)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"Celery 调度失败退积分异常: job_id={job.id}, err={refund_err}")
|
||||
|
||||
return TTSSynthesizeResponse(
|
||||
job_id=job.id,
|
||||
@@ -598,7 +553,6 @@ def save_tts_job_to_library(
|
||||
def preview_tts(
|
||||
request: TTSPreviewRequest,
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
) -> TTSPreviewResponse:
|
||||
@@ -607,31 +561,6 @@ def preview_tts(
|
||||
用于前端预览配音效果,限制文本长度 200 字以内。
|
||||
支持预设音色和克隆音色:克隆音色传的是 profile UUID,需解析为 CosyVoice voice_id。
|
||||
"""
|
||||
user_id = authenticated_user.user.id
|
||||
# ── 积分扣点(#1895 P2) ──
|
||||
_points_deducted = 0
|
||||
_points_scene = "ai_voice"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(request.text) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
# 解析 voice_id:前端可能传 VoiceCloneProfile UUID 或预设音色 ID
|
||||
actual_voice_id = request.voice_id
|
||||
profile = voice_clone_repo.get(request.voice_id)
|
||||
@@ -657,16 +586,16 @@ def preview_tts(
|
||||
emotion=request.emotion,
|
||||
language=getattr(request, "language", "zh-CN"),
|
||||
)
|
||||
except (CosyVoiceError, ValueError) as e:
|
||||
# 合成失败退费
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"TTS 预览失败退积分异常: {refund_err}")
|
||||
if isinstance(e, CosyVoiceError):
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"TTS 合成失败: {e}") from e
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
|
||||
except CosyVoiceError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"TTS 合成失败: {e}",
|
||||
) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(e),
|
||||
) from e
|
||||
|
||||
return TTSPreviewResponse(
|
||||
audio_url=result.audio_url,
|
||||
|
||||
@@ -3,17 +3,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from typing import Optional
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.config import settings
|
||||
from app.core.celery_app import celery_app
|
||||
from app.core.storage import get_storage_service
|
||||
from app.dependencies import (
|
||||
get_asset_repository,
|
||||
get_cosyvoice_service,
|
||||
get_db_session,
|
||||
get_project_repository,
|
||||
get_voice_clone_profile_repository,
|
||||
)
|
||||
@@ -25,7 +22,6 @@ from app.schemas.voice_clone import (
|
||||
VoiceCloneStatusResponse,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.voice_clone_profile_repository import (
|
||||
SQLAlchemyVoiceCloneProfileRepository,
|
||||
@@ -42,11 +38,6 @@ from packages.application.voice_clone.use_cases import (
|
||||
from packages.application.voice_clone.workflow import (
|
||||
VoiceCloneWorkflowService,
|
||||
)
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
# remove duplicate
|
||||
_DUMMY_DELETED = ()
|
||||
from packages.ports.asset_repository import AssetRepository
|
||||
from packages.ports.project_repository import ProjectRepository
|
||||
from packages.shared.storage import SharedStorageService
|
||||
@@ -327,12 +318,8 @@ _ALLOWED_PREVIEW_EMOTIONS = {
|
||||
"悲伤",
|
||||
"愤怒",
|
||||
"惊奇",
|
||||
"吃惊",
|
||||
"害怕",
|
||||
"讨厌",
|
||||
# 灵应 P1 指定别名
|
||||
"中性",
|
||||
"伤心",
|
||||
"沉稳",
|
||||
"亲切",
|
||||
}
|
||||
@@ -348,7 +335,6 @@ def get_voice_clone_preview(
|
||||
description="情绪:neutral/happy/sad/angry/surprised/fearful/disgusted,兼容旧值 natural/excited/calm/friendly,空为默认自然",
|
||||
),
|
||||
authenticated_user: AuthenticatedUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db_session),
|
||||
repository: SQLAlchemyVoiceCloneProfileRepository = Depends(get_voice_clone_profile_repository),
|
||||
cosyvoice: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
) -> VoiceClonePreviewResponse:
|
||||
@@ -360,35 +346,10 @@ def get_voice_clone_preview(
|
||||
"""
|
||||
import time
|
||||
|
||||
user_id = authenticated_user.user.id
|
||||
_points_deducted = 0
|
||||
_points_scene = "voice_clone_synth"
|
||||
_points_svc = PointsService() if settings.points_enabled else None
|
||||
_preview_text_for_points = text.strip() or CLONE_PREVIEW_TEMPLATE
|
||||
if _points_svc is not None:
|
||||
est_minutes = max(1.0, math.ceil(len(_preview_text_for_points) / 240))
|
||||
_points_deducted = calculate_points_cost(
|
||||
_points_scene,
|
||||
is_member=getattr(authenticated_user.user, "is_member", False),
|
||||
duration_minutes=est_minutes,
|
||||
member_type=getattr(authenticated_user.user, "member_type", None),
|
||||
)
|
||||
_deduct_res = _points_svc.deduct_points(user_id, _points_deducted, _points_scene, db)
|
||||
if not _deduct_res["success"]:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"code": "INSUFFICIENT_POINTS",
|
||||
"message": f"积分不足,需要 {_points_deducted} 积分,当前余额 {_deduct_res['balance']}",
|
||||
"required": _points_deducted,
|
||||
"balance": _deduct_res["balance"],
|
||||
},
|
||||
)
|
||||
|
||||
if emotion not in _ALLOWED_PREVIEW_EMOTIONS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"不支持的 emotion 值: {emotion},可选: neutral/happy/sad/angry/surprised/fearful/disgusted 或中文 中立/中性/开心/难过/伤心/生气/愤怒/惊讶/吃惊/恐惧/害怕/厌恶/讨厌 或留空",
|
||||
detail=f"不支持的 emotion 值: {emotion},可选: neutral/happy/sad/angry/surprised/fearful/disgusted 或中文 中立/开心/难过/生气/惊讶/恐惧/厌恶,或留空",
|
||||
)
|
||||
|
||||
use_case = GetVoiceCloneUseCase(repository)
|
||||
@@ -428,14 +389,9 @@ def get_voice_clone_preview(
|
||||
speed=speed,
|
||||
emotion=emotion,
|
||||
)
|
||||
except (CosyVoiceError, ValueError) as e:
|
||||
if _points_deducted > 0 and _points_svc is not None:
|
||||
try:
|
||||
_points_svc.refund_points(user_id, _points_deducted, _points_scene, db)
|
||||
except Exception as refund_err:
|
||||
logger.warning(f"克隆音色试听失败退积分异常: clone_id={clone_id}, err={refund_err}")
|
||||
if isinstance(e, CosyVoiceError):
|
||||
raise HTTPException(status_code=502, detail=f"TTS 合成失败: {e}") from e
|
||||
except CosyVoiceError as e:
|
||||
raise HTTPException(status_code=502, detail=f"TTS 合成失败: {e}") from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e
|
||||
|
||||
# 缓存(仅默认参数组合)
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
/**
|
||||
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677 / #1800 布局修复)
|
||||
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677)
|
||||
*
|
||||
* N 个正式生成任务各自独立卡片:进度条 / 成功成片播放 / 失败原因 + 单独重试。
|
||||
* 数据来自 useGenerateVideo 的 batchTasks(useGenerationPolling 实时回传)。
|
||||
*
|
||||
* #1800 修复点:
|
||||
* - 不再用 inline style 硬编码 grid 列宽 / 卡片 maxWidth,改由 CSS 统一控制
|
||||
* (便于响应式 + 避免 inline 覆盖类规则)。
|
||||
* - 标题图标 + 文本拆分为独立 span,文本 span 加 flex:1/min-width:0/ellipsis,
|
||||
* 防止长标题在窄列里溢出导致与相邻卡片进度条视觉重叠。
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined, CheckCircleFilled, CloseCircleOutlined } from "@ant-design/icons"
|
||||
@@ -40,34 +34,36 @@ const BatchGenerationGrid: React.FC<BatchGenerationGridProps> = ({
|
||||
完成 {tasks.filter((t) => t.status === "completed").length} / {tasks.length}
|
||||
</span>
|
||||
</div>
|
||||
{/* #1800: grid 列宽 / gap / justify 全部交由 .xx-batch-gen-grid CSS 控制 */}
|
||||
<div className="xx-batch-gen-grid">
|
||||
<div
|
||||
className="xx-batch-gen-grid"
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fill, minmax(280px, 320px))",
|
||||
justifyContent: "center",
|
||||
justifyItems: "center",
|
||||
gap: 14,
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{sorted.map((task) => {
|
||||
const title = titles[task.variantIndex] || `视频 ${task.variantIndex + 1}`
|
||||
const video = (task.videos?.[0] || null) as GeneratedVideo | null
|
||||
return (
|
||||
<div key={task.taskId} className={`xx-batch-gen-card status-${task.status}`}>
|
||||
<div
|
||||
key={task.taskId}
|
||||
className={`xx-batch-gen-card status-${task.status}`}
|
||||
style={{ maxWidth: 320 }}
|
||||
>
|
||||
<div className="xx-batch-gen-card-head">
|
||||
<span className="xx-batch-gen-card-title" title={title}>
|
||||
{task.status === "completed" ? (
|
||||
<CheckCircleFilled
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#52c41a" }}
|
||||
/>
|
||||
<CheckCircleFilled style={{ color: "#52c41a", marginRight: 6 }} />
|
||||
) : task.status === "failed" ? (
|
||||
<CloseCircleOutlined
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#ef4444" }}
|
||||
/>
|
||||
<CloseCircleOutlined style={{ color: "#ef4444", marginRight: 6 }} />
|
||||
) : (
|
||||
<LoadingOutlined
|
||||
className="xx-batch-gen-card-icon"
|
||||
style={{ color: "#1677ff" }}
|
||||
/>
|
||||
<LoadingOutlined style={{ color: "#1677ff", marginRight: 6 }} />
|
||||
)}
|
||||
<span className="xx-batch-gen-card-title-text">
|
||||
视频 {task.variantIndex + 1}:{title}
|
||||
</span>
|
||||
视频 {task.variantIndex + 1}:{title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -3376,18 +3376,14 @@
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
第5步确认生成:批量渲染进度网格(Issue #1677 / #1800 布局修复)
|
||||
- 列宽从 minmax(160,180) 放宽到 minmax(300,360),避免进度条/标题挤压
|
||||
- 卡片 width:100% 撑满列宽,避免 inline maxWidth 硬编码
|
||||
- 标题图标/文本拆分 flex 布局,文本 ellipsis 长标题不溢出
|
||||
第5步确认生成:批量渲染进度网格(Issue #1677)
|
||||
============================================================ */
|
||||
.xx-batch-gen-grid {
|
||||
justify-items: center;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 360px));
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 180px));
|
||||
justify-content: center;
|
||||
justify-items: stretch;
|
||||
gap: 14px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card {
|
||||
@@ -3398,9 +3394,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card.status-completed {
|
||||
@@ -3416,30 +3410,14 @@
|
||||
.xx-batch-gen-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary, #1a1a1a);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-icon {
|
||||
flex-shrink: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-title-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -3449,7 +3427,6 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.xx-batch-gen-card-pct {
|
||||
@@ -3478,10 +3455,10 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* ── 响应式:窄屏批量网格回退单列 ── */
|
||||
/* ── 响应式:窄屏批量网格回退单列(.xx-canvas-grid 的窄屏限宽见网格定义处 #1741) ── */
|
||||
@media (max-width: 960px) {
|
||||
.xx-batch-gen-grid {
|
||||
justify-items: center;
|
||||
grid-template-columns: minmax(0, 360px);
|
||||
grid-template-columns: minmax(0, 320px);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd"
|
||||
@@ -605,25 +604,18 @@ const ScriptLibrary: React.FC = () => {
|
||||
label={
|
||||
<span>
|
||||
名称
|
||||
{/* #1893 UX: disabled 时原生 title 在 antd Button 上不触发,
|
||||
用 Tooltip + span 包裹保证提示可见 */}
|
||||
<Tooltip
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<BulbOutlined />}
|
||||
loading={titleGenLoading}
|
||||
disabled={contentEmpty}
|
||||
onClick={handleGenerateTitles}
|
||||
title={contentEmpty ? "请先填写文案内容" : "基于正文 AI 生成 3 个候选标题"}
|
||||
style={{ padding: "0 4px", marginLeft: 4, height: 22 }}
|
||||
>
|
||||
<span style={{ display: "inline-flex", marginLeft: 4 }}>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<BulbOutlined />}
|
||||
loading={titleGenLoading}
|
||||
disabled={contentEmpty}
|
||||
onClick={handleGenerateTitles}
|
||||
style={{ padding: "0 4px", height: 22 }}
|
||||
>
|
||||
✨ AI 生成标题
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
✨ AI 生成标题
|
||||
</Button>
|
||||
</span>
|
||||
}
|
||||
rules={[{ required: true, message: "请填写文案名称" }, { max: 200 }]}
|
||||
@@ -670,29 +662,16 @@ const ScriptLibrary: React.FC = () => {
|
||||
options={REWRITE_STYLE_OPTIONS}
|
||||
style={{ width: 110 }}
|
||||
size="small"
|
||||
disabled={rewriteLoading}
|
||||
/>
|
||||
{/* #1893 UX: content 为空时禁用改写按钮并给提示,避免用户点了才弹 warning */}
|
||||
<Tooltip title={contentEmpty ? "请先填写文案正文再改写" : ""}>
|
||||
<span style={{ display: "inline-flex" }}>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<RobotOutlined />}
|
||||
loading={rewriteLoading}
|
||||
disabled={contentEmpty}
|
||||
onClick={() => {
|
||||
// 每次打开重置上一次结果,避免误看旧对比
|
||||
if (!rewriteLoading) {
|
||||
setRewriteResult(null)
|
||||
setRewriteModalOpen(true)
|
||||
}
|
||||
}}
|
||||
>
|
||||
✨ AI 改写
|
||||
</Button>
|
||||
</span>
|
||||
</Tooltip>
|
||||
{rewriteResult && !contentEmpty && (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<RobotOutlined />}
|
||||
loading={rewriteLoading}
|
||||
onClick={() => setRewriteModalOpen(true)}
|
||||
>
|
||||
✨ AI 改写
|
||||
</Button>
|
||||
{rewriteResult && (
|
||||
<Button size="small" type="link" onClick={() => setRewriteModalOpen(true)}>
|
||||
查看上一次改写结果
|
||||
</Button>
|
||||
@@ -803,9 +782,7 @@ const ScriptLibrary: React.FC = () => {
|
||||
<Modal
|
||||
title={`✨ AI 改写(${rewriteStyle}风格)`}
|
||||
open={rewriteModalOpen}
|
||||
onCancel={() => !rewriteLoading && setRewriteModalOpen(false)}
|
||||
maskClosable={!rewriteLoading}
|
||||
closable={!rewriteLoading}
|
||||
onCancel={() => setRewriteModalOpen(false)}
|
||||
footer={
|
||||
rewriteResult ? (
|
||||
<Space>
|
||||
@@ -815,9 +792,7 @@ const ScriptLibrary: React.FC = () => {
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Button disabled={rewriteLoading} onClick={() => setRewriteModalOpen(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
<Button onClick={() => setRewriteModalOpen(false)}>关闭</Button>
|
||||
)
|
||||
}
|
||||
width={640}
|
||||
|
||||
@@ -58,12 +58,8 @@ EMOTION_MAP: dict[str, str] = {
|
||||
"悲伤": "sad",
|
||||
"愤怒": "angry",
|
||||
"惊奇": "surprised",
|
||||
"吃惊": "surprised",
|
||||
"害怕": "fearful",
|
||||
"讨厌": "disgusted",
|
||||
# ── 灵应派任务指定的中文别名(中性/伤心/愤怒 等)──
|
||||
"中性": "neutral",
|
||||
"伤心": "sad",
|
||||
# ── 旧英文 4 枚举兼容(natural/excited/calm/friendly 归并到最接近的标准值)──
|
||||
"natural": "neutral",
|
||||
"excited": "happy",
|
||||
@@ -72,56 +68,6 @@ EMOTION_MAP: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
# ── 支持 emotion Instruct 的 v3-flash 系统音色白名单(官方音色列表标注"Instruct:支持"且支持情感值)──
|
||||
# 这些音色的 instruction 必须使用中文固定格式 "你说话的情感是<emotion>。";
|
||||
# longanhuan_v3 虽然 Instruct 支持,但只支持方言 instruct(请用<方言>表达。),不支持 emotion,故不列入。
|
||||
_SYSTEM_VOICES_WITH_EMOTION_INSTRUCT: frozenset[str] = frozenset(
|
||||
{
|
||||
"longanyang", # 龙安洋(标杆音色)
|
||||
"longanhuan", # 龙安欢
|
||||
"longhuhu_v3", # 龙呼呼
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _is_cloned_voice(voice_id: str) -> bool:
|
||||
"""判断一个 voice_id 是否为克隆/设计音色(非系统预置音色)。
|
||||
|
||||
所有以 "long"/"loong" 开头的是系统预置音色(longxiaochun_v3/longanyang/loongabby_v3 等),
|
||||
其余视为用户克隆音色/设计音色,支持任意中英文自然语言 instruction。
|
||||
"""
|
||||
if not voice_id:
|
||||
return False
|
||||
v = voice_id.lower()
|
||||
return not (v.startswith("long") or v.startswith("loong"))
|
||||
|
||||
|
||||
def build_emotion_instruction(voice_id: str, emotion_enum: str) -> str:
|
||||
"""根据 voice 类型构造符合官方规范的 emotion instruction.
|
||||
|
||||
- 克隆/设计音色(非 long*/loong* 前缀):英文自然语言 "Speak in a {emotion} tone.",
|
||||
DashScope 对克隆音色允许任意自然语言指令。
|
||||
- 系统音色中 emotion-instruct 可用的(longanyang/longanhuan/longhuhu_v3):
|
||||
严格按官方中文固定格式 "你说话的情感是{emotion}。",结尾中文句号不可省。
|
||||
- 其他系统音色(含默认 longxiaochun_v3 等绝大多数 v3 系统音色):官方不支持 Instruct,
|
||||
返回空串(调用方据此不传 instruction,避免被 API 报错或忽略)。
|
||||
|
||||
Args:
|
||||
voice_id: CosyVoice voice 参数
|
||||
emotion_enum: 已归一化的 7 种英文枚举之一(neutral/happy/sad/...)
|
||||
|
||||
Returns:
|
||||
拼接好的 instruction 字符串;不支持时返回空串
|
||||
"""
|
||||
if not emotion_enum:
|
||||
return ""
|
||||
if _is_cloned_voice(voice_id):
|
||||
return f"Speak in a {emotion_enum} tone."
|
||||
if voice_id in _SYSTEM_VOICES_WITH_EMOTION_INSTRUCT:
|
||||
return f"你说话的情感是{emotion_enum}。"
|
||||
return ""
|
||||
|
||||
|
||||
def normalize_emotion(emotion: str) -> str:
|
||||
"""将前端情绪值归一化为 CosyVoice v3 官方英文枚举,用于拼入 instruction.
|
||||
|
||||
@@ -617,11 +563,10 @@ class CosyVoiceService:
|
||||
"rate": speed,
|
||||
"volume": volume,
|
||||
}
|
||||
# 情绪 → instruction(按 voice 类型选择格式)
|
||||
# 情绪 → instruction 严格按官方格式: 你说话的情感是{emotion_enum}。(结尾中文句号)
|
||||
norm_emotion = normalize_emotion(emotion)
|
||||
emotion_instruction = build_emotion_instruction(voice_id, norm_emotion)
|
||||
if emotion_instruction:
|
||||
input_payload["instruction"] = emotion_instruction
|
||||
if norm_emotion:
|
||||
input_payload["instruction"] = f"你说话的情感是{norm_emotion}。"
|
||||
# 语言 → language_hints 数组(仅取第一个元素生效);
|
||||
# 系统音色(非克隆/非 voice_id 中包含下划线以外的短 ID)仅传 zh/en,其他语言不传避免报错
|
||||
norm_lang = normalize_language(language)
|
||||
|
||||
@@ -74,11 +74,6 @@ class SharedSettings(BaseSettings):
|
||||
mediakit_base_url: str = "https://mediakit.cn-beijing.volces.com/api/v1"
|
||||
mediakit_timeout: int = 60
|
||||
|
||||
# ── 积分/会员系统 (#1895) ────────────────────────────────────────────
|
||||
# 总开关:默认 false(对所有用户零影响),P2 路由逐个接入时用
|
||||
# `if settings.points_enabled:` 包裹,防止未完善的扣点逻辑影响现有用户。
|
||||
points_enabled: bool = False
|
||||
|
||||
@property
|
||||
def effective_database_url(self) -> str:
|
||||
"""返回实际使用的数据库 URL。
|
||||
|
||||
@@ -1,18 +1,6 @@
|
||||
"""AI 功能入口的积分扣费装饰器 (#1895)
|
||||
|
||||
支持 sync 和 async 函数。业务失败时自动退还积分。
|
||||
|
||||
关键设计点:
|
||||
1. **POINTS_ENABLED 默认关闭**,装饰器零副作用透传,安全上线。
|
||||
2. **wrapper 绑定到被装饰模块的 globals**:Python 闭包的 __globals__ 默认指向定义闭包
|
||||
的模块(即本文件),但 Pydantic 在解函数类型注解里的 ForwardRef 时(Python 3.12
|
||||
eval_type_backport 路径)直接用 wrapper.__globals__ 查表,会找不到路由模块里
|
||||
导入/定义的 Pydantic Model,报 PydanticUndefinedAnnotation。因此用
|
||||
``types.FunctionType`` 把 wrapper code 绑定到被装饰函数所在模块的 globals。
|
||||
3. **装饰器内部入口通过「本模块 __dict__ 动态查找」**:注入到被装饰模块 globals
|
||||
的是一层薄的转发函数,每次调用都从 ``sys.modules[本模块]`` 里取最新引用,这样
|
||||
测试里 ``monkeypatch.setattr(points_gate, "_points_gate_enabled", lambda: True)``
|
||||
等替换依然能生效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,8 +9,6 @@ import asyncio
|
||||
import functools
|
||||
import inspect
|
||||
import logging
|
||||
import sys
|
||||
import types
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
@@ -30,56 +16,6 @@ from fastapi import HTTPException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PG_MODULE_NAME = __name__ # "packages.middleware.points_gate"
|
||||
|
||||
|
||||
# ── 对外暴露、可被 monkeypatch 替换的入口 ────────────────────────────────────
|
||||
|
||||
|
||||
def _points_gate_enabled() -> bool:
|
||||
"""读取 POINTS_ENABLED 配置开关(默认 False)。
|
||||
|
||||
暴露在模块顶层便于测试 monkeypatch。
|
||||
"""
|
||||
try:
|
||||
from app.config import settings as _settings
|
||||
|
||||
return bool(_settings.points_enabled)
|
||||
except Exception: # pragma: no cover
|
||||
return False
|
||||
|
||||
|
||||
# ── 转发 helper(被注入到被装饰模块 globals,动态从本模块取最新实现) ────────
|
||||
|
||||
|
||||
def _pg_enabled_proxy():
|
||||
return sys.modules[_PG_MODULE_NAME]._points_gate_enabled()
|
||||
|
||||
|
||||
def _pg_filter_kwargs_proxy(func, kwargs):
|
||||
return sys.modules[_PG_MODULE_NAME]._filter_kwargs_impl(func, kwargs)
|
||||
|
||||
|
||||
def _pg_execute_proxy(func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async):
|
||||
return sys.modules[_PG_MODULE_NAME]._execute_with_gate_impl(
|
||||
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async
|
||||
)
|
||||
|
||||
|
||||
# ── 真正实现(不直接被 wrapper 闭包引用,通过 proxy 访问) ─────────────────
|
||||
|
||||
|
||||
def _filter_kwargs_impl(func: Callable, kwargs: dict) -> dict:
|
||||
try:
|
||||
sig = inspect.signature(func)
|
||||
params = sig.parameters
|
||||
has_var_keyword = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
|
||||
if has_var_keyword:
|
||||
return kwargs
|
||||
return {k: v for k, v in kwargs.items() if k in params}
|
||||
except (ValueError, TypeError):
|
||||
return kwargs
|
||||
|
||||
|
||||
def points_gate(
|
||||
scene_key: str,
|
||||
@@ -87,68 +23,46 @@ def points_gate(
|
||||
unit_field: str | None = None,
|
||||
quantity_field: str | None = None,
|
||||
) -> Callable:
|
||||
"""AI 功能入口积分扣费装饰器。
|
||||
|
||||
Args:
|
||||
scene_key: 消耗场景标识(对应 points_rules.POINTS_SCENES 的 key)
|
||||
per_unit: 固定消耗积分(直接指定,不走规则计算)
|
||||
unit_field: 从 request body 取时长字段名(按时长计费场景)
|
||||
quantity_field: 从 request body 取数量字段名(按次计费场景)
|
||||
|
||||
使用示例::
|
||||
|
||||
@router.post("/ai/voice")
|
||||
@points_gate("ai_voice", unit_field="duration_minutes")
|
||||
async def create_ai_voice(body: VoiceRequest, current_user=Depends(get_current_user), db=Depends(get_db_session)):
|
||||
...
|
||||
"""
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
is_async = asyncio.iscoroutinefunction(func)
|
||||
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
return await _execute_with_gate(
|
||||
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=True
|
||||
)
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
return _execute_with_gate(
|
||||
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=False
|
||||
)
|
||||
|
||||
if is_async:
|
||||
|
||||
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
if not _pg_enabled(): # noqa: F821
|
||||
return await func(*args, **kwargs)
|
||||
return await _pg_execute( # noqa: F821
|
||||
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, True
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
if not _pg_enabled(): # noqa: F821
|
||||
return func(*args, **_pg_filter(func, kwargs)) # noqa: F821
|
||||
return _pg_execute( # noqa: F821
|
||||
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, False
|
||||
)
|
||||
|
||||
# 把 wrapper code 绑定到被装饰函数所在模块的 globals,
|
||||
# 并注入 proxy 入口(短名避免冲突)
|
||||
route_globals: dict = func.__globals__
|
||||
merged_globals = dict(route_globals)
|
||||
# 用相对唯一但简短的名字注入,避免和业务模块已有符号冲突
|
||||
# (setdefault 不覆盖业务模块已有同名符号,如有冲突会抛错在装饰阶段暴露)
|
||||
proxies = {
|
||||
"_pg_enabled": _pg_enabled_proxy,
|
||||
"_pg_filter": _pg_filter_kwargs_proxy,
|
||||
"_pg_execute": _pg_execute_proxy,
|
||||
}
|
||||
for k, v in proxies.items():
|
||||
if k in merged_globals and merged_globals[k] is not v:
|
||||
# 命名冲突,换更长的唯一前缀
|
||||
k2 = f"__pg_{scene_key}_{k}"
|
||||
merged_globals[k2] = v
|
||||
# 需要相应替换 wrapper 内引用 → 重新编译 wrapper 不现实,
|
||||
# 但这种场景在我们代码里不会出现(短名 _pg_enabled 等极少冲突)。
|
||||
# 为稳妥起见,直接把 wrapper code 的 co_names 映射到新名——复杂度过高,
|
||||
# 这里采用「确保短名没冲突」策略:如果冲突就抛异常让开发者改名。
|
||||
raise RuntimeError(
|
||||
f"points_gate: name collision in {func.__module__}.{func.__name__}: " f"'{k}' already defined"
|
||||
)
|
||||
merged_globals[k] = v
|
||||
|
||||
new_wrapper = types.FunctionType(
|
||||
wrapper.__code__,
|
||||
merged_globals,
|
||||
wrapper.__name__,
|
||||
wrapper.__defaults__,
|
||||
wrapper.__closure__,
|
||||
)
|
||||
# functools.wraps 会复制 __name__/__doc__/__wrapped__/__module__ 等,
|
||||
# 但注意不要把 __globals__ 覆盖回去。
|
||||
new_wrapper = functools.wraps(func)(new_wrapper)
|
||||
return new_wrapper
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def _extract_kwargs(func: Callable, args: tuple, kwargs: dict) -> dict:
|
||||
"""将位置参数映射到函数签名中的参数名,便于统一按 kwargs 提取。"""
|
||||
sig = inspect.signature(func)
|
||||
bound = sig.bind_partial(*args, **kwargs)
|
||||
merged = dict(bound.arguments)
|
||||
@@ -156,7 +70,7 @@ def _extract_kwargs(func: Callable, args: tuple, kwargs: dict) -> dict:
|
||||
return merged
|
||||
|
||||
|
||||
def _execute_with_gate_impl(
|
||||
def _execute_with_gate(
|
||||
func: Callable,
|
||||
args: tuple,
|
||||
kwargs: dict,
|
||||
@@ -166,10 +80,13 @@ def _execute_with_gate_impl(
|
||||
quantity_field: str | None,
|
||||
is_async: bool,
|
||||
) -> Any:
|
||||
"""积分扣费核心逻辑。"""
|
||||
merged = _extract_kwargs(func, args, kwargs)
|
||||
|
||||
current_user = merged.get("current_user") or merged.get("authenticated_user")
|
||||
# 提取 current_user
|
||||
current_user = merged.get("current_user")
|
||||
if current_user is None:
|
||||
# 尝试从位置参数中找
|
||||
for arg in args:
|
||||
if hasattr(arg, "user"):
|
||||
current_user = arg
|
||||
@@ -177,6 +94,7 @@ def _execute_with_gate_impl(
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
|
||||
# 提取 db session
|
||||
db = merged.get("db")
|
||||
if db is None:
|
||||
raise HTTPException(status_code=500, detail="缺少数据库 session")
|
||||
@@ -185,6 +103,7 @@ def _execute_with_gate_impl(
|
||||
is_member = getattr(user, "is_member", False)
|
||||
member_type = getattr(user, "member_type", None)
|
||||
|
||||
# ── 混剪场景:先检查免费额度 ──
|
||||
if scene_key == "ai_video":
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
@@ -195,9 +114,10 @@ def _execute_with_gate_impl(
|
||||
kwargs["_points_deducted"] = 0
|
||||
kwargs["_is_free_quota"] = True
|
||||
if is_async:
|
||||
return _run_async_impl(func, args, _filter_kwargs_impl(func, kwargs))
|
||||
return func(*args, **_filter_kwargs_impl(func, kwargs))
|
||||
return _run_async(func, args, kwargs)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# ── 计算积分消耗 ──
|
||||
if per_unit is not None:
|
||||
total_points = per_unit
|
||||
else:
|
||||
@@ -219,12 +139,14 @@ def _execute_with_gate_impl(
|
||||
member_type=member_type,
|
||||
)
|
||||
|
||||
# 零消耗场景(如免费的声音克隆训练)直接放行
|
||||
if total_points == 0:
|
||||
kwargs["_points_deducted"] = 0
|
||||
if is_async:
|
||||
return _run_async_impl(func, args, _filter_kwargs_impl(func, kwargs))
|
||||
return func(*args, **_filter_kwargs_impl(func, kwargs))
|
||||
return _run_async(func, args, kwargs)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# ── 扣减积分 ──
|
||||
from packages.domain.points_service import PointsService
|
||||
|
||||
svc = PointsService()
|
||||
@@ -245,20 +167,16 @@ def _execute_with_gate_impl(
|
||||
kwargs["_points_deducted"] = total_points
|
||||
kwargs["_points_transaction_id"] = result["transaction_id"]
|
||||
|
||||
# ── 执行业务函数,失败则退还积分 ──
|
||||
try:
|
||||
if is_async:
|
||||
return _run_async_impl(func, args, _filter_kwargs_impl(func, kwargs))
|
||||
return func(*args, **_filter_kwargs_impl(func, kwargs))
|
||||
return _run_async(func, args, kwargs)
|
||||
return func(*args, **kwargs)
|
||||
except Exception:
|
||||
svc.refund_points(user.id, total_points, scene_key, db, ref_id=str(job_id))
|
||||
raise
|
||||
|
||||
|
||||
def _run_async_impl(func: Callable, args: tuple, kwargs: dict):
|
||||
return func(*args, **_filter_kwargs_impl(func, kwargs))
|
||||
|
||||
|
||||
# 兼容历史测试文件直接 import 的别名
|
||||
_filter_kwargs = _filter_kwargs_impl
|
||||
_execute_with_gate = _execute_with_gate_impl
|
||||
_run_async = _run_async_impl
|
||||
def _run_async(func: Callable, args: tuple, kwargs: dict):
|
||||
"""在 async wrapper 中 await 原始 async 函数。"""
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@@ -46,11 +46,8 @@ def test_normalize_emotion_chinese_values():
|
||||
assert normalize_emotion("恐惧") == "fearful"
|
||||
assert normalize_emotion("厌恶") == "disgusted"
|
||||
assert normalize_emotion("中立") == "neutral"
|
||||
assert normalize_emotion("中性") == "neutral"
|
||||
assert normalize_emotion("难过") == "sad"
|
||||
assert normalize_emotion("伤心") == "sad"
|
||||
assert normalize_emotion("生气") == "angry"
|
||||
assert normalize_emotion("吃惊") == "surprised"
|
||||
|
||||
|
||||
def test_normalize_emotion_invalid_defaults_neutral():
|
||||
@@ -102,45 +99,21 @@ def _make_service_with_captured_client(captured: dict):
|
||||
return svc
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_uses_instruction_for_cloned_voice():
|
||||
"""#1898: 克隆/设计音色传 emotion 时 instruction 走英文 'Speak in a {emotion} tone.' 格式;
|
||||
不支持 Instruct 的系统音色(含默认 longxiaochun_v3)不传 instruction。"""
|
||||
def test_submit_synthesize_payload_uses_instruction_and_language_hints():
|
||||
"""#1898: emotion 通过 instruction 按官方格式传递(你说话的情感是{英文枚举}。);语言用 language_hints."""
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
# 克隆音色(非 long/loong 前缀)→ 英文 tone 格式
|
||||
svc.submit_synthesize_task(text="你好", voice_id="myclone_voice", speed=1.5, emotion="兴奋", language="zh-CN")
|
||||
svc.submit_synthesize_task(text="你好", voice_id="longxiaochun_v3", speed=1.5, emotion="兴奋", language="zh-CN")
|
||||
|
||||
inp = captured["json"]["input"]
|
||||
# 不再传 emotion 枚举字段
|
||||
assert "emotion" not in inp
|
||||
assert inp["instruction"] == "Speak in a happy tone."
|
||||
assert inp["rate"] == 1.5
|
||||
# 克隆音色不做 language_hints 限制
|
||||
assert inp["language_hints"] == ["zh"]
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_uses_chinese_instruction_for_emotion_system_voice():
|
||||
"""longanyang 等支持 emotion instruct 的系统音色 → 中文固定格式 '你说话的情感是{emotion}。'。"""
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
svc.submit_synthesize_task(text="你好", voice_id="longanyang", emotion="开心", language="zh-CN")
|
||||
|
||||
inp = captured["json"]["input"]
|
||||
# 情绪通过 instruction 中文指令
|
||||
assert inp["instruction"] == "你说话的情感是happy。"
|
||||
assert inp["language_hints"] == ["zh"]
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_default_voice_omits_instruction_even_with_emotion():
|
||||
"""默认音色 longxiaochun_v3 官方不支持 Instruct,即使传 emotion 也不应拼 instruction,
|
||||
避免被 API 忽略或报错。"""
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
svc.submit_synthesize_task(text="你好", voice_id="longxiaochun_v3", emotion="开心", language="zh-CN")
|
||||
|
||||
inp = captured["json"]["input"]
|
||||
assert "instruction" not in inp
|
||||
# rate 字段保持
|
||||
assert inp["rate"] == 1.5
|
||||
# 系统音色 zh → language_hints=["zh"]
|
||||
assert inp["language_hints"] == ["zh"]
|
||||
|
||||
|
||||
@@ -155,15 +128,14 @@ def test_submit_synthesize_payload_omits_instruction_when_emotion_empty():
|
||||
assert inp["language_hints"] == ["en"]
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_cloned_voice_english_emotion():
|
||||
"""克隆音色 + 英文 emotion 枚举 → 英文 tone 格式。"""
|
||||
def test_submit_synthesize_payload_english_emotion_maps_to_chinese():
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
svc.submit_synthesize_task(text="hi", voice_id="myclone_voice", emotion="sad")
|
||||
svc.submit_synthesize_task(text="hi", voice_id="longxiaochun_v3", emotion="sad")
|
||||
|
||||
inp = captured["json"]["input"]
|
||||
assert inp["instruction"] == "Speak in a sad tone."
|
||||
assert inp["instruction"] == "你说话的情感是sad。"
|
||||
|
||||
|
||||
# ── 对口型 TTS 直生分支 ─────────────────────────────────────────────────
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
"""AI数字人渲染 积分扣点单元测试 (#1895 P2 step 2.6)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
class TestAiAvatarRenderPoints:
|
||||
def test_ai_digital_human_per_unit(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
cost = calculate_points_cost("ai_digital_human", is_member=False, duration_minutes=1)
|
||||
assert cost >= 15
|
||||
|
||||
def test_decorator_attached(self):
|
||||
from app.api.routes.ai_avatar_render import create_render_job
|
||||
|
||||
assert hasattr(create_render_job, "__wrapped__"), "missing @points_gate"
|
||||
|
||||
def test_insufficient_raises_402(self):
|
||||
from app.api.routes.ai_avatar_render import create_render_job
|
||||
from app.schemas.ai_avatar_render import CreateAiAvatarRenderRequest
|
||||
from fastapi import HTTPException
|
||||
|
||||
db = MagicMock()
|
||||
cu = MagicMock()
|
||||
cu.user.id = "u1"
|
||||
cu.user.is_member = False
|
||||
cu.user.member_type = None
|
||||
svc = MagicMock()
|
||||
body = CreateAiAvatarRenderRequest(lipsync_job_id="lip1")
|
||||
with patch("packages.domain.points_service.PointsService") as MS:
|
||||
msvc = MagicMock()
|
||||
msvc.deduct_points.return_value = {"success": False, "balance": 0}
|
||||
MS.return_value = msvc
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_render_job(body=body, current_user=cu, svc=svc, db=db)
|
||||
assert ei.value.status_code == 402
|
||||
@@ -10,16 +10,6 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_points_gate(monkeypatch):
|
||||
"""默认关闭积分闸门,避免影响既有用例。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
yield
|
||||
|
||||
|
||||
os.environ.setdefault("JWT_SECRET_KEY", "dev-secret-key-for-testing")
|
||||
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.config.base import (
|
||||
@@ -178,56 +176,3 @@ class TestSettingsSingleton:
|
||||
shared = get_shared_settings()
|
||||
api = get_cached_settings(APISettings)
|
||||
assert shared is not api
|
||||
|
||||
|
||||
class TestPointsEnabledSwitch:
|
||||
"""#1895 P2: POINTS_ENABLED 配置开关(默认 false 保护现有用户)。"""
|
||||
|
||||
def test_default_points_enabled_is_false(self):
|
||||
from packages.config.base import SharedSettings
|
||||
|
||||
s = SharedSettings()
|
||||
assert s.points_enabled is False
|
||||
|
||||
def test_points_enabled_can_be_set_true(self, monkeypatch):
|
||||
from packages.config import base as base_mod
|
||||
|
||||
monkeypatch.setenv("POINTS_ENABLED", "true")
|
||||
base_mod.reload_settings_cache()
|
||||
try:
|
||||
s = base_mod.SharedSettings()
|
||||
assert s.points_enabled is True
|
||||
finally:
|
||||
monkeypatch.delenv("POINTS_ENABLED", raising=False)
|
||||
base_mod.reload_settings_cache()
|
||||
|
||||
def test_points_gate_disabled_passthrough(self, monkeypatch):
|
||||
"""开关关闭时,@points_gate 装饰器完全透传原函数。"""
|
||||
import packages.middleware.points_gate as pg_mod
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
monkeypatch.setattr(pg_mod, "_points_gate_enabled", lambda: False)
|
||||
|
||||
@points_gate("ai_rewrite")
|
||||
def my_func(current_user=None, db=None):
|
||||
return "bypass"
|
||||
|
||||
# 不传 current_user/db 也不报错(证明扣点逻辑被跳过)
|
||||
assert my_func() == "bypass"
|
||||
|
||||
def test_points_gate_enabled_blocks_without_user(self, monkeypatch):
|
||||
"""开关开启时,没有 current_user 会抛 401。"""
|
||||
from fastapi import HTTPException
|
||||
|
||||
import packages.middleware.points_gate as pg_mod
|
||||
from packages.middleware.points_gate import points_gate
|
||||
|
||||
monkeypatch.setattr(pg_mod, "_points_gate_enabled", lambda: True)
|
||||
|
||||
@points_gate("ai_rewrite")
|
||||
def my_func(current_user=None, db=None):
|
||||
return "ok"
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
my_func(db=MagicMock())
|
||||
assert exc.value.status_code == 401
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""CosyVoice EMOTION_MAP / normalize_emotion / build_emotion_instruction 单测(P1 修复 #1898).
|
||||
"""CosyVoice EMOTION_MAP 与 normalize_emotion 单测(P1 修复 #1898).
|
||||
|
||||
覆盖:
|
||||
- 7 种标准英文枚举 neutral/happy/sad/angry/surprised/fearful/disgusted
|
||||
(CosyVoice v3 官方 emotion 值)
|
||||
(CosyVoice v3 官方 instruction 情感值,必须原样拼入 "你说话的情感是<值>。")
|
||||
- 大小写不敏感
|
||||
- 前端中文 7 标签(中立/开心/难过/生气/惊讶/恐惧/厌恶)→ 英文枚举
|
||||
- 灵应指定别名(中性/伤心/愤怒/吃惊)→ 英文枚举
|
||||
- 常见中文别名与旧英文 4 枚举兼容
|
||||
- 常见中文别名
|
||||
- 旧英文 4 枚举兼容(natural/excited/calm/friendly)→ 归并到最接近的标准值
|
||||
- 空串/空白/None 边界
|
||||
- 未知值默认 neutral(warning 日志)
|
||||
- build_emotion_instruction 三路分支:
|
||||
· 克隆/设计音色 → "Speak in a {emotion} tone."
|
||||
· 支持 emotion Instruct 的系统音色(longanyang/longanhuan/longhuhu_v3)→ "你说话的情感是{emotion}。"
|
||||
· 默认系统音色(含 longxiaochun_v3)→ 返回空串(不传 instruction)
|
||||
- instruction 拼接格式严格符合官方要求("你说话的情感是{emotion_enum}。",单中文句号)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,11 +20,10 @@ import pytest
|
||||
|
||||
from packages.application.cosyvoice_service import (
|
||||
EMOTION_MAP,
|
||||
build_emotion_instruction,
|
||||
normalize_emotion,
|
||||
)
|
||||
|
||||
# 7 种官方英文枚举
|
||||
# 7 种官方英文枚举及其期望归一化结果
|
||||
SEVEN_STANDARD_ENUMS = [
|
||||
"neutral",
|
||||
"happy",
|
||||
@@ -49,15 +45,7 @@ FRONTEND_CN_LABELS = [
|
||||
("厌恶", "disgusted"),
|
||||
]
|
||||
|
||||
# 灵应派任务补充的中文别名
|
||||
LINGYING_CN_ALIASES = [
|
||||
("中性", "neutral"),
|
||||
("伤心", "sad"),
|
||||
("愤怒", "angry"),
|
||||
("吃惊", "surprised"),
|
||||
]
|
||||
|
||||
# 其他常见中文别名
|
||||
# 常见中文别名 → 期望英文枚举
|
||||
CN_ALIASES = [
|
||||
("自然", "neutral"),
|
||||
("愉快", "happy"),
|
||||
@@ -65,6 +53,7 @@ CN_ALIASES = [
|
||||
("快乐", "happy"),
|
||||
("兴奋", "happy"),
|
||||
("悲伤", "sad"),
|
||||
("愤怒", "angry"),
|
||||
("惊奇", "surprised"),
|
||||
("害怕", "fearful"),
|
||||
("讨厌", "disgusted"),
|
||||
@@ -78,31 +67,10 @@ OLD_FOUR_ENUMS = [
|
||||
("friendly", "happy"),
|
||||
]
|
||||
|
||||
# 支持 emotion Instruct 的系统音色(白名单)
|
||||
SYSTEM_EMOTION_VOICES = ["longanyang", "longanhuan", "longhuhu_v3"]
|
||||
|
||||
# 不支持 Instruct 的典型系统音色(含默认音色 longxiaochun_v3)
|
||||
NON_INSTRUCT_SYSTEM_VOICES = [
|
||||
"longxiaochun_v3",
|
||||
"longxiaoxia_v3",
|
||||
"longsanshu_v3",
|
||||
"longyue_v3",
|
||||
"longyingjing_v3",
|
||||
"loongabby_v3",
|
||||
"loongandy_v3",
|
||||
"longfei_v3",
|
||||
]
|
||||
|
||||
# 克隆/设计音色(非 long/loong 前缀)
|
||||
CLONED_VOICE_IDS = [
|
||||
"myclone_abc123",
|
||||
"xiaoming_20260915",
|
||||
"clone_voice_42",
|
||||
"custom_voice_test",
|
||||
]
|
||||
|
||||
|
||||
class TestEmotionMapSevenStandard:
|
||||
"""7 种标准英文枚举必须映射到自身(CosyVoice 官方值)。"""
|
||||
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_standard_enum_maps_to_self(self, enum_val: str) -> None:
|
||||
assert enum_val in EMOTION_MAP
|
||||
@@ -114,27 +82,27 @@ class TestEmotionMapSevenStandard:
|
||||
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_normalize_case_insensitive(self, enum_val: str) -> None:
|
||||
"""大小写不敏感:NEUTRAL/Happy/Angry 都能正确归一。"""
|
||||
assert normalize_emotion(enum_val.upper()) == enum_val
|
||||
assert normalize_emotion(enum_val.capitalize()) == enum_val
|
||||
assert normalize_emotion(f" {enum_val} ") == enum_val
|
||||
|
||||
def test_neutral_maps_to_neutral(self) -> None:
|
||||
"""neutral 必须映射到 neutral(默认情绪)。"""
|
||||
assert normalize_emotion("neutral") == "neutral"
|
||||
|
||||
|
||||
class TestFrontendCnLabels:
|
||||
"""前端中文 7 标签必须映射到对应英文枚举。"""
|
||||
|
||||
@pytest.mark.parametrize("cn,expected", FRONTEND_CN_LABELS)
|
||||
def test_cn_label_normalizes_to_enum(self, cn: str, expected: str) -> None:
|
||||
assert normalize_emotion(cn) == expected
|
||||
|
||||
|
||||
class TestLingyingSpecAliases:
|
||||
@pytest.mark.parametrize("cn,expected", LINGYING_CN_ALIASES)
|
||||
def test_lingying_aliases(self, cn: str, expected: str) -> None:
|
||||
assert normalize_emotion(cn) == expected
|
||||
|
||||
|
||||
class TestBackwardCompatAliases:
|
||||
"""旧英文 4 枚举和中文别名必须兼容映射到标准值。"""
|
||||
|
||||
@pytest.mark.parametrize("old_key,expected", OLD_FOUR_ENUMS)
|
||||
def test_old_four_enums(self, old_key: str, expected: str) -> None:
|
||||
assert normalize_emotion(old_key) == expected
|
||||
@@ -145,8 +113,11 @@ class TestBackwardCompatAliases:
|
||||
|
||||
|
||||
class TestNormalizeEmotionEdgeCases:
|
||||
"""空串、空白、None、未知值等边界。"""
|
||||
|
||||
@pytest.mark.parametrize("empty_val", ["", None])
|
||||
def test_empty_or_none_returns_empty(self, empty_val) -> None:
|
||||
"""空串/None 返回空串——调用方据此不传 instruction(CosyVoice 走默认自然情绪)。"""
|
||||
assert normalize_emotion(empty_val) == ""
|
||||
|
||||
@pytest.mark.parametrize("ws", [" ", "\t", "\n", " \n "])
|
||||
@@ -154,6 +125,7 @@ class TestNormalizeEmotionEdgeCases:
|
||||
assert normalize_emotion(ws) == ""
|
||||
|
||||
def test_unknown_value_defaults_to_neutral_with_warning(self, caplog) -> None:
|
||||
"""未知值:不能失败,默认返回 neutral,并打 warning 日志。"""
|
||||
caplog.set_level(logging.WARNING)
|
||||
result = normalize_emotion("not_a_real_emotion_xyz")
|
||||
assert result == "neutral"
|
||||
@@ -162,82 +134,79 @@ class TestNormalizeEmotionEdgeCases:
|
||||
def test_strips_leading_trailing_whitespace(self) -> None:
|
||||
assert normalize_emotion(" happy ") == "happy"
|
||||
assert normalize_emotion(" 生气 ") == "angry"
|
||||
assert normalize_emotion(" 中性 ") == "neutral"
|
||||
|
||||
|
||||
class TestBuildEmotionInstructionClonedVoice:
|
||||
@pytest.mark.parametrize("voice_id", CLONED_VOICE_IDS)
|
||||
class TestEmotionInstructionFormat:
|
||||
"""instruction 严格符合 CosyVoice v3 官方要求:
|
||||
格式:"你说话的情感是<emotion_enum>。"
|
||||
- 必须以"你说话的情感是"开头
|
||||
- 必须以中文句号"。"结尾
|
||||
- 情感值必须是 7 种英文枚举之一
|
||||
- 只允许一个中文句号(结尾),防止多句注入
|
||||
"""
|
||||
|
||||
PREFIX = "你说话的情感是"
|
||||
SUFFIX = "。"
|
||||
|
||||
def _build_instruction(self, emotion: str) -> str:
|
||||
return f"{self.PREFIX}{normalize_emotion(emotion)}{self.SUFFIX}"
|
||||
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_cloned_voice_uses_english_tone_format(self, voice_id: str, enum_val: str) -> None:
|
||||
inst = build_emotion_instruction(voice_id, enum_val)
|
||||
assert inst == f"Speak in a {enum_val} tone."
|
||||
assert inst.isascii(), f"克隆音色 instruction 必须是纯 ASCII 英文: {inst!r}"
|
||||
def test_instruction_starts_with_prefix(self, enum_val: str) -> None:
|
||||
assert self._build_instruction(enum_val).startswith(self.PREFIX)
|
||||
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_instruction_ends_with_single_cn_period(self, enum_val: str) -> None:
|
||||
inst = self._build_instruction(enum_val)
|
||||
assert inst.endswith(self.SUFFIX)
|
||||
assert inst.count("。") == 1, f"instruction 只能有一个中文句号,实际: {inst!r}"
|
||||
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_instruction_contains_english_enum(self, enum_val: str) -> None:
|
||||
"""instruction 中情感值必须是英文枚举,不能是中文描述词。"""
|
||||
inst = self._build_instruction(enum_val)
|
||||
# 取出情感值部分(去掉前缀和句号)
|
||||
emotion_part = inst[len(self.PREFIX) : -len(self.SUFFIX)]
|
||||
assert emotion_part == enum_val
|
||||
# 必须是纯 ASCII 英文(英文枚举值)
|
||||
assert emotion_part.isascii()
|
||||
|
||||
@pytest.mark.parametrize("cn,expected", FRONTEND_CN_LABELS)
|
||||
def test_cn_label_produces_correct_instruction(self, cn: str, expected: str) -> None:
|
||||
"""中文标签拼出的 instruction 情感值必须是英文枚举。"""
|
||||
inst = self._build_instruction(cn)
|
||||
assert inst == f"{self.PREFIX}{expected}{self.SUFFIX}"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cn,expected",
|
||||
FRONTEND_CN_LABELS + LINGYING_CN_ALIASES + CN_ALIASES,
|
||||
)
|
||||
def test_cloned_voice_chinese_input_english_output(self, cn: str, expected: str) -> None:
|
||||
norm = normalize_emotion(cn)
|
||||
inst = build_emotion_instruction("myclone_voice", norm)
|
||||
assert inst == f"Speak in a {expected} tone."
|
||||
assert inst.isascii()
|
||||
|
||||
def test_cloned_voice_empty_emotion_returns_empty(self) -> None:
|
||||
assert build_emotion_instruction("myclone", "") == ""
|
||||
|
||||
@pytest.mark.parametrize("voice_id", CLONED_VOICE_IDS)
|
||||
def test_cloned_voice_unknown_emotion_falls_back_neutral(self, voice_id: str) -> None:
|
||||
norm = normalize_emotion("unknown_xyz")
|
||||
assert norm == "neutral"
|
||||
inst = build_emotion_instruction(voice_id, norm)
|
||||
assert inst == "Speak in a neutral tone."
|
||||
|
||||
|
||||
class TestBuildEmotionInstructionSystemVoiceEmotion:
|
||||
CN_PREFIX = "你说话的情感是"
|
||||
CN_SUFFIX = "。"
|
||||
|
||||
@pytest.mark.parametrize("voice_id", SYSTEM_EMOTION_VOICES)
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_system_emotion_voice_cn_fixed_format(self, voice_id: str, enum_val: str) -> None:
|
||||
inst = build_emotion_instruction(voice_id, enum_val)
|
||||
assert inst == f"{self.CN_PREFIX}{enum_val}{self.CN_SUFFIX}"
|
||||
assert inst.count("。") == 1
|
||||
mid = inst[len(self.CN_PREFIX) : -len(self.CN_SUFFIX)]
|
||||
assert mid == enum_val
|
||||
assert mid.isascii(), f"系统音色 emotion 值必须是纯 ASCII 英文枚举: {inst!r}"
|
||||
|
||||
@pytest.mark.parametrize("voice_id", SYSTEM_EMOTION_VOICES)
|
||||
def test_system_emotion_voice_empty_returns_empty(self, voice_id: str) -> None:
|
||||
assert build_emotion_instruction(voice_id, "") == ""
|
||||
|
||||
|
||||
class TestBuildEmotionInstructionNonInstructSystemVoice:
|
||||
@pytest.mark.parametrize("voice_id", NON_INSTRUCT_SYSTEM_VOICES)
|
||||
@pytest.mark.parametrize("enum_val", SEVEN_STANDARD_ENUMS)
|
||||
def test_non_instruct_voice_returns_empty(self, voice_id: str, enum_val: str) -> None:
|
||||
assert build_emotion_instruction(voice_id, enum_val) == ""
|
||||
|
||||
def test_default_voice_longxiaochun_v3_no_instruction(self) -> None:
|
||||
assert build_emotion_instruction("longxiaochun_v3", "happy") == ""
|
||||
assert build_emotion_instruction("longxiaochun_v3", "neutral") == ""
|
||||
|
||||
|
||||
class TestBuildEmotionInstructionEdgeCases:
|
||||
def test_empty_voice_id_treated_as_system(self) -> None:
|
||||
assert build_emotion_instruction("", "happy") == ""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"voice_id,enum_val,expected",
|
||||
"example",
|
||||
[
|
||||
("MYCLONE_VOICE", "happy", "Speak in a happy tone."),
|
||||
("CloneVoice", "sad", "Speak in a sad tone."),
|
||||
"neutral",
|
||||
"happy",
|
||||
"sad",
|
||||
"angry",
|
||||
"中立",
|
||||
"开心",
|
||||
"难过",
|
||||
"生气",
|
||||
],
|
||||
)
|
||||
def test_voice_id_case_handling(self, voice_id: str, enum_val: str, expected: str) -> None:
|
||||
assert build_emotion_instruction(voice_id, enum_val) == expected
|
||||
def test_example_matches_official_doc_format(self, example: str) -> None:
|
||||
"""对照官方示例 "你说话的情感是neutral。" 格式。"""
|
||||
inst = self._build_instruction(example)
|
||||
# 官方格式示例:你说话的情感是neutral。
|
||||
assert inst.startswith(self.PREFIX)
|
||||
assert inst.endswith(self.SUFFIX)
|
||||
# 中间必须是英文枚举
|
||||
mid = inst[len(self.PREFIX) : -len(self.SUFFIX)]
|
||||
assert mid in SEVEN_STANDARD_ENUMS
|
||||
|
||||
def test_loong_prefix_is_system_voice(self) -> None:
|
||||
assert build_emotion_instruction("loongandy_v3", "happy") == ""
|
||||
assert build_emotion_instruction("loongabby_v3", "angry") == ""
|
||||
def test_empty_emotion_produces_no_instruction(self) -> None:
|
||||
"""空 emotion 不应拼 instruction(调用方据此跳过字段,CosyVoice 走默认)。"""
|
||||
assert normalize_emotion("") == ""
|
||||
assert normalize_emotion(" ") == ""
|
||||
assert normalize_emotion(None) == ""
|
||||
|
||||
def test_unknown_emotion_still_produces_valid_instruction(self) -> None:
|
||||
"""未知 emotion 默认 neutral,仍能产生合法 instruction,不会导致合成失败。"""
|
||||
inst = self._build_instruction("unknown_xyz")
|
||||
assert inst == f"{self.PREFIX}neutral{self.SUFFIX}"
|
||||
|
||||
@@ -5,15 +5,6 @@ from __future__ import annotations
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_points_gate(monkeypatch):
|
||||
"""默认关闭积分闸门,避免影响既有用例。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
yield
|
||||
|
||||
|
||||
def test_generation_cover_router_importable():
|
||||
"""新路由模块可以正确导入"""
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
"""AI封面生成 积分扣点单元测试 (#1895 P2 step 2.7)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
class TestGenerationCoverPoints:
|
||||
def test_ai_cover_cost(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
assert calculate_points_cost("ai_cover", is_member=False) == 2
|
||||
assert calculate_points_cost("ai_cover", is_member=True, member_type="yearly") >= 0
|
||||
|
||||
def test_decorator_attached(self):
|
||||
from app.api.routes.generation_cover import generate_cover
|
||||
|
||||
assert hasattr(generate_cover, "__wrapped__"), "missing @points_gate"
|
||||
@@ -573,15 +573,6 @@ from app.schemas.generation_task import (
|
||||
PreviewGenerationTaskResponse,
|
||||
)
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_points_gate(monkeypatch):
|
||||
"""默认关闭积分闸门,避免影响既有用例。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
yield
|
||||
|
||||
|
||||
def _make_user(user_id="test_user_001"):
|
||||
"""构造 mock AuthenticatedUser"""
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
"""视频预览生成 积分扣点单元测试 (#1895 P2 step 2.5)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
class TestGenerationPreviewPoints:
|
||||
def test_ai_video_cost(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
assert calculate_points_cost("ai_video", is_member=False) == 4
|
||||
assert calculate_points_cost("ai_video", is_member=True, member_type="monthly") == 2
|
||||
|
||||
def test_insufficient_raises_402(self):
|
||||
from app.api.routes.generation_preview import create_preview_generation_task
|
||||
from app.schemas.generation_task import CreatePreviewGenerationTaskRequest
|
||||
from fastapi import HTTPException
|
||||
|
||||
db = MagicMock()
|
||||
cu = MagicMock()
|
||||
cu.user.id = "u1"
|
||||
cu.user.is_member = False
|
||||
cu.user.member_type = None
|
||||
req = CreatePreviewGenerationTaskRequest(template_id="t1", asset_ids=["a1"], preview_count=1)
|
||||
with patch("packages.domain.points_service.PointsService") as MS:
|
||||
svc = MagicMock()
|
||||
svc.check_daily_free_clip.return_value = False
|
||||
svc.deduct_points.return_value = {"success": False, "balance": 0}
|
||||
MS.return_value = svc
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_preview_generation_task(
|
||||
request=req,
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
generation_task_repository=MagicMock(),
|
||||
asset_repo=MagicMock(),
|
||||
)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_decorator_attached(self):
|
||||
from app.api.routes.generation_preview import create_preview_generation_task
|
||||
|
||||
assert hasattr(create_preview_generation_task, "__wrapped__"), "missing @points_gate"
|
||||
@@ -6,7 +6,6 @@ from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
from packages.application.generation_tasks import (
|
||||
CreateGenerationTaskCommand,
|
||||
CreateGenerationTaskUseCase,
|
||||
@@ -19,13 +18,6 @@ from packages.application.generation_tasks import (
|
||||
from packages.domain import GenerationTask
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_points_gate(monkeypatch):
|
||||
"""默认关闭积分闸门,避免影响既有用例。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_repo():
|
||||
return MagicMock()
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
"""视频生成 积分扣点单元测试 (#1895 P2 step 2.4)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
class TestGenerationTasksPoints:
|
||||
def test_ai_video_base_cost(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
assert calculate_points_cost("ai_video", is_member=False) == 4
|
||||
assert calculate_points_cost("ai_video", is_member=True, member_type="monthly") == 2
|
||||
|
||||
def test_ai_video_quantity_scales(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
c1 = calculate_points_cost("ai_video", is_member=False, quantity=1)
|
||||
c3 = calculate_points_cost("ai_video", is_member=False, quantity=3)
|
||||
assert c3 > c1
|
||||
|
||||
def test_insufficient_raises_402(self):
|
||||
from app.api.routes.generation_tasks import create_generation_task
|
||||
from app.schemas.generation_task import CreateGenerationTaskRequest
|
||||
from fastapi import HTTPException
|
||||
|
||||
db = MagicMock()
|
||||
cu = MagicMock()
|
||||
cu.user.id = "u1"
|
||||
cu.user.is_member = False
|
||||
cu.user.member_type = None
|
||||
req = CreateGenerationTaskRequest(template_id="t1", asset_ids=["a1"], count=1)
|
||||
with patch("packages.domain.points_service.PointsService") as MS:
|
||||
svc = MagicMock()
|
||||
svc.check_daily_free_clip.return_value = False
|
||||
svc.deduct_points.return_value = {"success": False, "balance": 0}
|
||||
MS.return_value = svc
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_generation_task(
|
||||
request=req,
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
generation_task_repository=MagicMock(),
|
||||
project_repository=MagicMock(),
|
||||
asset_library_repository=MagicMock(),
|
||||
asset_repository=MagicMock(),
|
||||
)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_decorator_attached(self):
|
||||
from app.api.routes.generation_tasks import create_generation_task
|
||||
|
||||
assert hasattr(create_generation_task, "__wrapped__"), "missing @points_gate"
|
||||
@@ -1,242 +0,0 @@
|
||||
"""lipsync 积分扣点单元测试 (#1895 P2 step 2.2)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
def _make_cu(user_id="user-1", is_member=False, member_type=None):
|
||||
cu = MagicMock()
|
||||
cu.user.id = user_id
|
||||
cu.user.is_member = is_member
|
||||
cu.user.member_type = member_type
|
||||
return cu
|
||||
|
||||
|
||||
class TestLipsyncDurationEstimate:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("你好", 1.0),
|
||||
("你" * 240, 1.0),
|
||||
("你" * 241, 2.0),
|
||||
("你" * 1000, 5.0),
|
||||
],
|
||||
)
|
||||
def test_text_estimate(self, text, expected):
|
||||
est = max(1.0, math.ceil(len(text) / 240))
|
||||
assert est == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"seconds,expected",
|
||||
[
|
||||
(30, 1.0),
|
||||
(60, 1.0),
|
||||
(61, 2.0),
|
||||
(120, 2.0),
|
||||
(180, 3.0),
|
||||
],
|
||||
)
|
||||
def test_audio_duration_estimate(self, seconds, expected):
|
||||
est = max(1.0, math.ceil(seconds / 60.0))
|
||||
assert est == expected
|
||||
|
||||
|
||||
class TestLipsyncPointsDeduction:
|
||||
def _deduct(self, text="你好", audio_duration=None, enabled=True, success=True, balance=100, **cu_kw):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
svc = MagicMock() if enabled else None
|
||||
cu = _make_cu(**cu_kw)
|
||||
if svc is None:
|
||||
return 0, cu
|
||||
if audio_duration and audio_duration > 0:
|
||||
est = max(1.0, math.ceil(audio_duration / 60.0))
|
||||
elif text:
|
||||
est = max(1.0, math.ceil(len(text) / 240))
|
||||
else:
|
||||
est = 1.0
|
||||
cost = calculate_points_cost(
|
||||
"ai_digital_human",
|
||||
is_member=getattr(cu.user, "is_member", False),
|
||||
duration_minutes=est,
|
||||
member_type=getattr(cu.user, "member_type", None),
|
||||
)
|
||||
svc.deduct_points.return_value = {"success": success, "balance": balance}
|
||||
res = svc.deduct_points(cu.user.id, cost, "ai_digital_human", MagicMock())
|
||||
if not res["success"]:
|
||||
raise HTTPException(status_code=402, detail={"code": "INSUFFICIENT_POINTS"})
|
||||
return cost, cu
|
||||
|
||||
def test_disabled(self):
|
||||
cost, _ = self._deduct(enabled=False)
|
||||
assert cost == 0
|
||||
|
||||
def test_short_text_min_1min(self):
|
||||
cost, _ = self._deduct(text="你好")
|
||||
assert cost >= 15 # 15 base/min for free user × 1.15
|
||||
|
||||
def test_audio_duration_used(self):
|
||||
cost_long, _ = self._deduct(audio_duration=180) # 3min
|
||||
cost_short, _ = self._deduct(audio_duration=30) # 1min
|
||||
assert cost_long > cost_short
|
||||
|
||||
def test_insufficient_402(self):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
self._deduct(text="你" * 500, success=False, balance=0)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_member_cheaper(self):
|
||||
cm, _ = self._deduct(text="你" * 500, is_member=True, member_type="yearly")
|
||||
cf, _ = self._deduct(text="你" * 500, is_member=False)
|
||||
assert cm < cf
|
||||
|
||||
|
||||
# ── 直接调用 create_lipsync_job 覆盖扣点/402/退费分支 ──
|
||||
import importlib
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
# Ensure the enable-gate fixture for lipsync also covers @points_gate (if any)
|
||||
# (the existing autouse _enable is below; importlib to avoid duplicate)
|
||||
def _do_enable(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
|
||||
|
||||
def _body(**kw):
|
||||
b = MagicMock()
|
||||
defaults = dict(
|
||||
video_url="http://x/v.mp4",
|
||||
audio_url=None,
|
||||
audio_duration=None,
|
||||
sentence_timings=None,
|
||||
voice_id=None,
|
||||
script_text="你好世界",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
enable_video_loop=False,
|
||||
project_id=None,
|
||||
)
|
||||
defaults.update(kw)
|
||||
for k, v in defaults.items():
|
||||
setattr(b, k, v)
|
||||
return b
|
||||
|
||||
|
||||
def _cu(user_id="u1", is_member=False, member_type=None):
|
||||
cu = MagicMock()
|
||||
cu.user.id = user_id
|
||||
cu.user.is_member = is_member
|
||||
cu.user.member_type = member_type
|
||||
return cu
|
||||
|
||||
|
||||
class TestLipsyncEndpointPoints:
|
||||
def test_insufficient_raises_402(self, monkeypatch):
|
||||
_do_enable(monkeypatch)
|
||||
from app.api.routes.lipsync import create_lipsync_job
|
||||
|
||||
db = MagicMock()
|
||||
svc = MagicMock()
|
||||
ps = MagicMock()
|
||||
ps.deduct_points.return_value = {"success": False, "balance": 0}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
with (
|
||||
patch("app.api.routes.lipsync.PointsService", return_value=ps),
|
||||
patch("app.api.routes.lipsync.settings", fs),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_lipsync_job(body=_body(script_text="你" * 500), current_user=_cu(), db=db, svc=svc)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_value_error_refunds(self, monkeypatch):
|
||||
_do_enable(monkeypatch)
|
||||
from app.api.routes.lipsync import create_lipsync_job
|
||||
|
||||
db = MagicMock()
|
||||
svc = MagicMock()
|
||||
svc.create_job.side_effect = ValueError("bad input")
|
||||
ps = MagicMock()
|
||||
ps.deduct_points.return_value = {"success": True, "balance": 99}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
with (
|
||||
patch("app.api.routes.lipsync.PointsService", return_value=ps),
|
||||
patch("app.api.routes.lipsync.settings", fs),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_lipsync_job(body=_body(), current_user=_cu(), db=db, svc=svc)
|
||||
assert ei.value.status_code == 400
|
||||
assert ps.refund_points.called
|
||||
|
||||
def test_mediakit_error_refunds(self, monkeypatch):
|
||||
_do_enable(monkeypatch)
|
||||
from app.api.routes.lipsync import create_lipsync_job
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
db = MagicMock()
|
||||
svc = MagicMock()
|
||||
svc.create_job.side_effect = MediaKitError("fail", code="InvalidInput")
|
||||
ps = MagicMock()
|
||||
ps.deduct_points.return_value = {"success": True, "balance": 99}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
with (
|
||||
patch("app.api.routes.lipsync.PointsService", return_value=ps),
|
||||
patch("app.api.routes.lipsync.settings", fs),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_lipsync_job(body=_body(), current_user=_cu(), db=db, svc=svc)
|
||||
assert ei.value.status_code == 400
|
||||
assert ps.refund_points.called
|
||||
|
||||
def test_generic_exception_refunds(self, monkeypatch):
|
||||
_do_enable(monkeypatch)
|
||||
from app.api.routes.lipsync import create_lipsync_job
|
||||
|
||||
db = MagicMock()
|
||||
svc = MagicMock()
|
||||
svc.create_job.side_effect = RuntimeError("boom")
|
||||
ps = MagicMock()
|
||||
ps.deduct_points.return_value = {"success": True, "balance": 99}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
with (
|
||||
patch("app.api.routes.lipsync.PointsService", return_value=ps),
|
||||
patch("app.api.routes.lipsync.settings", fs),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
create_lipsync_job(body=_body(), current_user=_cu(), db=db, svc=svc)
|
||||
assert ei.value.status_code == 400
|
||||
assert ps.refund_points.called
|
||||
|
||||
def test_audio_duration_estimation(self, monkeypatch):
|
||||
_do_enable(monkeypatch)
|
||||
from app.api.routes.lipsync import create_lipsync_job
|
||||
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
db = MagicMock()
|
||||
svc = MagicMock()
|
||||
job = SimpleNamespace(id="job-1", status="queued")
|
||||
svc.create_job.return_value = job
|
||||
ps = MagicMock()
|
||||
ps.deduct_points.return_value = {"success": True, "balance": 99}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
with (
|
||||
patch("app.api.routes.lipsync.PointsService", return_value=ps),
|
||||
patch("app.api.routes.lipsync.settings", fs),
|
||||
):
|
||||
create_lipsync_job(
|
||||
body=_body(audio_url="http://x/a.mp3", audio_duration=180, script_text=None),
|
||||
current_user=_cu(),
|
||||
db=db,
|
||||
svc=svc,
|
||||
)
|
||||
# 180 seconds -> 3 minutes; assert deduct called with cost >= 15*3
|
||||
args = ps.deduct_points.call_args[0]
|
||||
assert args[1] >= calculate_points_cost("ai_digital_human", is_member=False, duration_minutes=3)
|
||||
@@ -8,17 +8,9 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
from packages.middleware.points_gate import _execute_with_gate, _extract_kwargs, points_gate
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable_points_gate(monkeypatch):
|
||||
"""测试用:强制开启 points_gate,绕过 POINTS_ENABLED 默认关闭。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
def _make_user(user_id="user-1", is_member=False, member_type=None):
|
||||
user = MagicMock()
|
||||
user.id = user_id
|
||||
|
||||
@@ -16,8 +16,6 @@ from unittest.mock import MagicMock, patch
|
||||
import pydantic
|
||||
import pytest
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
sys.path.insert(0, "apps/api")
|
||||
|
||||
|
||||
@@ -30,18 +28,6 @@ def _make_auth_user(user_id: str = "u1"):
|
||||
return auth
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_points_gate(monkeypatch):
|
||||
"""默认关闭积分闸门,避免影响既有用例。"""
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db():
|
||||
return MagicMock()
|
||||
|
||||
|
||||
def _mock_youtube_dl(
|
||||
extract_info_return=None,
|
||||
extract_info_side_effect=None,
|
||||
@@ -96,7 +82,7 @@ class TestExtractFromDouyin:
|
||||
|
||||
req = ExtractFromDouyinRequest(url="https://v.douyin.com/xxxxx/")
|
||||
auth = _make_auth_user()
|
||||
result = extract_from_douyin(request=req, current_user=auth)
|
||||
result = extract_from_douyin(request=req, authenticated_user=auth)
|
||||
|
||||
assert result.text == "这是一段测试文案内容"
|
||||
assert result.duration_seconds == 120.5
|
||||
@@ -126,7 +112,7 @@ class TestExtractFromDouyin:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
extract_from_douyin(request=req, current_user=auth)
|
||||
extract_from_douyin(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
@patch("tempfile.TemporaryDirectory")
|
||||
@@ -150,7 +136,7 @@ class TestExtractFromDouyin:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
extract_from_douyin(request=req, current_user=auth)
|
||||
extract_from_douyin(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
@patch("app.api.routes.scripts_ai.transcribe_to_text")
|
||||
@@ -183,7 +169,7 @@ class TestExtractFromDouyin:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
extract_from_douyin(request=req, current_user=auth)
|
||||
extract_from_douyin(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 503
|
||||
|
||||
@patch("app.api.routes.scripts_ai.transcribe_to_text")
|
||||
@@ -216,7 +202,7 @@ class TestExtractFromDouyin:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
extract_from_douyin(request=req, current_user=auth)
|
||||
extract_from_douyin(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
@@ -239,7 +225,7 @@ class TestAiRewrite:
|
||||
|
||||
req = AiRewriteRequest(content="原始文案内容", style="口语化")
|
||||
auth = _make_auth_user()
|
||||
result = ai_rewrite(request=req, current_user=auth)
|
||||
result = ai_rewrite(request=req, authenticated_user=auth)
|
||||
|
||||
assert result.original == "原始文案内容"
|
||||
assert result.rewritten == "改写后的文案内容,口语化风格"
|
||||
@@ -256,7 +242,7 @@ class TestAiRewrite:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
ai_rewrite(request=req, current_user=auth)
|
||||
ai_rewrite(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
@patch("app.api.routes.scripts_ai.get_doubao_client")
|
||||
@@ -275,7 +261,7 @@ class TestAiRewrite:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
ai_rewrite(request=req, current_user=auth)
|
||||
ai_rewrite(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
@patch("app.api.routes.scripts_ai.get_doubao_client")
|
||||
@@ -293,7 +279,7 @@ class TestAiRewrite:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
ai_rewrite(request=req, current_user=auth)
|
||||
ai_rewrite(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
@@ -315,7 +301,7 @@ class TestAiGenerateTitles:
|
||||
|
||||
req = AiGenerateTitlesRequest(content="这是一段关于美食的文案", count=3)
|
||||
auth = _make_auth_user()
|
||||
result = ai_generate_titles(request=req, current_user=auth)
|
||||
result = ai_generate_titles(request=req, authenticated_user=auth)
|
||||
|
||||
assert len(result.titles) == 3
|
||||
assert all(isinstance(t, str) for t in result.titles)
|
||||
@@ -353,12 +339,12 @@ class TestAiGenerateTitles:
|
||||
|
||||
# count=5
|
||||
req = AiGenerateTitlesRequest(content="测试内容", count=5)
|
||||
result = ai_generate_titles(request=req, current_user=auth)
|
||||
result = ai_generate_titles(request=req, authenticated_user=auth)
|
||||
assert len(result.titles) <= 5
|
||||
|
||||
# count=1
|
||||
req = AiGenerateTitlesRequest(content="测试内容", count=1)
|
||||
result = ai_generate_titles(request=req, current_user=auth)
|
||||
result = ai_generate_titles(request=req, authenticated_user=auth)
|
||||
assert len(result.titles) >= 1
|
||||
|
||||
def test_generate_titles_empty_content(self):
|
||||
@@ -371,7 +357,7 @@ class TestAiGenerateTitles:
|
||||
auth = _make_auth_user()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
ai_generate_titles(request=req, current_user=auth)
|
||||
ai_generate_titles(request=req, authenticated_user=auth)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
@patch("app.services.ai_service.get_doubao_client")
|
||||
@@ -386,7 +372,7 @@ class TestAiGenerateTitles:
|
||||
|
||||
req = AiGenerateTitlesRequest(content="测试文案内容")
|
||||
auth = _make_auth_user()
|
||||
result = ai_generate_titles(request=req, current_user=auth)
|
||||
result = ai_generate_titles(request=req, authenticated_user=auth)
|
||||
|
||||
assert len(result.titles) == 3
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
"""scripts_ai 积分扣点单元测试 (#1895 P2 step 2.3)"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
def _make_cu(user_id="u1", is_member=False, member_type=None):
|
||||
cu = MagicMock()
|
||||
cu.user.id = user_id
|
||||
cu.user.is_member = is_member
|
||||
cu.user.member_type = member_type
|
||||
return cu
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable_gate(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
class TestScriptsAiPointsGate:
|
||||
"""测试 scripts_ai 三个端点都挂了 @points_gate 并正确扣费。"""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"scene,endpoint_fn_name",
|
||||
[
|
||||
("douyin_extract", "extract_from_douyin"),
|
||||
("ai_rewrite", "ai_rewrite"),
|
||||
("ai_title", "ai_generate_titles"),
|
||||
],
|
||||
)
|
||||
def test_insufficient_points_raises_402(self, scene, endpoint_fn_name):
|
||||
"""积分不足时抛 402。"""
|
||||
from app.api.routes import scripts_ai
|
||||
from app.schemas.scripts_ai import (
|
||||
AiGenerateTitlesRequest,
|
||||
AiRewriteRequest,
|
||||
ExtractFromDouyinRequest,
|
||||
)
|
||||
|
||||
fn = getattr(scripts_ai, endpoint_fn_name)
|
||||
db = MagicMock()
|
||||
cu = _make_cu()
|
||||
if scene == "douyin_extract":
|
||||
req = ExtractFromDouyinRequest(url="https://v.douyin.com/abc/")
|
||||
elif scene == "ai_rewrite":
|
||||
req = AiRewriteRequest(content="测试文案")
|
||||
else:
|
||||
req = AiGenerateTitlesRequest(content="测试文案", count=3)
|
||||
|
||||
with patch("packages.domain.points_service.PointsService") as MockSvc:
|
||||
svc = MagicMock()
|
||||
svc.deduct_points.return_value = {"success": False, "balance": 0}
|
||||
MockSvc.return_value = svc
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
fn(request=req, current_user=cu, db=db)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_disabled_passthrough_no_user_error(self, monkeypatch):
|
||||
"""关闭时不需要 user/db 也能被装饰器透传(验证 gate 关闭零副作用)。"""
|
||||
from app.api.routes import scripts_ai
|
||||
from app.schemas.scripts_ai import AiRewriteRequest
|
||||
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: False)
|
||||
fn = scripts_ai.ai_rewrite
|
||||
# 不带 db/current_user 也应透传(后续业务逻辑可能报错但不是 401/500 gate 错误)
|
||||
with pytest.raises(Exception) as ei:
|
||||
fn(request=AiRewriteRequest(content="x"), current_user=None, db=None)
|
||||
# 不应是 gate 抛的 401/500
|
||||
assert isinstance(ei.value, AttributeError) or ei.value.status_code not in (401, 500)
|
||||
@@ -1,267 +0,0 @@
|
||||
"""TTS + voice_clone 积分扣点单元测试 (#1895 P2 step 2.1)
|
||||
|
||||
覆盖 synthesize / voice_clone preview 在积分开关下的扣点、余额不足、失败退费、会员折扣等分支。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
import packages.middleware.points_gate as _pg_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable_gate(monkeypatch):
|
||||
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
|
||||
yield
|
||||
|
||||
|
||||
def _make_cu(user_id="user-1", is_member=False, member_type=None):
|
||||
cu = MagicMock()
|
||||
cu.user.id = user_id
|
||||
cu.user.is_member = is_member
|
||||
cu.user.member_type = member_type
|
||||
return cu
|
||||
|
||||
|
||||
def _make_request(text="你好世界", voice_id="v1", **kw):
|
||||
r = MagicMock()
|
||||
r.text = text
|
||||
r.voice_id = voice_id
|
||||
r.voice_clone_profile_id = None
|
||||
r.speed = 1.0
|
||||
r.emotion = ""
|
||||
r.language = "zh-CN"
|
||||
r.metadata_ = {}
|
||||
r.voice_model = None
|
||||
for k, v in kw.items():
|
||||
setattr(r, k, v)
|
||||
return r
|
||||
|
||||
|
||||
def _est_minutes(chars: int) -> float:
|
||||
return max(1.0, math.ceil(chars / 240))
|
||||
|
||||
|
||||
class TestEstimateMinutes:
|
||||
@pytest.mark.parametrize(
|
||||
"chars,expected",
|
||||
[(1, 1.0), (240, 1.0), (241, 2.0), (480, 2.0), (481, 3.0), (1000, 5.0)],
|
||||
)
|
||||
def test_estimate(self, chars, expected):
|
||||
assert _est_minutes(chars) == expected
|
||||
|
||||
|
||||
class TestTtsSynthesizePointsDeduction:
|
||||
def _setup(self, text="你好", deduct_success=True, balance=0, start_synth_raises=None, send_task_raises=None):
|
||||
db = MagicMock()
|
||||
cu = _make_cu()
|
||||
repo = MagicMock()
|
||||
import enum
|
||||
|
||||
class _S(enum.Enum):
|
||||
processing = "processing"
|
||||
|
||||
job = SimpleNamespace(id="job-1", status=_S.processing, metadata={})
|
||||
uc = MagicMock()
|
||||
uc.execute.return_value = job
|
||||
wf = MagicMock()
|
||||
wf.start_synthesis.return_value = job
|
||||
wf.process_synthesis_failure.return_value = job
|
||||
if start_synth_raises:
|
||||
wf.start_synthesis.side_effect = start_synth_raises
|
||||
vc_repo = MagicMock()
|
||||
vc_repo.get.return_value = None
|
||||
svc = MagicMock()
|
||||
svc.deduct_points.return_value = {"success": deduct_success, "balance": balance}
|
||||
fake_settings = MagicMock(points_enabled=True)
|
||||
return db, cu, repo, uc, wf, vc_repo, svc, fake_settings, job
|
||||
|
||||
def test_insufficient_raises_402(self):
|
||||
db, cu, repo, uc, wf, vc_repo, svc, fs, _ = self._setup(text="你好" * 200, deduct_success=False, balance=0)
|
||||
from app.api.routes.tts import synthesize
|
||||
|
||||
with (
|
||||
patch("app.api.routes.tts.CreateTTSJobUseCase", return_value=uc),
|
||||
patch("app.api.routes.tts.TTSWorkflowService", return_value=wf),
|
||||
patch("app.api.routes.tts.PointsService", return_value=svc),
|
||||
patch("app.api.routes.tts.settings", fs),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
synthesize(
|
||||
request=_make_request(text="你好" * 200),
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice_service=MagicMock(),
|
||||
voice_clone_repo=vc_repo,
|
||||
)
|
||||
assert ei.value.status_code == 402
|
||||
assert ei.value.detail["code"] == "INSUFFICIENT_POINTS"
|
||||
|
||||
def test_success_deducts_points(self):
|
||||
db, cu, repo, uc, wf, vc_repo, svc, fs, job = self._setup()
|
||||
from app.api.routes.tts import synthesize
|
||||
|
||||
with (
|
||||
patch("app.api.routes.tts.CreateTTSJobUseCase", return_value=uc),
|
||||
patch("app.api.routes.tts.TTSWorkflowService", return_value=wf),
|
||||
patch("app.api.routes.tts.PointsService", return_value=svc),
|
||||
patch("app.api.routes.tts.celery_app.send_task") as _st,
|
||||
patch("app.api.routes.tts.settings", fs),
|
||||
):
|
||||
resp = synthesize(
|
||||
request=_make_request(text="测试"),
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice_service=MagicMock(),
|
||||
voice_clone_repo=vc_repo,
|
||||
)
|
||||
svc.deduct_points.assert_called_once()
|
||||
assert resp.job_id == job.id
|
||||
|
||||
def test_synthesis_failure_refunds(self):
|
||||
db, cu, repo, uc, wf, vc_repo, svc, fs, _ = self._setup(start_synth_raises=RuntimeError("boom"))
|
||||
from app.api.routes.tts import synthesize
|
||||
|
||||
with (
|
||||
patch("app.api.routes.tts.CreateTTSJobUseCase", return_value=uc),
|
||||
patch("app.api.routes.tts.TTSWorkflowService", return_value=wf),
|
||||
patch("app.api.routes.tts.PointsService", return_value=svc),
|
||||
patch("app.api.routes.tts.celery_app.send_task"),
|
||||
patch("app.api.routes.tts.settings", fs),
|
||||
):
|
||||
synthesize(
|
||||
request=_make_request(text="测试"),
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice_service=MagicMock(),
|
||||
voice_clone_repo=vc_repo,
|
||||
)
|
||||
assert svc.refund_points.called
|
||||
|
||||
def test_celery_send_failure_refunds(self):
|
||||
db, cu, repo, uc, wf, vc_repo, svc, fs, _ = self._setup(send_task_raises=RuntimeError("celery down"))
|
||||
from app.api.routes.tts import synthesize
|
||||
|
||||
with (
|
||||
patch("app.api.routes.tts.CreateTTSJobUseCase", return_value=uc),
|
||||
patch("app.api.routes.tts.TTSWorkflowService", return_value=wf),
|
||||
patch("app.api.routes.tts.PointsService", return_value=svc),
|
||||
patch("app.api.routes.tts.celery_app.send_task", side_effect=RuntimeError("celery down")),
|
||||
patch("app.api.routes.tts.settings", fs),
|
||||
):
|
||||
synthesize(
|
||||
request=_make_request(text="测试"),
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice_service=MagicMock(),
|
||||
voice_clone_repo=vc_repo,
|
||||
)
|
||||
assert svc.refund_points.called
|
||||
|
||||
def test_member_cheaper(self):
|
||||
from packages.domain.points_rules import calculate_points_cost
|
||||
|
||||
cf = calculate_points_cost("ai_voice", is_member=False, duration_minutes=2)
|
||||
cm = calculate_points_cost("ai_voice", is_member=True, member_type="monthly", duration_minutes=2)
|
||||
assert cm < cf
|
||||
|
||||
|
||||
class TestVoiceClonePreviewPoints:
|
||||
def _setup(self, text="你好", deduct_success=True, balance=0, synth_raises=None):
|
||||
db = MagicMock()
|
||||
cu = _make_cu()
|
||||
repo = MagicMock()
|
||||
profile = SimpleNamespace(is_ready=True, voice_id="vc-1", user_id=cu.user.id)
|
||||
uc = MagicMock()
|
||||
uc.execute.return_value = profile
|
||||
cosy = MagicMock()
|
||||
r = SimpleNamespace(audio_url="http://x/a.mp3", duration=1.2, file_size=1000)
|
||||
cosy.synthesize_speech.return_value = r
|
||||
if synth_raises:
|
||||
cosy.synthesize_speech.side_effect = synth_raises
|
||||
svc = MagicMock()
|
||||
svc.deduct_points.return_value = {"success": deduct_success, "balance": balance}
|
||||
fs = MagicMock(points_enabled=True)
|
||||
return db, cu, repo, uc, cosy, svc, fs
|
||||
|
||||
def test_insufficient_raises_402(self):
|
||||
db, cu, repo, uc, cosy, svc, fs = self._setup(deduct_success=False, balance=0)
|
||||
from app.api.routes.voice_clones import get_voice_clone_preview
|
||||
|
||||
with (
|
||||
patch("app.api.routes.voice_clones.GetVoiceCloneUseCase", return_value=uc),
|
||||
patch("app.api.routes.voice_clones.PointsService", return_value=svc),
|
||||
patch("app.api.routes.voice_clones.settings", fs),
|
||||
patch("app.api.routes.voice_clones._clone_preview_cache", {}),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
get_voice_clone_preview(
|
||||
clone_id="c1",
|
||||
text="你好",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice=cosy,
|
||||
)
|
||||
assert ei.value.status_code == 402
|
||||
|
||||
def test_synth_cosyvoice_error_refunds_and_raises_502(self):
|
||||
from packages.application.cosyvoice_service import CosyVoiceError
|
||||
|
||||
db, cu, repo, uc, cosy, svc, fs = self._setup(synth_raises=CosyVoiceError("fail"))
|
||||
from app.api.routes.voice_clones import get_voice_clone_preview
|
||||
|
||||
with (
|
||||
patch("app.api.routes.voice_clones.GetVoiceCloneUseCase", return_value=uc),
|
||||
patch("app.api.routes.voice_clones.PointsService", return_value=svc),
|
||||
patch("app.api.routes.voice_clones.settings", fs),
|
||||
patch("app.api.routes.voice_clones._clone_preview_cache", {}),
|
||||
):
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
get_voice_clone_preview(
|
||||
clone_id="c1",
|
||||
text="你好",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice=cosy,
|
||||
)
|
||||
assert ei.value.status_code == 502
|
||||
assert svc.refund_points.called
|
||||
|
||||
def test_success_returns_audio(self):
|
||||
db, cu, repo, uc, cosy, svc, fs = self._setup()
|
||||
from app.api.routes.voice_clones import get_voice_clone_preview
|
||||
|
||||
with (
|
||||
patch("app.api.routes.voice_clones.GetVoiceCloneUseCase", return_value=uc),
|
||||
patch("app.api.routes.voice_clones.PointsService", return_value=svc),
|
||||
patch("app.api.routes.voice_clones.settings", fs),
|
||||
patch("app.api.routes.voice_clones._clone_preview_cache", {}),
|
||||
):
|
||||
resp = get_voice_clone_preview(
|
||||
clone_id="c1",
|
||||
text="你好",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
authenticated_user=cu,
|
||||
db=db,
|
||||
repository=repo,
|
||||
cosyvoice=cosy,
|
||||
)
|
||||
svc.deduct_points.assert_called_once()
|
||||
assert resp.audio_url.startswith("http")
|
||||
Reference in New Issue
Block a user