Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 99c5777514 |
@@ -20,7 +20,6 @@ on:
|
||||
default: "手动触发 - CI漏触发补跑"
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: ci-pipeline-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
@@ -89,22 +88,9 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -eu
|
||||
# 优先用 git diff 判断 PR 改动范围(比 API 稳定)
|
||||
PR_NUMBER=$(echo "$GITHUB_REF" | sed 's|refs/pull/||; s|/.*||')
|
||||
if command -v git >/dev/null 2>&1 && [ -d .git ]; then
|
||||
FILES=$(git diff --name-only origin/develop...HEAD 2>/dev/null || true)
|
||||
fi
|
||||
if [ -z "${FILES:-}" ]; then
|
||||
# fallback 到 API
|
||||
API_URL="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/files?limit=300"
|
||||
FILES=$(curl -sf -H "Authorization: token ${GITHUB_TOKEN}" "$API_URL" | python3 -c "import sys,json; [print(f['filename']) for f in json.load(sys.stdin)]" 2>/dev/null || true)
|
||||
fi
|
||||
if [ -z "${FILES:-}" ]; then
|
||||
echo "⚠️ 无法获取变更文件列表,保守运行完整 CI"
|
||||
echo "skip_backend=false" >> $GITHUB_OUTPUT
|
||||
echo "skip_frontend=false" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
API_URL="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/files?limit=300"
|
||||
FILES=$(curl -s -H "Authorization: token ${GITHUB_TOKEN}" "$API_URL" | python3 -c "import sys,json; [print(f['filename']) for f in json.load(sys.stdin)]")
|
||||
FRONTEND_COUNT=$(echo "$FILES" | grep -c '^apps/web/' || true)
|
||||
BACKEND_COUNT=$(echo "$FILES" | grep -cv '^apps/web/' || true)
|
||||
TOTAL=$(echo "$FILES" | grep -cv '^$' || true)
|
||||
@@ -196,7 +182,7 @@ jobs:
|
||||
- name: Run style checks
|
||||
shell: bash
|
||||
run: bash scripts/ci/validate_style.sh
|
||||
- name: Auto-fix formatting (black + isort + ruff)
|
||||
- name: Auto-fix formatting (black + isort)
|
||||
if: failure()
|
||||
shell: sh
|
||||
env:
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
"""lipsync_jobs 增加 TTS 直生字段(voice_id/script_text/speed/emotion)
|
||||
|
||||
Revision ID: 073_add_lipsync_tts_fields
|
||||
Revises: 072_add_ai_avatar_render
|
||||
Create Date: 2026-09-09
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "073_add_lipsync_tts_fields"
|
||||
down_revision = "072_add_ai_avatar_render"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 对口型支持「传音色 + 文案直接生成」:后端内部先 TTS 合成音频再提交对口型
|
||||
op.add_column(
|
||||
"lipsync_jobs",
|
||||
sa.Column("voice_id", sa.String(200), nullable=False, server_default=""),
|
||||
)
|
||||
op.add_column(
|
||||
"lipsync_jobs",
|
||||
sa.Column("script_text", sa.Text(), nullable=False, server_default=""),
|
||||
)
|
||||
op.add_column(
|
||||
"lipsync_jobs",
|
||||
sa.Column("speed", sa.Float(), nullable=False, server_default=sa.text("1.0")),
|
||||
)
|
||||
op.add_column(
|
||||
"lipsync_jobs",
|
||||
sa.Column("emotion", sa.String(20), nullable=False, server_default=""),
|
||||
)
|
||||
# audio_url 改为可空:直生模式下音频由后端 TTS 合成后回填
|
||||
op.alter_column("lipsync_jobs", "audio_url", existing_type=sa.Text(), nullable=True)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.alter_column("lipsync_jobs", "audio_url", existing_type=sa.Text(), nullable=False)
|
||||
op.drop_column("lipsync_jobs", "emotion")
|
||||
op.drop_column("lipsync_jobs", "speed")
|
||||
op.drop_column("lipsync_jobs", "script_text")
|
||||
op.drop_column("lipsync_jobs", "voice_id")
|
||||
@@ -1,36 +0,0 @@
|
||||
"""ai_avatar_render_jobs.script_id 放宽为可空串(手动文案直生场景不关联文案库)
|
||||
|
||||
Revision ID: 074_render_script_id_optional
|
||||
Revises: 073_add_lipsync_tts_fields
|
||||
Create Date: 2026-09-09
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "074_render_script_id_optional"
|
||||
down_revision = "073_add_lipsync_tts_fields"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 列保持 NOT NULL(空串占位),仅应用层允许不传;这里显式补 server_default 防止历史约束歧义
|
||||
with op.batch_alter_table("ai_avatar_render_jobs") as batch:
|
||||
batch.alter_column(
|
||||
"script_id",
|
||||
existing_type=sa.String(length=36),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("ai_avatar_render_jobs") as batch:
|
||||
batch.alter_column(
|
||||
"script_id",
|
||||
existing_type=sa.String(length=36),
|
||||
nullable=False,
|
||||
server_default=None,
|
||||
)
|
||||
@@ -17,10 +17,7 @@ from app.dependencies import get_db_session
|
||||
from app.schemas.ai_avatar_render import (
|
||||
AiAvatarRenderJobResponse,
|
||||
CreateAiAvatarRenderRequest,
|
||||
SmartCoverRequest,
|
||||
SmartCoverResponse,
|
||||
)
|
||||
from app.services.ai_avatar_cover_service import generate_smart_cover
|
||||
from app.services.ai_avatar_render_service import (
|
||||
AiAvatarRenderError,
|
||||
AiAvatarRenderService,
|
||||
@@ -52,7 +49,7 @@ def create_render_job(
|
||||
"""
|
||||
try:
|
||||
job = svc.create_render_job(
|
||||
user_id=current_user.user.id,
|
||||
user_id=current_user.id,
|
||||
lipsync_job_id=body.lipsync_job_id,
|
||||
script_id=body.script_id,
|
||||
b_roll_segments=[s.model_dump() for s in body.b_roll_segments],
|
||||
@@ -97,7 +94,7 @@ def list_render_jobs(
|
||||
):
|
||||
"""获取 AI 数字人渲染任务列表."""
|
||||
items, total = svc.list_render_jobs(
|
||||
user_id=current_user.user.id,
|
||||
user_id=current_user.id,
|
||||
project_id=project_id,
|
||||
status=status,
|
||||
offset=offset,
|
||||
@@ -121,7 +118,7 @@ def get_render_job(
|
||||
svc: AiAvatarRenderService = Depends(_get_service),
|
||||
):
|
||||
"""获取渲染任务详情."""
|
||||
job = svc.get_render_job(job_id, current_user.user.id)
|
||||
job = svc.get_render_job(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="渲染任务不存在")
|
||||
return job
|
||||
@@ -137,7 +134,7 @@ def cancel_render_job(
|
||||
svc: AiAvatarRenderService = Depends(_get_service),
|
||||
):
|
||||
"""取消渲染任务(仅 pending 状态可取消)."""
|
||||
job = svc.cancel_render_job(job_id, current_user.user.id)
|
||||
job = svc.cancel_render_job(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="渲染任务不存在")
|
||||
if job.status != "cancelled":
|
||||
@@ -158,7 +155,7 @@ def retry_render_job(
|
||||
svc: AiAvatarRenderService = Depends(_get_service),
|
||||
):
|
||||
"""重试失败的渲染任务."""
|
||||
job = svc.retry_render_job(job_id, current_user.user.id)
|
||||
job = svc.retry_render_job(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="渲染任务不存在")
|
||||
if job.status != "pending":
|
||||
@@ -176,43 +173,3 @@ def retry_render_job(
|
||||
logger.warning("Celery 任务提交失败,重试任务已重置但未触发执行: %s", job.id)
|
||||
|
||||
return job
|
||||
|
||||
|
||||
|
||||
# ── POST /smart-cover — 智能获取封面(MediaKit 抽帧 + 评分选帧)────────
|
||||
|
||||
|
||||
@router.post("/smart-cover", response_model=SmartCoverResponse)
|
||||
def generate_avatar_smart_cover(
|
||||
body: SmartCoverRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
) -> SmartCoverResponse:
|
||||
"""智能获取数字人视频封面.
|
||||
|
||||
复用智能剪辑的 MediaKit 抽帧 + 质量评分选最佳帧逻辑(非 FFmpeg 简单截帧),
|
||||
并将选中帧转存到自家 OSS,返回非临时的封面公网 URL。
|
||||
|
||||
前端「智能获取封面」按钮可直接调用本接口;不依赖渲染任务完成。
|
||||
"""
|
||||
video_url = (body.video_url or "").strip()
|
||||
if not video_url.startswith(("http://", "https://")):
|
||||
raise HTTPException(status_code=400, detail="video_url 必须是合法的 HTTP/HTTPS URL")
|
||||
|
||||
try:
|
||||
cover_url = generate_smart_cover(video_url, max_frames=body.max_frames)
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"智能封面生成异常: user=%s video_url=%s err=%s",
|
||||
current_user.user.id, video_url[:80], exc,
|
||||
exc_info=True,
|
||||
)
|
||||
cover_url = ""
|
||||
|
||||
if not cover_url:
|
||||
return SmartCoverResponse(
|
||||
cover_url="",
|
||||
status="fallback_failed",
|
||||
message="智能抽帧失败(MediaKit 不可用或抽帧异常),请稍后重试",
|
||||
)
|
||||
logger.info("智能封面生成成功: user=%s cover_url=%s", current_user.user.id, cover_url[:120])
|
||||
return SmartCoverResponse(cover_url=cover_url, status="completed")
|
||||
|
||||
@@ -177,8 +177,8 @@ def _cleanup_expired_uploads() -> int:
|
||||
meta_file.unlink()
|
||||
cleaned += 1
|
||||
logger.info(f"Cleaned up expired upload: {upload_id}")
|
||||
except Exception:
|
||||
logger.exception("Failed to cleanup upload metadata: %s", meta_file)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to cleanup upload metadata {meta_file}: {e}")
|
||||
|
||||
return cleaned
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ def create_variant_plans(
|
||||
if _latest:
|
||||
source_plan_id = _latest.id
|
||||
except Exception:
|
||||
logger.exception("[variant-plans] 源 plan 解析失败")
|
||||
logger.warning("[variant-plans] 源 plan 解析失败", exc_info=True)
|
||||
|
||||
if not source_plan_id:
|
||||
raise HTTPException(
|
||||
@@ -122,7 +122,7 @@ def create_variant_plans(
|
||||
|
||||
voice_durations = _query_voice_durations(db, voices)
|
||||
except Exception:
|
||||
logger.exception("[variant-plans] 配音时长查询失败(按占位段长选片)")
|
||||
logger.warning("[variant-plans] 配音时长查询失败(按占位段长选片)", exc_info=True)
|
||||
voice_durations = [0.0] * request.count
|
||||
|
||||
from app.services.edit_plan_service import EditPlanService
|
||||
@@ -143,7 +143,7 @@ def create_variant_plans(
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception("[variant-plans] 选片异常")
|
||||
logger.error("[variant-plans] 选片异常: %s", e, exc_info=True)
|
||||
raise HTTPException(status_code=500, detail="选片失败,请稍后重试") from e
|
||||
|
||||
# 组装 clips 响应
|
||||
|
||||
@@ -13,16 +13,15 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from app.auth import AuthenticatedUser, get_current_user
|
||||
from app.dependencies import (
|
||||
get_db_session,
|
||||
get_voice_clone_profile_repository,
|
||||
)
|
||||
from app.dependencies import get_cosyvoice_service, get_db_session, get_voice_clone_profile_repository
|
||||
from app.schemas.lipsync import CreateLipsyncJobRequest, LipsyncJobResponse
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.application.cosyvoice_service import CosyVoiceError, CosyVoiceService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -30,14 +29,35 @@ router = APIRouter()
|
||||
|
||||
def _get_service(
|
||||
db: Session = Depends(get_db_session),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
|
||||
) -> LipsyncService:
|
||||
# voice_clone_repo 用于克隆音色 profile 解析
|
||||
# TTS 合成已移至 Celery 异步任务,无需同步注入 cosyvoice_service
|
||||
return LipsyncService(
|
||||
db,
|
||||
voice_clone_repo=voice_clone_repo,
|
||||
)
|
||||
return LipsyncService(db, cosyvoice_service=cosyvoice_service)
|
||||
|
||||
|
||||
def _resolve_voice_id(
|
||||
raw_voice_id: str,
|
||||
user_id: str,
|
||||
voice_clone_repo,
|
||||
) -> str:
|
||||
"""解析 voice_id:支持预设音色 ID 或克隆音色 profile UUID.
|
||||
|
||||
与 TTS 路由保持一致:命中 profile → 校验归属 → 取 CosyVoice voice_id。
|
||||
"""
|
||||
try:
|
||||
profile = voice_clone_repo.get(raw_voice_id)
|
||||
except Exception as exc:
|
||||
logger.error("查询克隆音色失败: voice_id=%s, error=%s", raw_voice_id, exc)
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"voice_id 无效: {raw_voice_id}",
|
||||
) from exc
|
||||
if profile is not None:
|
||||
if profile.user_id != user_id:
|
||||
raise HTTPException(status_code=403, detail="无权访问该音色")
|
||||
if not profile.voice_id:
|
||||
raise HTTPException(status_code=400, detail="音色克隆尚未完成,请稍后再试")
|
||||
return profile.voice_id
|
||||
return raw_voice_id
|
||||
|
||||
|
||||
# ── POST /jobs — 提交对口型任务 ───────────────────────────────────────────
|
||||
@@ -48,41 +68,41 @@ def create_lipsync_job(
|
||||
body: CreateLipsyncJobRequest,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
voice_clone_repo=Depends(get_voice_clone_profile_repository),
|
||||
):
|
||||
"""提交对口型任务.
|
||||
|
||||
#1809/#1822: 前端传 {video_url, voice_id, script_text, speed?, emotion?},
|
||||
后端创建任务记录(状态 tts_processing),dispatch Celery 异步任务执行 TTS 合成 + MediaKit 提交;
|
||||
也支持直接传 {video_url, audio_url}(同步提交 MediaKit)。
|
||||
#1809: 前端传 {voice_id, script_text, video_url},
|
||||
后端内部调 TTS 合成音频,再提交 MediaKit。
|
||||
"""
|
||||
# 解析 voice_id(支持克隆音色 profile UUID)
|
||||
actual_voice_id = _resolve_voice_id(body.voice_id, current_user.id, voice_clone_repo)
|
||||
|
||||
try:
|
||||
job = svc.create_job(
|
||||
user_id=current_user.user.id,
|
||||
user_id=current_user.id,
|
||||
video_url=body.video_url,
|
||||
audio_url=body.audio_url,
|
||||
voice_id=body.voice_id,
|
||||
voice_id=actual_voice_id,
|
||||
script_text=body.script_text,
|
||||
speed=body.speed,
|
||||
emotion=body.emotion,
|
||||
enable_video_loop=body.enable_video_loop,
|
||||
project_id=body.project_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
# 参数无效(如 voice_id 格式不对、文本过长等)
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except MediaKitError as exc:
|
||||
# 音色无权访问 → 403;参数无效 → 400;MediaKit 提交失败 → 502
|
||||
status_code = 502
|
||||
if exc.code in ("VoiceForbidden",):
|
||||
status_code = 403
|
||||
elif exc.code in ("InvalidInput", "TTSInvalidParam", "VoiceNotReady"):
|
||||
status_code = 400
|
||||
except CosyVoiceError as exc:
|
||||
# TTS 合成基础设施失败(API/网络/认证)
|
||||
raise HTTPException(
|
||||
status_code=status_code,
|
||||
status_code=502,
|
||||
detail={"code": "TTSSynthesisFailed", "message": str(exc)},
|
||||
) from exc
|
||||
except MediaKitError as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail={
|
||||
"code": exc.code,
|
||||
"message": str(exc),
|
||||
"request_id": getattr(exc, "request_id", ""),
|
||||
"request_id": exc.request_id,
|
||||
},
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
@@ -110,7 +130,7 @@ def list_lipsync_jobs(
|
||||
):
|
||||
"""获取对口型任务列表."""
|
||||
items, total = svc.list_jobs(
|
||||
user_id=current_user.user.id,
|
||||
user_id=current_user.id,
|
||||
project_id=project_id,
|
||||
status=status,
|
||||
offset=offset,
|
||||
@@ -130,22 +150,13 @@ def list_lipsync_jobs(
|
||||
@router.get("/jobs/{job_id}", response_model=LipsyncJobResponse)
|
||||
def get_lipsync_job(
|
||||
job_id: str,
|
||||
background: BackgroundTasks,
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
"""获取对口型任务详情.
|
||||
|
||||
非终态任务:先返回 DB 缓存,挂后台刷新(下次轮询拿到新状态),
|
||||
避免 MediaKit 慢响应阻塞前端轮询。
|
||||
"""
|
||||
job = svc.get_job(job_id, current_user.user.id)
|
||||
"""获取对口型任务详情."""
|
||||
job = svc.get_job(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="任务不存在")
|
||||
|
||||
if job.status not in ("completed", "failed"):
|
||||
background.add_task(svc.refresh_job_status, job_id, current_user.user.id)
|
||||
|
||||
return job
|
||||
|
||||
|
||||
@@ -159,7 +170,7 @@ def refresh_lipsync_job(
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
"""从 MediaKit 拉取最新状态并更新."""
|
||||
job = svc.refresh_job_status(job_id, current_user.user.id)
|
||||
job = svc.refresh_job_status(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="任务不存在")
|
||||
return job
|
||||
@@ -174,13 +185,13 @@ def cancel_lipsync_job(
|
||||
current_user: AuthenticatedUser = Depends(get_current_user),
|
||||
svc: LipsyncService = Depends(_get_service),
|
||||
):
|
||||
"""取消对口型任务(仅 pending/tts_processing/submitted 状态可取消)."""
|
||||
job = svc.cancel_job(job_id, current_user.user.id)
|
||||
"""取消对口型任务(仅 pending/submitted 状态可取消)."""
|
||||
job = svc.cancel_job(job_id, current_user.id)
|
||||
if job is None:
|
||||
raise HTTPException(status_code=404, detail="任务不存在")
|
||||
if job.status != "cancelled":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"任务状态 {job.status} 不可取消,仅 pending/tts_processing/submitted 可取消",
|
||||
detail=f"任务状态 {job.status} 不可取消,仅 pending/submitted 可取消",
|
||||
)
|
||||
return job
|
||||
|
||||
@@ -65,8 +65,8 @@ def _build_asset_analyses(
|
||||
if url:
|
||||
video_urls.append(url)
|
||||
valid_asset_ids.append(aid)
|
||||
except Exception:
|
||||
logger.exception("获取素材URL失败: asset_id=%s", aid)
|
||||
except Exception as e:
|
||||
logger.warning("获取素材URL失败: asset_id=%s error=%s", aid, str(e))
|
||||
|
||||
if not video_urls:
|
||||
logger.info("无可用视频素材,跳过视频理解分析")
|
||||
@@ -108,7 +108,7 @@ def _build_asset_analyses(
|
||||
return analyses
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("MediaKit 视频理解异常,将降级到无分析模式: %s", e)
|
||||
logger.warning("MediaKit 视频理解异常,将降级到无分析模式: %s", str(e))
|
||||
return {}
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ def editor_ai_recommend(
|
||||
try:
|
||||
db.rollback()
|
||||
except Exception:
|
||||
logger.exception("db rollback failed in ai_recommend")
|
||||
pass
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="AI推荐结果保存失败,请稍后重试",
|
||||
|
||||
@@ -132,8 +132,8 @@ def _build_asset_url_map(
|
||||
result: dict[str, str | None] = {}
|
||||
try:
|
||||
storage = get_storage_service()
|
||||
except Exception as e:
|
||||
logger.exception("获取存储服务失败,跳过asset_url生成: %s", e)
|
||||
except Exception:
|
||||
logger.warning("获取存储服务失败,跳过asset_url生成")
|
||||
return {aid: None for aid in asset_ids}
|
||||
|
||||
# 批量查询所有 Asset(单次 SQL IN 查询,避免 N+1)
|
||||
@@ -141,7 +141,7 @@ def _build_asset_url_map(
|
||||
assets = asset_repo.find_by_ids(unique_ids)
|
||||
asset_map = {a.id: a for a in assets}
|
||||
except Exception:
|
||||
logger.exception("批量查询素材失败: asset_ids=%s", asset_ids)
|
||||
logger.warning("批量查询素材失败: asset_ids=%s", asset_ids, exc_info=True)
|
||||
return {aid: None for aid in asset_ids if aid}
|
||||
|
||||
for aid in unique_ids:
|
||||
@@ -156,7 +156,7 @@ def _build_asset_url_map(
|
||||
continue
|
||||
result[aid] = storage.get_download_url(storage_key, expires_seconds=3600)
|
||||
except Exception:
|
||||
logger.exception("生成素材签名URL失败: asset_id=%s", aid)
|
||||
logger.warning("生成素材签名URL失败: asset_id=%s", aid, exc_info=True)
|
||||
result[aid] = None
|
||||
|
||||
return result
|
||||
@@ -486,8 +486,8 @@ def _get_mediakit_recommendations(
|
||||
if url:
|
||||
video_urls.append(url)
|
||||
valid_asset_ids.append(asset_id)
|
||||
except Exception:
|
||||
logger.exception("获取素材URL失败: asset_id=%s", asset_id)
|
||||
except Exception as e:
|
||||
logger.warning("获取素材URL失败: asset_id=%s error=%s", asset_id, e)
|
||||
|
||||
if not video_urls:
|
||||
return {}
|
||||
@@ -563,7 +563,7 @@ def _get_mediakit_recommendations(
|
||||
return recommendations
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("MediaKit 智能选片异常,降级为随机选择: %s", e)
|
||||
logger.warning("MediaKit 智能选片异常,降级为随机选择: %s", e)
|
||||
return {}
|
||||
|
||||
|
||||
@@ -860,7 +860,7 @@ def create_clips_from_assets_editor(
|
||||
duplicate_warning = None
|
||||
if dup_rate > 50:
|
||||
duplicate_warning = f"查重率 {dup_rate:.1f}% 超过50%,建议更换素材或模板"
|
||||
logger.exception(
|
||||
logger.warning(
|
||||
"from-assets 成片查重率超标: plan_id=%s dup_rate=%.1f%%",
|
||||
plan_id,
|
||||
dup_rate,
|
||||
@@ -960,8 +960,8 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
# 尝试获取存储服务(用于生成视频 URL)
|
||||
try:
|
||||
storage = get_storage_service()
|
||||
except Exception as e:
|
||||
logger.exception("后台任务: 获取存储服务失败,跳过 SceneChange 更新: %s", e)
|
||||
except Exception:
|
||||
logger.warning("后台任务: 获取存储服务失败,跳过 SceneChange 更新")
|
||||
return
|
||||
|
||||
# 获取 MediaKit 客户端
|
||||
@@ -987,8 +987,8 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
if storage_key and mime.startswith("video/"):
|
||||
try:
|
||||
video_url = storage.get_download_url(storage_key)
|
||||
except Exception:
|
||||
logger.exception("后台任务: 获取素材URL失败: asset_id=%s", asset_id)
|
||||
except Exception as e:
|
||||
logger.warning("后台任务: 获取素材URL失败: asset_id=%s error=%s", asset_id, e)
|
||||
|
||||
# 构建该素材的占用区间列表(排除已更新片段)
|
||||
def _get_other_segments(asset_id_inner, clip_id_inner):
|
||||
@@ -1039,11 +1039,12 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
asset_id,
|
||||
len(scene_changes),
|
||||
)
|
||||
except Exception:
|
||||
except Exception as cache_err:
|
||||
# 缓存写入失败不影响本次片段更新
|
||||
logger.exception(
|
||||
"后台任务: 场景点缓存写入失败: asset_id=%s",
|
||||
logger.warning(
|
||||
"后台任务: 场景点缓存写入失败: asset_id=%s error=%s",
|
||||
asset_id,
|
||||
cache_err,
|
||||
)
|
||||
|
||||
# SceneChange 未获得有效结果 → 尝试 analyze_videos 作为 fallback
|
||||
@@ -1123,10 +1124,11 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
recommended_start + clip_duration,
|
||||
plan_id,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"后台任务: 同步素材区间记录失败,回滚本次片段更新: clip_id=%s",
|
||||
except Exception as me:
|
||||
logger.warning(
|
||||
"后台任务: 同步素材区间记录失败,回滚本次片段更新: clip_id=%s error=%s",
|
||||
clip.id,
|
||||
me,
|
||||
)
|
||||
db.rollback()
|
||||
continue
|
||||
@@ -1142,8 +1144,8 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
asset_id,
|
||||
recommended_start,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("后台任务: 单个片段更新失败: clip_id=%s", clip.id)
|
||||
except Exception as ue:
|
||||
logger.warning("后台任务: 单个片段更新失败: clip_id=%s error=%s", clip.id, ue)
|
||||
try:
|
||||
db.rollback()
|
||||
except Exception:
|
||||
@@ -1152,9 +1154,9 @@ def _update_mediakit_recommendations_async( # pragma: no cover
|
||||
|
||||
logger.info("后台任务完成: plan_id=%s 成功更新 %d 个片段", plan_id, updated_count)
|
||||
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 后台任务失败不影响已创建的片段,静默处理
|
||||
logger.exception("后台任务异常: plan_id=%s", plan_id)
|
||||
logger.warning("后台任务异常: plan_id=%s error=%s", plan_id, e, exc_info=True)
|
||||
if db:
|
||||
try:
|
||||
db.rollback()
|
||||
|
||||
@@ -173,14 +173,6 @@ def synthesize(
|
||||
# job.voice_id 统一存解析后的 CosyVoice voice_id
|
||||
actual_voice_id = resolved_profile.voice_id
|
||||
|
||||
# 语速/情绪等合成参数随 metadata 落库,workflow 提交 CosyVoice 时读取透传
|
||||
synthesis_meta = {
|
||||
"speed": request.speed,
|
||||
"emotion": request.emotion or "",
|
||||
}
|
||||
if request.metadata_:
|
||||
synthesis_meta.update(request.metadata_)
|
||||
|
||||
use_case = CreateTTSJobUseCase(repository)
|
||||
job = use_case.execute(
|
||||
user_id=user_id,
|
||||
@@ -188,7 +180,7 @@ def synthesize(
|
||||
voice_id=actual_voice_id,
|
||||
voice_model=request.voice_model,
|
||||
voice_clone_profile_id=voice_clone_profile_id,
|
||||
metadata=synthesis_meta,
|
||||
metadata=request.metadata_,
|
||||
)
|
||||
|
||||
# 提交 CosyVoice 合成任务
|
||||
@@ -575,7 +567,6 @@ def preview_tts(
|
||||
text=request.text,
|
||||
voice_id=actual_voice_id,
|
||||
speed=request.speed,
|
||||
emotion=request.emotion,
|
||||
)
|
||||
except CosyVoiceError as e:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -163,12 +163,12 @@ def create_voice_clone(
|
||||
celery_app.send_task("worker.process_voice_clone", args=[profile.id])
|
||||
logger.info(f"Celery task dispatched for voice clone {profile.id}")
|
||||
except Exception as e:
|
||||
logger.exception("Failed to dispatch Celery task")
|
||||
logger.error(f"Failed to dispatch Celery task: {e}")
|
||||
# P2-3: Celery 调度失败时标记 profile 为 failed,避免永久卡在 processing
|
||||
try:
|
||||
workflow.process_clone_failure(profile.id, f"Celery 任务调度失败: {e}")
|
||||
except Exception:
|
||||
logger.exception("Failed to mark profile as failed after dispatch error")
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Failed to mark profile as failed after dispatch error: {inner_e}")
|
||||
|
||||
return _to_response(profile)
|
||||
|
||||
@@ -277,12 +277,12 @@ def retry_voice_clone(
|
||||
celery_app.send_task("worker.process_voice_clone", args=[profile.id])
|
||||
logger.info(f"Celery task dispatched for voice clone retry {profile.id}")
|
||||
except Exception as e:
|
||||
logger.exception("Failed to dispatch Celery task")
|
||||
logger.error(f"Failed to dispatch Celery task: {e}")
|
||||
# P2-3: Celery 调度失败时标记 profile 为 failed,避免永久卡在 processing
|
||||
try:
|
||||
workflow.process_clone_failure(profile.id, f"Celery 任务调度失败: {e}")
|
||||
except Exception:
|
||||
logger.exception("Failed to mark profile as failed after dispatch error")
|
||||
except Exception as inner_e:
|
||||
logger.error(f"Failed to mark profile as failed after dispatch error: {inner_e}")
|
||||
|
||||
return _to_response(profile)
|
||||
|
||||
|
||||
@@ -105,8 +105,8 @@ def _resolve_preset_preview_url(
|
||||
_preset_preview_cache[voice_id] = (audio_url, time.time())
|
||||
logger.info("Preset voice preview generated: %s", voice_id)
|
||||
return audio_url
|
||||
except Exception:
|
||||
logger.exception("Failed to generate preset voice preview: voice_id=%s", voice_id)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to generate preview for %s, using fallback: %s", voice_id, e)
|
||||
return fallback_url
|
||||
|
||||
|
||||
@@ -127,7 +127,6 @@ def _resolve_all_preset_preview_urls(
|
||||
try:
|
||||
result_map[p.voice_id] = _resolve_preset_preview_url(p.voice_id, p.preview_url, cosyvoice)
|
||||
except Exception:
|
||||
logger.exception("Failed to resolve preset preview URL: voice_id=%s", p.voice_id)
|
||||
result_map[p.voice_id] = p.preview_url
|
||||
return result_map
|
||||
|
||||
@@ -733,7 +732,7 @@ def _find_or_create_voice_library_for_extract(*, user_id, project_repository, as
|
||||
try:
|
||||
session.rollback()
|
||||
except Exception:
|
||||
logger.exception("session rollback failed in _find_or_create_voice_library")
|
||||
pass
|
||||
for lib in asset_library_repository.find_by_project(project.id):
|
||||
kind = lib.kind.value if hasattr(lib.kind, "value") else lib.kind
|
||||
if kind == AssetLibraryKind.VOICE.value:
|
||||
|
||||
@@ -50,7 +50,7 @@ class CreateAiAvatarRenderRequest(BaseModel):
|
||||
"""创建渲染任务请求."""
|
||||
|
||||
lipsync_job_id: str = Field(..., description="对口型任务 ID")
|
||||
script_id: str = Field("", description="文案 ID(选自文案库时传;手动输入文案直生场景可留空)")
|
||||
script_id: str = Field(..., description="文案 ID")
|
||||
b_roll_segments: list[BRollSegment] = Field(default_factory=list, description="B-roll 片段列表")
|
||||
title_config: dict[str, Any] = Field(default_factory=dict, description="标题配置")
|
||||
cover_config: dict[str, Any] = Field(default_factory=dict, description="封面配置")
|
||||
@@ -67,8 +67,10 @@ class CreateAiAvatarRenderRequest(BaseModel):
|
||||
@field_validator("script_id")
|
||||
@classmethod
|
||||
def validate_script_id(cls, v: str) -> str:
|
||||
# script_id 可选:手动输入文案(TTS 直生)场景不关联文案库条目
|
||||
return (v or "").strip()
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("script_id 不能为空")
|
||||
return v
|
||||
|
||||
|
||||
class AiAvatarRenderJobResponse(BaseModel):
|
||||
@@ -78,7 +80,7 @@ class AiAvatarRenderJobResponse(BaseModel):
|
||||
user_id: str
|
||||
project_id: str
|
||||
lipsync_job_id: str
|
||||
script_id: str = ""
|
||||
script_id: str
|
||||
b_roll_segments: list[dict[str, Any]]
|
||||
title_config: dict[str, Any]
|
||||
cover_config: dict[str, Any]
|
||||
@@ -107,18 +109,3 @@ class AiAvatarRenderProgressResponse(BaseModel):
|
||||
output_cover_url: str
|
||||
output_duration: float
|
||||
error_message: str
|
||||
|
||||
|
||||
class SmartCoverRequest(BaseModel):
|
||||
"""智能封面请求 — MediaKit 抽帧 + 质量评分选最佳帧."""
|
||||
|
||||
video_url: str = Field(..., description="数字人视频 URL(对口型/渲染成片)")
|
||||
max_frames: int = Field(5, ge=1, le=10, description="抽帧数量(默认 5)")
|
||||
|
||||
|
||||
class SmartCoverResponse(BaseModel):
|
||||
"""智能封面响应."""
|
||||
|
||||
cover_url: str = Field("", description="封面图公网 URL(OSS,非临时);失败为空")
|
||||
status: str = Field("completed", description="completed / fallback_failed")
|
||||
message: str = Field("", description="失败原因(如有)")
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
"""对口型 API Schema 定义 — #1796 / #1809 / #1822.
|
||||
|
||||
支持两种输入模式(二选一):
|
||||
1. TTS 直生模式(推荐):传 voice_id + script_text(+ speed/emotion),
|
||||
后端内部先调 CosyVoice 合成音频,再提交 MediaKit 对口型。
|
||||
2. 直接音频模式:传 video_url + audio_url(音频已由调用方准备好)。
|
||||
"""
|
||||
"""对口型 API Schema 定义 — #1796, #1809 参数调整."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class LipsyncJobResponse(BaseModel):
|
||||
@@ -23,10 +17,6 @@ class LipsyncJobResponse(BaseModel):
|
||||
video_url: str
|
||||
audio_url: str
|
||||
enable_video_loop: bool
|
||||
voice_id: str = ""
|
||||
script_text: str = ""
|
||||
speed: float = 1.0
|
||||
emotion: str = ""
|
||||
mediakit_task_id: str
|
||||
status: str
|
||||
output_video_url: str
|
||||
@@ -43,58 +33,45 @@ class LipsyncJobResponse(BaseModel):
|
||||
|
||||
|
||||
class CreateLipsyncJobRequest(BaseModel):
|
||||
"""创建对口型任务请求.
|
||||
"""创建对口型任务请求 — #1809.
|
||||
|
||||
两种模式(二选一):
|
||||
- TTS 直生:voice_id + script_text 必填(+ 可选 speed/emotion);audio_url 留空。
|
||||
- 直接音频:video_url + audio_url 必填。
|
||||
前端传 {voice_id, script_text, video_url},
|
||||
后端内部调 TTS 生成 audio_url 再提交 MediaKit。
|
||||
"""
|
||||
|
||||
video_url: str = Field(..., description="人物视频 URL(MP4,≤30min,单人真人)")
|
||||
|
||||
# 模式 2:直接音频
|
||||
audio_url: str = Field("", description="驱动音频 URL(mp3/aac/wav/m4a/flac);直生模式留空")
|
||||
|
||||
# 模式 1:TTS 直生
|
||||
voice_id: str = Field("", description="音色 ID(预置音色或克隆音色 profile UUID)")
|
||||
script_text: str = Field("", description="要合成的文案(直生模式必填,最长 5000 字符)")
|
||||
speed: float = Field(1.0, ge=0.5, le=2.0, description="语速(0.5-2.0),默认 1.0")
|
||||
emotion: str = Field("", description="情绪(natural/excited/calm/friendly 或中文 自然/兴奋/沉稳/亲切)")
|
||||
|
||||
voice_id: str = Field(..., description="音色 ID(预设音色或克隆音色 profile ID)")
|
||||
script_text: str = Field(..., description="要合成的脚本文本")
|
||||
enable_video_loop: bool = Field(False, description="音频长于视频时是否循环画面")
|
||||
project_id: str = Field("", description="项目 ID(可选)")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_input_mode(self) -> "CreateLipsyncJobRequest":
|
||||
video = (self.video_url or "").strip()
|
||||
if not video:
|
||||
@field_validator("video_url")
|
||||
@classmethod
|
||||
def validate_video_url(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("video_url 不能为空")
|
||||
if not video.startswith(("http://", "https://")):
|
||||
if not v.startswith(("http://", "https://")):
|
||||
raise ValueError("video_url 必须是 HTTP/HTTPS URL")
|
||||
lower = video.lower().split("?")[0]
|
||||
lower = v.lower().split("?")[0]
|
||||
if not lower.endswith(".mp4"):
|
||||
raise ValueError("video_url 仅支持 MP4 格式")
|
||||
return v
|
||||
|
||||
has_audio = bool((self.audio_url or "").strip())
|
||||
has_tts = bool((self.voice_id or "").strip()) and bool((self.script_text or "").strip())
|
||||
@field_validator("voice_id")
|
||||
@classmethod
|
||||
def validate_voice_id(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("voice_id 不能为空")
|
||||
return v
|
||||
|
||||
if not has_audio and not has_tts:
|
||||
raise ValueError(
|
||||
"必须提供驱动音频:要么传 audio_url(直接音频模式),"
|
||||
"要么同时传 voice_id + script_text(TTS 直生模式)"
|
||||
)
|
||||
|
||||
if has_tts and len(self.script_text) > 5000:
|
||||
@field_validator("script_text")
|
||||
@classmethod
|
||||
def validate_script_text(cls, v: str) -> str:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("script_text 不能为空")
|
||||
if len(v) > 5000:
|
||||
raise ValueError("script_text 最长 5000 字符")
|
||||
|
||||
if has_audio:
|
||||
au = self.audio_url.strip()
|
||||
if not au.startswith(("http://", "https://")):
|
||||
raise ValueError("audio_url 必须是 HTTP/HTTPS URL")
|
||||
au_lower = au.lower().split("?")[0]
|
||||
allowed = (".mp3", ".aac", ".wav", ".m4a", ".flac")
|
||||
if not any(au_lower.endswith(ext) for ext in allowed):
|
||||
raise ValueError(f"audio_url 格式不支持,仅支持: {', '.join(allowed)}")
|
||||
self.audio_url = au
|
||||
|
||||
return self
|
||||
return v
|
||||
|
||||
@@ -16,7 +16,6 @@ class TTSSynthesizeRequest(BaseModel):
|
||||
output_name: str = Field("", description="输出文件名")
|
||||
language: str = Field("zh-CN", description="语言")
|
||||
speed: float = Field(1.0, ge=0.5, le=2.0, description="语速")
|
||||
emotion: str = Field("", description="情绪(natural/excited/calm/friendly,或中文 自然/兴奋/沉稳/亲切)")
|
||||
voice_model: str = Field("", description="语音模型名称")
|
||||
voice_clone_profile_id: str = Field("", description="关联的音色克隆档案 ID")
|
||||
format: str = Field("mp3", description="输出格式(mp3/wav/pcm)")
|
||||
@@ -110,7 +109,6 @@ class TTSPreviewRequest(BaseModel):
|
||||
text: str = Field(..., min_length=1, max_length=200, description="合成文本,限制 200 字")
|
||||
voice_id: str = Field(..., min_length=1, description="音色 ID")
|
||||
speed: float = Field(1.0, ge=0.5, le=2.0, description="语速")
|
||||
emotion: str = Field("", description="情绪(natural/excited/calm/friendly,或中文)")
|
||||
pitch: float = Field(1.0, ge=0.5, le=2.0, description="音调(预留,当前未使用)")
|
||||
|
||||
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
"""AI 数字人封面服务 — 复用智能剪辑的 MediaKit 抽帧 + 质量评分选最佳帧.
|
||||
|
||||
与 generation_cover.py 的智能选帧能力对齐(不再用 FFmpeg 简单截帧):
|
||||
1. MediaKit extract_frames 抽取多帧(默认 5 帧,SpecifiedFrames 策略)
|
||||
2. cover_frame_scorer.score_frames 按清晰度/亮度/色彩评分选最佳
|
||||
3. 下载最佳帧并转存 OSS,返回公网封面 URL
|
||||
|
||||
降级:MediaKit 不可用或抽帧失败时返回空字符串,由调用方决定回退策略。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tempfile
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# MediaKit 抽帧轮询参数(与 MediaKit API timeout=60s 对齐)
|
||||
COVER_POLL_INTERVAL = 3.0
|
||||
COVER_MAX_POLL_ATTEMPTS = 20 # 最多等 60 秒
|
||||
|
||||
# 帧图片下载超时(秒)
|
||||
FRAME_DOWNLOAD_TIMEOUT = 20
|
||||
# 最佳帧下载超时(用于 persist)
|
||||
BEST_FRAME_DOWNLOAD_TIMEOUT = 30
|
||||
|
||||
# 自家 OSS 私有桶 URL 重签有效期(供 MediaKit GPU worker 拉取)
|
||||
MEDIAKIT_URL_TTL_SECONDS = 7 * 24 * 3600
|
||||
|
||||
|
||||
def _sign_video_url_for_mediakit(video_url: str) -> str:
|
||||
"""如果 video_url 是自家 OSS 私有桶 URL,重新签名为长有效期预签名 URL。
|
||||
|
||||
MediaKit GPU worker 需要能公网访问 video_url,裸 public_url 在私有桶下会 403。
|
||||
"""
|
||||
if not video_url:
|
||||
return video_url
|
||||
try:
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
|
||||
storage = get_shared_storage_service()
|
||||
public_base = getattr(storage, "public_url", "")
|
||||
if not isinstance(public_base, str) or not public_base:
|
||||
return video_url
|
||||
own_host = urlparse(public_base).netloc.lower()
|
||||
url_host = urlparse(video_url).netloc.lower()
|
||||
if own_host and url_host == own_host:
|
||||
# 是自家 OSS URL,重签 7 天有效期供 MediaKit 拉取
|
||||
signed = storage.get_download_url(video_url, expires_seconds=MEDIAKIT_URL_TTL_SECONDS)
|
||||
if signed:
|
||||
logger.info("[数字人封面] video_url 已重签(自家 OSS 私有桶)")
|
||||
return signed
|
||||
except Exception:
|
||||
logger.warning("[数字人封面] video_url 重签失败,使用原始 URL", exc_info=True)
|
||||
return video_url
|
||||
|
||||
|
||||
def select_best_cover_frame(video_url: str, *, max_frames: int = 5) -> str:
|
||||
"""从视频抽取多帧并评分选最佳帧,返回最佳帧的临时 URL.
|
||||
|
||||
Args:
|
||||
video_url: 可公网访问的视频 URL
|
||||
max_frames: 抽帧数量
|
||||
|
||||
Returns:
|
||||
最佳帧图片 URL;失败返回空字符串
|
||||
"""
|
||||
if not video_url:
|
||||
return ""
|
||||
|
||||
# 确保 MediaKit 能访问 video_url(自家 OSS 私有桶需重签)
|
||||
video_url = _sign_video_url_for_mediakit(video_url)
|
||||
|
||||
try:
|
||||
from packages.shared.cover_frame_scorer import score_frames
|
||||
from packages.shared.mediakit_client import get_mediakit_client
|
||||
|
||||
mk = get_mediakit_client()
|
||||
if not mk.is_available:
|
||||
logger.warning("[数字人封面] MediaKit 未配置,无法智能抽帧")
|
||||
return ""
|
||||
|
||||
logger.info(
|
||||
"[数字人封面] 开始抽帧: video_url=%s max_frames=%d poll_interval=%.1f max_poll=%d",
|
||||
video_url[:80],
|
||||
max_frames,
|
||||
COVER_POLL_INTERVAL,
|
||||
COVER_MAX_POLL_ATTEMPTS,
|
||||
)
|
||||
|
||||
snapshots = mk.extract_frames(
|
||||
video_url=video_url,
|
||||
strategy="SpecifiedFrames",
|
||||
max_frames=max_frames,
|
||||
poll_interval=COVER_POLL_INTERVAL,
|
||||
max_poll_attempts=COVER_MAX_POLL_ATTEMPTS,
|
||||
max_retries=1,
|
||||
)
|
||||
if not snapshots:
|
||||
logger.warning("[数字人封面] MediaKit 未返回帧: %s", video_url[:80])
|
||||
return ""
|
||||
|
||||
if len(snapshots) == 1:
|
||||
return snapshots[0].get("image_url") or snapshots[0].get("url") or ""
|
||||
|
||||
# 使用连接池下载各帧(复用 TCP 连接,减少延迟)
|
||||
import httpx
|
||||
|
||||
candidates = []
|
||||
with httpx.Client(timeout=FRAME_DOWNLOAD_TIMEOUT, follow_redirects=True) as client:
|
||||
for snap in snapshots:
|
||||
url = snap.get("image_url") or snap.get("url") or ""
|
||||
if not url:
|
||||
continue
|
||||
tmp_path: Optional[str] = None
|
||||
try:
|
||||
resp = client.get(url)
|
||||
resp.raise_for_status()
|
||||
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
|
||||
tmp.write(resp.content)
|
||||
tmp_path = tmp.name
|
||||
candidates.append({"image_path": tmp_path, "url": url})
|
||||
except Exception as e:
|
||||
logger.warning("[数字人封面] 帧下载失败,跳过: url=%s err=%s", url[:80], e)
|
||||
candidates.append({"image_path": None, "url": url, "score": 0.0})
|
||||
|
||||
if not candidates:
|
||||
return snapshots[0].get("image_url") or snapshots[0].get("url") or ""
|
||||
|
||||
scored = score_frames(candidates)
|
||||
best = scored[0] if scored else None
|
||||
best_url = best.get("url", "") if best else ""
|
||||
|
||||
# 清理临时文件
|
||||
for c in candidates:
|
||||
p = c.get("image_path")
|
||||
if p:
|
||||
try:
|
||||
Path(p).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
logger.info(
|
||||
"[数字人封面] 智能选帧完成: candidates=%d best_score=%s",
|
||||
len(candidates),
|
||||
best.get("score") if best else "n/a",
|
||||
)
|
||||
return best_url
|
||||
|
||||
except Exception:
|
||||
logger.warning("[数字人封面] 智能选帧失败", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
def persist_cover_to_oss(frame_url: str, *, job_id: str = "", prefix: str = "ai-avatar/covers") -> str:
|
||||
"""下载帧图并转存到 OSS,返回公网封面 URL.
|
||||
|
||||
Args:
|
||||
frame_url: MediaKit 返回的临时帧图 URL
|
||||
job_id: 关联任务 ID(用于 OSS key 命名)
|
||||
prefix: OSS key 前缀
|
||||
|
||||
Returns:
|
||||
OSS 公网 URL;失败回退原始 frame_url
|
||||
"""
|
||||
if not frame_url:
|
||||
return ""
|
||||
tmp_path: Optional[str] = None
|
||||
try:
|
||||
import httpx
|
||||
|
||||
with httpx.Client(timeout=BEST_FRAME_DOWNLOAD_TIMEOUT, follow_redirects=True) as client:
|
||||
resp = client.get(frame_url)
|
||||
resp.raise_for_status()
|
||||
if not resp.content:
|
||||
logger.warning("[数字人封面] 帧图内容为空: %s", frame_url[:80])
|
||||
return frame_url
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
|
||||
tmp.write(resp.content)
|
||||
tmp_path = tmp.name
|
||||
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
|
||||
storage = get_shared_storage_service()
|
||||
token = job_id or uuid.uuid4().hex[:12]
|
||||
cover_key = f"{prefix}/{token}/cover_{uuid.uuid4().hex[:8]}.jpg"
|
||||
public_url = storage.upload_file(
|
||||
file_or_path=tmp_path,
|
||||
storage_key=cover_key,
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
logger.info("[数字人封面] 封面已转存 OSS: key=%s", cover_key)
|
||||
# 私有桶:返回预签名 URL(前端才能加载)
|
||||
if public_url:
|
||||
signed = storage.get_download_url(cover_key, expires_seconds=86400)
|
||||
return signed
|
||||
return frame_url
|
||||
except Exception:
|
||||
logger.warning("[数字人封面] 封面转存 OSS 失败,返回原始 URL", exc_info=True)
|
||||
return frame_url
|
||||
finally:
|
||||
if tmp_path:
|
||||
try:
|
||||
Path(tmp_path).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def generate_smart_cover(video_url: str, *, job_id: str = "", max_frames: int = 5) -> str:
|
||||
"""一站式:MediaKit 智能抽帧选最佳 → 转存 OSS,返回封面公网 URL.
|
||||
|
||||
供独立封面接口与渲染管线复用。失败返回空字符串。
|
||||
"""
|
||||
best_frame = select_best_cover_frame(video_url, max_frames=max_frames)
|
||||
if not best_frame:
|
||||
return ""
|
||||
return persist_cover_to_oss(best_frame, job_id=job_id)
|
||||
@@ -53,8 +53,8 @@ class AiAvatarRenderService:
|
||||
*,
|
||||
user_id: str,
|
||||
lipsync_job_id: str,
|
||||
script_id: str = "",
|
||||
b_roll_segments: list[dict[str, Any]] | None = None,
|
||||
script_id: str,
|
||||
b_roll_segments: list[dict[str, Any]],
|
||||
title_config: dict[str, Any],
|
||||
cover_config: dict[str, Any],
|
||||
project_id: str = "",
|
||||
@@ -83,19 +83,17 @@ class AiAvatarRenderService:
|
||||
if not lipsync_job.output_video_url:
|
||||
raise AiAvatarRenderError("对口型任务输出视频 URL 为空", code="LipsyncJobNoOutput")
|
||||
|
||||
# 2. 验证文案归属(仅当选了文案库条目时;手动输入文案直生场景 script_id 可空)
|
||||
script_id = (script_id or "").strip()
|
||||
if script_id:
|
||||
script = (
|
||||
self.db.query(ScriptModel)
|
||||
.filter(
|
||||
ScriptModel.id == script_id,
|
||||
ScriptModel.user_id == user_id,
|
||||
)
|
||||
.first()
|
||||
# 2. 验证文案归属
|
||||
script = (
|
||||
self.db.query(ScriptModel)
|
||||
.filter(
|
||||
ScriptModel.id == script_id,
|
||||
ScriptModel.user_id == user_id,
|
||||
)
|
||||
if script is None:
|
||||
raise AiAvatarRenderError("文案不存在或无权访问", code="ScriptNotFound")
|
||||
.first()
|
||||
)
|
||||
if script is None:
|
||||
raise AiAvatarRenderError("文案不存在或无权访问", code="ScriptNotFound")
|
||||
|
||||
# 3. 创建渲染任务
|
||||
job_id = str(uuid.uuid4())
|
||||
@@ -105,7 +103,7 @@ class AiAvatarRenderService:
|
||||
project_id=project_id,
|
||||
lipsync_job_id=lipsync_job_id,
|
||||
script_id=script_id,
|
||||
b_roll_segments=[s if isinstance(s, dict) else s.model_dump() for s in (b_roll_segments or [])],
|
||||
b_roll_segments=[s if isinstance(s, dict) else s.model_dump() for s in b_roll_segments],
|
||||
title_config=title_config,
|
||||
cover_config=cover_config,
|
||||
status="pending",
|
||||
@@ -290,22 +288,7 @@ class AiAvatarRenderService:
|
||||
output_video_url = self._upload_to_oss(output_video_path, f"ai-avatar/{job_id}/output.mp4")
|
||||
job.output_video_url = output_video_url
|
||||
|
||||
# 封面:优先复用智能剪辑的 MediaKit 抽帧 + 质量评分选最佳帧;
|
||||
# MediaKit 不可用时回退到 FFmpeg 已按 cover_config 抽取的 cover_path
|
||||
smart_cover_url = ""
|
||||
if output_video_url:
|
||||
try:
|
||||
from app.services.ai_avatar_cover_service import (
|
||||
generate_smart_cover,
|
||||
)
|
||||
|
||||
smart_cover_url = generate_smart_cover(output_video_url, job_id=job_id, max_frames=5)
|
||||
except Exception:
|
||||
logger.warning("智能封面(MediaKit)失败,回退 FFmpeg 封面 job_id=%s", job_id, exc_info=True)
|
||||
|
||||
if smart_cover_url:
|
||||
job.output_cover_url = smart_cover_url
|
||||
elif cover_path:
|
||||
if cover_path:
|
||||
output_cover_url = self._upload_to_oss(cover_path, f"ai-avatar/{job_id}/cover.jpg")
|
||||
job.output_cover_url = output_cover_url
|
||||
|
||||
@@ -322,38 +305,6 @@ class AiAvatarRenderService:
|
||||
self.db.commit()
|
||||
logger.info("渲染任务完成: %s", job_id)
|
||||
|
||||
# 7. 自动保存成片记录到成片库
|
||||
if job.output_video_url:
|
||||
try:
|
||||
from packages.adapters.sqlalchemy_impl.generated_video_repository import (
|
||||
SQLAlchemyGeneratedVideoRepository,
|
||||
)
|
||||
from packages.domain.generated_video import GeneratedVideo
|
||||
|
||||
clip_name = f"AI数字人_{job_id[:8]}"
|
||||
clip = GeneratedVideo.create(
|
||||
project_id=job.project_id,
|
||||
generation_task_id=job.lipsync_job_id,
|
||||
name=clip_name,
|
||||
file_url=job.output_video_url,
|
||||
user_id=job.user_id,
|
||||
duration=job.output_duration or 0.0,
|
||||
thumbnail_url=job.output_cover_url or None,
|
||||
generation_params={
|
||||
"source": "ai_avatar_render",
|
||||
"render_job_id": job.id,
|
||||
},
|
||||
)
|
||||
video_repo = SQLAlchemyGeneratedVideoRepository(self.db)
|
||||
video_repo.create(clip)
|
||||
logger.info("成片记录已保存到成片库: clip_id=%s, render_job=%s", clip.id, job_id)
|
||||
except Exception as clip_err:
|
||||
logger.warning(
|
||||
"自动保存成片记录失败(不影响渲染任务状态): render_job=%s, error=%s",
|
||||
job_id,
|
||||
clip_err,
|
||||
)
|
||||
|
||||
except AiAvatarRenderError as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = str(exc)
|
||||
@@ -408,7 +359,7 @@ class AiAvatarRenderService:
|
||||
else:
|
||||
filter_arg = ""
|
||||
|
||||
return f"ffmpeg {inputs} {filter_arg} -c:v libx264 -preset veryfast -crf 23 -y {output_path}"
|
||||
return f"ffmpeg {inputs} {filter_arg} -c:v libx264 -preset fast -crf 23 -y {output_path}"
|
||||
|
||||
def _upload_to_oss(self, local_path: str, oss_key: str) -> str:
|
||||
"""上传文件到 OSS,返回 URL.
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
"""对口型 Service — #1796 MediaKit 对口型业务逻辑, #1809 参数调整.
|
||||
|
||||
职责:
|
||||
- 创建/查询对口型任务
|
||||
- 双输入模式:TTS 直生(voice_id + script_text,内部先合成音频转存 OSS)或直接音频(audio_url)
|
||||
- 创建/查询/取消对口型任务
|
||||
- 调用 TTS 合成音频(#1809:前端不再传 audio_url)
|
||||
- 调用 MediaKit 客户端提交异步任务
|
||||
- 轮询更新任务状态(中间状态同步 DB,成片转存自家 OSS)
|
||||
- 轮询更新任务状态
|
||||
- 用户隔离(每个用户只能操作自己的任务)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.services.mediakit_client import (
|
||||
STATUS_COMPLETED,
|
||||
@@ -25,22 +23,13 @@ from app.services.mediakit_client import (
|
||||
MediaKitError,
|
||||
get_mediakit_client,
|
||||
)
|
||||
|
||||
# Celery 异步任务:TTS 合成 + MediaKit 提交(#lipsync-speed-optimization)
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.models import LipsyncJobModel
|
||||
from packages.application.cosyvoice_service import CosyVoiceError, normalize_emotion
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
from packages.shared.url_security import ALLOWED_AUDIO_MIME_TYPES, safe_download_bytes
|
||||
from packages.application.cosyvoice_service import CosyVoiceError, CosyVoiceService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 传给 MediaKit GPU worker / 回给前端播放的 OSS 预签名有效期:7 天。
|
||||
# MediaKit 排队 + 拉取可能延迟,私有桶裸 URL 或 1 小时短预签名都会 403,故统一重签长有效期。
|
||||
MEDIAKIT_URL_TTL_SECONDS = 7 * 24 * 3600
|
||||
|
||||
|
||||
class LipsyncService:
|
||||
"""对口型任务 Service."""
|
||||
@@ -49,98 +38,19 @@ class LipsyncService:
|
||||
self,
|
||||
db: Session,
|
||||
client: Optional[MediaKitClient] = None,
|
||||
cosyvoice_service=None,
|
||||
voice_clone_repo=None,
|
||||
cosyvoice_service: Optional[CosyVoiceService] = None,
|
||||
):
|
||||
self.db = db
|
||||
self.client = client or get_mediakit_client()
|
||||
self._cosyvoice = cosyvoice_service
|
||||
self._voice_clone_repo = voice_clone_repo
|
||||
self._cosyvoice_service = cosyvoice_service
|
||||
|
||||
def _get_cosyvoice(self):
|
||||
"""延迟获取 CosyVoiceService(与 tts 路由一致,含 OSS 预签名配置)."""
|
||||
if self._cosyvoice is None:
|
||||
@property
|
||||
def cosyvoice_service(self) -> CosyVoiceService:
|
||||
if self._cosyvoice_service is None:
|
||||
from app.dependencies import get_cosyvoice_service
|
||||
|
||||
self._cosyvoice = get_cosyvoice_service()
|
||||
return self._cosyvoice
|
||||
|
||||
def _resolve_voice_id(self, voice_id: str, user_id: str) -> str:
|
||||
"""将克隆音色 profile UUID 解析为 CosyVoice voice_id。
|
||||
|
||||
与 /tts/synthesize 保持一致:命中 profile → 校验归属 → 返回其 voice_id;
|
||||
未命中(预置音色 ID 或克隆 CosyVoice voice_id)原样返回。
|
||||
"""
|
||||
if not voice_id:
|
||||
return ""
|
||||
if self._voice_clone_repo is None:
|
||||
try:
|
||||
from app.dependencies import get_voice_clone_profile_repository
|
||||
|
||||
self._voice_clone_repo = get_voice_clone_profile_repository(self.db)
|
||||
except Exception:
|
||||
return voice_id
|
||||
try:
|
||||
profile = self._voice_clone_repo.get(voice_id)
|
||||
except Exception:
|
||||
return voice_id
|
||||
if profile is None:
|
||||
return voice_id
|
||||
if getattr(profile, "user_id", "") != user_id:
|
||||
raise MediaKitError("无权访问该音色", code="VoiceForbidden")
|
||||
if not getattr(profile, "voice_id", ""):
|
||||
raise MediaKitError("音色克隆尚未完成,请稍后再试", code="VoiceNotReady")
|
||||
return profile.voice_id
|
||||
|
||||
def _synthesize_and_persist_audio(
|
||||
self,
|
||||
*,
|
||||
user_id: str,
|
||||
job_id: str,
|
||||
voice_id: str,
|
||||
script_text: str,
|
||||
speed: float,
|
||||
emotion: str,
|
||||
) -> str:
|
||||
"""TTS 直生:调 CosyVoice 合成音频并转存 OSS,返回可公网访问的音频 URL.
|
||||
|
||||
Raises:
|
||||
MediaKitError: 合成失败
|
||||
"""
|
||||
actual_voice_id = self._resolve_voice_id(voice_id, user_id)
|
||||
cosyvoice = self._get_cosyvoice()
|
||||
try:
|
||||
result = cosyvoice.submit_synthesize_task(
|
||||
text=script_text,
|
||||
voice_id=actual_voice_id,
|
||||
speed=speed,
|
||||
emotion=normalize_emotion(emotion),
|
||||
)
|
||||
except CosyVoiceError as exc:
|
||||
raise MediaKitError(f"TTS 合成失败: {exc}", code="TTSSynthesisFailed") from exc
|
||||
except ValueError as exc:
|
||||
raise MediaKitError(f"TTS 参数错误: {exc}", code="TTSInvalidParam") from exc
|
||||
|
||||
temp_url = result.get("audio_url", "")
|
||||
if not temp_url:
|
||||
raise MediaKitError("TTS 未返回音频 URL", code="TTSNoAudio")
|
||||
|
||||
# 转存到自家 OSS,避免临时 URL 过期导致 MediaKit 拉取失败
|
||||
try:
|
||||
audio_data = safe_download_bytes(
|
||||
temp_url,
|
||||
purpose="lipsync_tts_audio",
|
||||
allowed_mime_types=ALLOWED_AUDIO_MIME_TYPES,
|
||||
timeout=60.0,
|
||||
)
|
||||
storage = get_shared_storage_service()
|
||||
storage_key = f"lipsync-tts/{user_id}/{job_id}.mp3"
|
||||
permanent_url = storage.upload_file(io.BytesIO(audio_data), storage_key, content_type="audio/mpeg")
|
||||
logger.info("对口型 TTS 音频已转存 OSS: job_id=%s key=%s", job_id, storage_key)
|
||||
return permanent_url
|
||||
except Exception as exc:
|
||||
logger.warning("TTS 音频转存 OSS 失败,回退临时 URL: job_id=%s err=%s", job_id, exc)
|
||||
return temp_url
|
||||
self._cosyvoice_service = get_cosyvoice_service()
|
||||
return self._cosyvoice_service
|
||||
|
||||
# ── 创建任务 ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -149,39 +59,48 @@ class LipsyncService:
|
||||
*,
|
||||
user_id: str,
|
||||
video_url: str,
|
||||
audio_url: str = "",
|
||||
voice_id: str = "",
|
||||
script_text: str = "",
|
||||
speed: float = 1.0,
|
||||
emotion: str = "",
|
||||
voice_id: str,
|
||||
script_text: str,
|
||||
enable_video_loop: bool = False,
|
||||
project_id: str = "",
|
||||
) -> LipsyncJobModel:
|
||||
"""创建对口型任务.
|
||||
"""创建对口型任务并提交到 MediaKit.
|
||||
|
||||
两种输入模式:
|
||||
- TTS 直生:voice_id + script_text(audio_url 留空)
|
||||
→ 先创建 DB 记录(状态 tts_processing),再 dispatch Celery 异步任务
|
||||
执行 TTS 合成 + MediaKit 提交。API 响应 <1s。
|
||||
- 直接音频:提供 audio_url
|
||||
→ 同步提交 MediaKit,状态直接设为 submitted。
|
||||
#1809: 内部调 TTS 合成音频,不再由前端传 audio_url。
|
||||
|
||||
Raises:
|
||||
MediaKitError: 参数校验失败或 MediaKit 提交失败(仅直接音频模式)
|
||||
CosyVoiceError: TTS 合成失败
|
||||
MediaKitError: API 调用失败
|
||||
"""
|
||||
# 0. 输入校验
|
||||
if not audio_url:
|
||||
if not (voice_id and script_text):
|
||||
raise MediaKitError(
|
||||
"必须提供 audio_url 或 voice_id+script_text",
|
||||
code="InvalidInput",
|
||||
)
|
||||
# TTS 模式:在 HTTP 请求中同步校验音色归属,快速失败
|
||||
self._resolve_voice_id(voice_id, user_id)
|
||||
# 1. 调 TTS 合成音频
|
||||
try:
|
||||
tts_result = self.cosyvoice_service.synthesize_speech(
|
||||
text=script_text,
|
||||
voice_id=voice_id,
|
||||
)
|
||||
audio_url = tts_result.audio_url
|
||||
except CosyVoiceError as exc:
|
||||
logger.error("TTS 合成失败: voice_id=%s, error=%s", voice_id, exc)
|
||||
# 创建失败记录
|
||||
job_id = str(uuid.uuid4())
|
||||
job = LipsyncJobModel(
|
||||
id=job_id,
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
video_url=video_url,
|
||||
audio_url="",
|
||||
enable_video_loop=enable_video_loop,
|
||||
status="failed",
|
||||
error_message=f"TTS 合成失败: {exc}",
|
||||
error_code="TTSSynthesisFailed",
|
||||
)
|
||||
self.db.add(job)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
raise
|
||||
|
||||
# 1. 创建数据库记录
|
||||
# 2. 创建数据库记录
|
||||
job_id = str(uuid.uuid4())
|
||||
is_tts_mode = not bool(audio_url)
|
||||
job = LipsyncJobModel(
|
||||
id=job_id,
|
||||
user_id=user_id,
|
||||
@@ -189,57 +108,28 @@ class LipsyncService:
|
||||
video_url=video_url,
|
||||
audio_url=audio_url,
|
||||
enable_video_loop=enable_video_loop,
|
||||
voice_id=voice_id or "",
|
||||
script_text=script_text or "",
|
||||
speed=speed,
|
||||
emotion=normalize_emotion(emotion),
|
||||
status="tts_processing" if is_tts_mode else "pending",
|
||||
status="pending",
|
||||
)
|
||||
self.db.add(job)
|
||||
self.db.flush()
|
||||
|
||||
if is_tts_mode:
|
||||
# 2a. TTS 模式:dispatch Celery 异步任务处理 TTS 合成 + MediaKit 提交
|
||||
try:
|
||||
tts_synthesize_and_submit.apply_async(
|
||||
args=(
|
||||
job_id,
|
||||
user_id,
|
||||
voice_id,
|
||||
script_text,
|
||||
speed,
|
||||
normalize_emotion(emotion),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Celery 任务提交失败,TTS 任务已创建但未触发执行: %s",
|
||||
job_id,
|
||||
exc_info=True,
|
||||
)
|
||||
else:
|
||||
# 2b. 直接音频模式:同步签名并提交 MediaKit
|
||||
video_url = self._sign_media_url(video_url)
|
||||
if audio_url:
|
||||
audio_url = self._sign_media_url(audio_url)
|
||||
job.audio_url = audio_url
|
||||
|
||||
try:
|
||||
result = self.client.submit_lipsync(
|
||||
video_url=video_url,
|
||||
audio_url=audio_url,
|
||||
enable_video_loop=enable_video_loop,
|
||||
client_token=job_id,
|
||||
)
|
||||
job.mediakit_task_id = result["task_id"]
|
||||
job.status = "submitted"
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
except MediaKitError as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = str(exc)
|
||||
job.error_code = exc.code
|
||||
logger.error("提交对口型任务失败: %s", exc)
|
||||
raise
|
||||
# 3. 提交到 MediaKit
|
||||
try:
|
||||
result = self.client.submit_lipsync(
|
||||
video_url=video_url,
|
||||
audio_url=audio_url,
|
||||
enable_video_loop=enable_video_loop,
|
||||
client_token=job_id, # 幂等控制
|
||||
)
|
||||
job.mediakit_task_id = result["task_id"]
|
||||
job.status = "submitted"
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
except MediaKitError as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = str(exc)
|
||||
job.error_code = exc.code
|
||||
logger.error("提交对口型任务失败: %s", exc)
|
||||
raise
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
@@ -302,14 +192,11 @@ class LipsyncService:
|
||||
return job
|
||||
|
||||
mk_status = status_data.get("status", STATUS_RUNNING)
|
||||
logger.info("MediaKit 对口型状态 [%s]: %s", job_id, mk_status)
|
||||
|
||||
if mk_status == STATUS_COMPLETED:
|
||||
result = status_data.get("result", {})
|
||||
job.status = STATUS_COMPLETED
|
||||
output_url = result.get("video_url", "")
|
||||
# MediaKit 输出为临时 URL,转存自家 OSS 防止过期(失败则回退临时 URL)
|
||||
job.output_video_url = self._persist_output_video(output_url, job_id, user_id)
|
||||
job.output_video_url = result.get("video_url", "")
|
||||
job.output_duration = result.get("duration", 0.0)
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
elif mk_status == STATUS_FAILED:
|
||||
@@ -318,72 +205,21 @@ class LipsyncService:
|
||||
job.error_message = error.get("message", "任务执行失败")
|
||||
job.error_code = error.get("code", "TaskFailed")
|
||||
job.completed_at = datetime.now(timezone.utc)
|
||||
else:
|
||||
# 中间状态(running/processing/queued 等)同步到 DB,避免前端永远卡在 submitted
|
||||
if isinstance(mk_status, str) and mk_status:
|
||||
job.status = mk_status
|
||||
# running 状态只更新时间戳
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
self.db.refresh(job)
|
||||
return job
|
||||
|
||||
def _persist_output_video(self, temp_url: str, job_id: str, user_id: str) -> str:
|
||||
"""将 MediaKit 输出的临时视频 URL 转存到自家 OSS.
|
||||
|
||||
失败时回退返回原始临时 URL,不影响任务完成。
|
||||
"""
|
||||
if not temp_url:
|
||||
return ""
|
||||
try:
|
||||
import httpx
|
||||
|
||||
with httpx.Client(timeout=180.0, follow_redirects=True) as client:
|
||||
resp = client.get(temp_url)
|
||||
resp.raise_for_status()
|
||||
data = resp.content
|
||||
storage = get_shared_storage_service()
|
||||
storage_key = f"lipsync-outputs/{user_id}/{job_id}.mp4"
|
||||
permanent_url = storage.upload_file(io.BytesIO(data), storage_key, content_type="video/mp4")
|
||||
logger.info("对口型输出视频已转存 OSS: job_id=%s key=%s", job_id, storage_key)
|
||||
return self._sign_media_url(permanent_url) or temp_url
|
||||
except Exception as exc:
|
||||
logger.warning("对口型输出视频转存 OSS 失败,回退临时 URL: job_id=%s err=%s", job_id, exc)
|
||||
return temp_url
|
||||
|
||||
def _sign_media_url(self, url: str) -> str:
|
||||
"""对自家 OSS 私有桶 URL 重签长有效期预签名,供 MediaKit 拉取 / 前端播放。
|
||||
|
||||
- 裸 public_url(upload_file 返回,不带签名)→ 私有桶匿名访问 403,重签。
|
||||
- 已带签名但即将过期的 URL(如前端 1h 预签名)→ 抽 storage_key 后重签。
|
||||
- 外部 URL(CosyVoice/MediaKit 临时链接,非本桶 host)→ 原样透传。
|
||||
- 任何异常都降级原样返回,不阻断主流程。
|
||||
"""
|
||||
if not url:
|
||||
return url
|
||||
try:
|
||||
storage = get_shared_storage_service()
|
||||
public_base = getattr(storage, "public_url", "")
|
||||
if not isinstance(public_base, str) or not public_base:
|
||||
return url # 无法判定归属,保守透传
|
||||
own_host = urlparse(public_base).netloc.lower()
|
||||
host = urlparse(url).netloc.lower()
|
||||
if not own_host or host != own_host:
|
||||
return url # 非自家 OSS(外部临时链接),不处理
|
||||
signed = storage.get_download_url(url, expires_seconds=MEDIAKIT_URL_TTL_SECONDS)
|
||||
return signed or url
|
||||
except Exception as exc: # noqa: BLE001 - 签名失败不阻断,降级原 URL
|
||||
logger.warning("对口型 URL 重签失败,原样返回: url_prefix=%s err=%s", url[:80], exc)
|
||||
return url
|
||||
|
||||
# ── 取消任务 ──────────────────────────────────────────────────────────
|
||||
|
||||
def cancel_job(self, job_id: str, user_id: str) -> Optional[LipsyncJobModel]:
|
||||
"""取消任务(仅 pending/tts_processing/submitted 状态可取消)."""
|
||||
"""取消任务(仅 pending/submitted 状态可取消)."""
|
||||
job = self.get_job(job_id, user_id)
|
||||
if job is None:
|
||||
return None
|
||||
|
||||
if job.status in ("pending", "tts_processing", "submitted"):
|
||||
if job.status in ("pending", "submitted"):
|
||||
job.status = "cancelled"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
"""AI 数字人对口型 TTS 异步任务 — 将 TTS 合成从 HTTP 请求移至 Celery 后台执行.
|
||||
|
||||
优化目标:将 create_job 的 API 响应时间从 6~35s 降到 <1s。
|
||||
任务流程:
|
||||
1. 创建新 DB session,加载 job 记录
|
||||
2. 调用 CosyVoice 合成音频
|
||||
3. 下载音频并转存到自家 OSS
|
||||
4. 更新 job 的 audio_url
|
||||
5. 签名 URL 并提交到 MediaKit
|
||||
6. 更新 job 状态为 submitted
|
||||
7. 异常时标记 job 为 failed
|
||||
"""
|
||||
|
||||
import io
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.core.celery_app import celery_app
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@celery_app.task(
|
||||
bind=True,
|
||||
name="lipsync_tts.synthesize_and_submit",
|
||||
max_retries=2,
|
||||
default_retry_delay=30,
|
||||
)
|
||||
def tts_synthesize_and_submit(
|
||||
self,
|
||||
job_id: str,
|
||||
user_id: str,
|
||||
voice_id: str,
|
||||
script_text: str,
|
||||
speed: float,
|
||||
emotion: str,
|
||||
):
|
||||
"""异步执行 TTS 合成 + OSS 转存 + MediaKit 提交.
|
||||
|
||||
在 Celery worker 中运行,不阻塞 HTTP 请求。
|
||||
"""
|
||||
from app.services.mediakit_client import MediaKitError, get_mediakit_client
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from packages.adapters.sqlalchemy_impl.database import SessionLocal
|
||||
from packages.adapters.sqlalchemy_impl.models import LipsyncJobModel
|
||||
from packages.application.cosyvoice_service import CosyVoiceError, CosyVoiceService
|
||||
from packages.shared.storage import get_shared_storage_service
|
||||
from packages.shared.url_security import safe_download_bytes
|
||||
|
||||
db: DBSession = SessionLocal()
|
||||
try:
|
||||
job = (
|
||||
db.query(LipsyncJobModel)
|
||||
.filter(
|
||||
LipsyncJobModel.id == job_id,
|
||||
LipsyncJobModel.user_id == user_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
if job is None:
|
||||
logger.error("[lipsync_tts] Job not found: job_id=%s", job_id)
|
||||
return
|
||||
|
||||
# 已取消的任务不再处理
|
||||
if job.status == "cancelled":
|
||||
logger.info("[lipsync_tts] Job already cancelled, skipping: job_id=%s", job_id)
|
||||
return
|
||||
|
||||
# 1. TTS 合成
|
||||
try:
|
||||
cosyvoice = CosyVoiceService()
|
||||
result = cosyvoice.submit_synthesize_task(
|
||||
text=script_text,
|
||||
voice_id=voice_id,
|
||||
speed=speed,
|
||||
emotion=emotion,
|
||||
)
|
||||
except CosyVoiceError as exc:
|
||||
logger.error("[lipsync_tts] TTS 合成失败: job_id=%s err=%s", job_id, exc)
|
||||
job.status = "failed"
|
||||
job.error_message = f"TTS 合成失败: {exc}"
|
||||
job.error_code = "TTSSynthesisFailed"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
return
|
||||
except ValueError as exc:
|
||||
logger.error("[lipsync_tts] TTS 参数错误: job_id=%s err=%s", job_id, exc)
|
||||
job.status = "failed"
|
||||
job.error_message = f"TTS 参数错误: {exc}"
|
||||
job.error_code = "TTSInvalidParam"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
return
|
||||
|
||||
temp_url = result.get("audio_url", "")
|
||||
if not temp_url:
|
||||
logger.error("[lipsync_tts] TTS 未返回音频 URL: job_id=%s", job_id)
|
||||
job.status = "failed"
|
||||
job.error_message = "TTS 未返回音频 URL"
|
||||
job.error_code = "TTSNoAudio"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
return
|
||||
|
||||
# 2. 下载并转存到自家 OSS
|
||||
try:
|
||||
audio_data = safe_download_bytes(
|
||||
temp_url,
|
||||
purpose="lipsync_tts_audio",
|
||||
allowed_mime_types=("audio/mpeg", "audio/mp3", "audio/wav", "audio/mp4", "audio/x-m4a"),
|
||||
timeout=60.0,
|
||||
)
|
||||
storage = get_shared_storage_service()
|
||||
storage_key = f"lipsync-tts/{user_id}/{job_id}.mp3"
|
||||
permanent_url = storage.upload_file(io.BytesIO(audio_data), storage_key, content_type="audio/mpeg")
|
||||
logger.info("[lipsync_tts] TTS 音频已转存 OSS: job_id=%s key=%s", job_id, storage_key)
|
||||
job.audio_url = permanent_url
|
||||
except Exception as exc:
|
||||
logger.warning("[lipsync_tts] TTS 音频转存 OSS 失败,回退临时 URL: job_id=%s err=%s", job_id, exc)
|
||||
job.audio_url = temp_url
|
||||
|
||||
db.commit()
|
||||
|
||||
# 3. 签名 URL 并提交到 MediaKit
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
temp_service = LipsyncService.__new__(LipsyncService)
|
||||
audio_url = temp_service._sign_media_url(job.audio_url)
|
||||
video_url = temp_service._sign_media_url(job.video_url)
|
||||
|
||||
client = get_mediakit_client()
|
||||
try:
|
||||
mk_result = client.submit_lipsync(
|
||||
video_url=video_url,
|
||||
audio_url=audio_url,
|
||||
enable_video_loop=job.enable_video_loop,
|
||||
client_token=job_id,
|
||||
)
|
||||
job.mediakit_task_id = mk_result["task_id"]
|
||||
job.status = "submitted"
|
||||
job.submitted_at = datetime.now(timezone.utc)
|
||||
logger.info("[lipsync_tts] 已提交 MediaKit: job_id=%s task_id=%s", job_id, mk_result["task_id"])
|
||||
except MediaKitError as exc:
|
||||
job.status = "failed"
|
||||
job.error_message = str(exc)
|
||||
job.error_code = exc.code
|
||||
logger.error("[lipsync_tts] 提交 MediaKit 失败: job_id=%s err=%s", job_id, exc)
|
||||
|
||||
db.commit()
|
||||
|
||||
except Exception:
|
||||
logger.exception("[lipsync_tts] 未预期的异常: job_id=%s", job_id)
|
||||
try:
|
||||
job = db.query(LipsyncJobModel).filter(LipsyncJobModel.id == job_id).first()
|
||||
if job and job.status not in ("cancelled", "failed", "completed"):
|
||||
job.status = "failed"
|
||||
job.error_message = "TTS 异步任务执行异常"
|
||||
job.error_code = "AsyncTaskError"
|
||||
job.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
except Exception:
|
||||
logger.exception("[lipsync_tts] 回写失败状态时异常: job_id=%s", job_id)
|
||||
finally:
|
||||
db.close()
|
||||
@@ -103,7 +103,6 @@ export interface TTSPreviewRequest {
|
||||
voice_id: string
|
||||
speed?: number
|
||||
pitch?: number
|
||||
emotion?: string // 情绪参数:natural/excited/calm/friendly
|
||||
}
|
||||
|
||||
/** TTS 试听响应 */
|
||||
|
||||
@@ -486,16 +486,14 @@
|
||||
|
||||
.aa-lipsync-preview {
|
||||
width: 100%;
|
||||
max-width: 240px;
|
||||
aspect-ratio: 9/16;
|
||||
background: #0f0f1a;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin: 0 auto 12px auto;
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.aa-lipsync-preview video {
|
||||
@@ -549,23 +547,21 @@
|
||||
/* ── 封面 & 生成 ── */
|
||||
.aa-cover-preview {
|
||||
width: 100%;
|
||||
max-width: 240px;
|
||||
aspect-ratio: 9/16;
|
||||
max-height: 160px;
|
||||
background: #f0f0f5;
|
||||
border-radius: 8px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 auto 12px auto;
|
||||
position: relative;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.aa-cover-preview img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.aa-cover-preview__placeholder {
|
||||
@@ -1154,99 +1150,3 @@
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* ─ 对口型生成弹窗 Spinner ── */
|
||||
.aa-lipsync-spinner {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border: 4px solid #f0f0f5;
|
||||
border-top-color: #6366f1;
|
||||
border-radius: 50%;
|
||||
animation: aa-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes aa-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.aa-btn--danger {
|
||||
background: #ff4d4f;
|
||||
color: #fff;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.aa-btn--danger:hover {
|
||||
background: #ff7875;
|
||||
}
|
||||
|
||||
/* ── v3.1 两步骤导航(仅追加,不改动上方任何原有样式) ── */
|
||||
.aa-step-nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
padding: 10px 24px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e8e8ec;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.aa-step-nav__item {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #8c8ca1;
|
||||
position: relative;
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
|
||||
.aa-step-nav__item.active {
|
||||
color: #4f46e5;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.aa-step-nav__item.active::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: -11px;
|
||||
height: 2px;
|
||||
background: #4f46e5;
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* 步骤切换按钮行 */
|
||||
.aa-step-btn-row {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed #f0f0f5;
|
||||
}
|
||||
|
||||
.aa-step-btn-row .aa-btn {
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
/* 分步布局:每个步骤 3 个横向面板等宽撑满(沿用原 .aa-panel 外观,仅改宽度) */
|
||||
.aa-page-body > .aa-panel--s1,
|
||||
.aa-page-body > .aa-panel--s2 {
|
||||
flex: 1 1 0;
|
||||
width: auto;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
/* 文案 / 对口型预览面板内容较多,给更宽的弹性比例 */
|
||||
.aa-page-body > .aa-panel--s1-wide {
|
||||
flex: 1.4 1 0;
|
||||
width: auto;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.aa-page-body > .aa-panel--s2-wide {
|
||||
flex: 1.4 1 0;
|
||||
width: auto;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
/**
|
||||
* AI数字人 — 主页面(v3 两步骤版)
|
||||
* 步骤1:出镜视频 / 配音库 / 文案
|
||||
* 步骤2:对口型预览(含插入画面)/ 标题配置 / 封面&生成
|
||||
* AI数字人 — 主页面(v3)
|
||||
* 5列水平面板布局
|
||||
*/
|
||||
import React, { useState, useCallback, useEffect, useRef } from "react"
|
||||
import { message } from "antd"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import "./AiAvatar.css"
|
||||
import { useAiAvatar } from "./hooks/useAiAvatar"
|
||||
import { PanelVideoSelector } from "./components/PanelVideoSelector"
|
||||
import PanelVoiceSelector from "./components/PanelVoiceSelector"
|
||||
import PanelScript from "./components/PanelScript"
|
||||
import PanelLipsyncPreview from "./components/PanelLipsyncPreview"
|
||||
import PanelScriptAndLipsync from "./components/PanelScriptAndLipsync"
|
||||
import PanelTitleConfig from "./components/PanelTitleConfig"
|
||||
import PanelCoverAndGenerate from "./components/PanelCoverAndGenerate"
|
||||
import { ModalAssetPicker } from "./components/ModalAssetPicker"
|
||||
@@ -22,73 +19,28 @@ import {
|
||||
createLipsyncJob,
|
||||
getLipsyncJob,
|
||||
submitRender,
|
||||
getRenderJob,
|
||||
generateSmartCover,
|
||||
} from "./api/aiAvatar"
|
||||
import {
|
||||
normalizeEmotion,
|
||||
buildTitleConfigPayload,
|
||||
buildCoverConfigPayload,
|
||||
} from "./utils/contract"
|
||||
|
||||
/** 面板折叠状态 */
|
||||
type PanelKey = "video" | "voice" | "script" | "lipsync" | "title" | "cover"
|
||||
type PanelKey = "video" | "voice" | "script" | "title" | "cover"
|
||||
|
||||
const AiAvatarPage: React.FC = () => {
|
||||
const state = useAiAvatar()
|
||||
const navigate = useNavigate()
|
||||
const [currentStep, setCurrentStep] = useState<1 | 2>(1)
|
||||
const [collapsed, setCollapsed] = useState<Record<PanelKey, boolean>>({
|
||||
video: false,
|
||||
voice: false,
|
||||
script: false,
|
||||
lipsync: false,
|
||||
title: false,
|
||||
cover: false,
|
||||
})
|
||||
|
||||
/* ── 对口型生成弹窗 ── */
|
||||
const [showLipsyncModal, setShowLipsyncModal] = useState(false)
|
||||
const [lipsyncStatus, setLipsyncStatus] = useState<"generating" | "completed" | "failed">(
|
||||
"generating",
|
||||
)
|
||||
const [lipsyncErrorMessage, setLipsyncErrorMessage] = useState("")
|
||||
/* ── 智能封面加载态 ── */
|
||||
const [smartCoverLoading, setSmartCoverLoading] = useState(false)
|
||||
/* ── 渲染进度弹窗 ── */
|
||||
const [showRenderModal, setShowRenderModal] = useState(false)
|
||||
const [renderStatus, setRenderStatus] = useState<"generating" | "completed" | "failed">(
|
||||
"generating",
|
||||
)
|
||||
const [renderProgress, setRenderProgress] = useState(0)
|
||||
const [renderErrorMessage, setRenderErrorMessage] = useState("")
|
||||
|
||||
/* ── 对口型轮询 ── */
|
||||
const lipsyncTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
/* ── 渲染进度轮询 ── */
|
||||
const renderTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
const togglePanel = useCallback((key: PanelKey) => {
|
||||
setCollapsed((prev) => ({ ...prev, [key]: !prev[key] }))
|
||||
}, [])
|
||||
|
||||
/* ── 步骤切换 ── */
|
||||
const handleNextStep = useCallback(() => {
|
||||
const missing: string[] = []
|
||||
if (!state.selectedVideo) missing.push("出镜视频")
|
||||
if (!state.selectedVoice) missing.push("配音")
|
||||
if (!state.scriptText.trim()) missing.push("文案")
|
||||
if (missing.length > 0) {
|
||||
message.warning(`请先完成${missing.join("、")}`)
|
||||
return
|
||||
}
|
||||
setCurrentStep(2)
|
||||
}, [state.selectedVideo, state.selectedVoice, state.scriptText])
|
||||
|
||||
const handlePrevStep = useCallback(() => {
|
||||
setCurrentStep(1)
|
||||
}, [])
|
||||
|
||||
/* ── 对口型 ── */
|
||||
const handleGenerateLipsync = useCallback(async () => {
|
||||
// ② 缺项明确提示(#1809):不再静默 return
|
||||
@@ -104,150 +56,72 @@ const AiAvatarPage: React.FC = () => {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// 显示生成弹窗
|
||||
setShowLipsyncModal(true)
|
||||
setLipsyncStatus("generating")
|
||||
setLipsyncErrorMessage("")
|
||||
|
||||
// ① 先按素材 id 拿 file_url(#1809 补充:对齐后端新参数 video_url)
|
||||
console.log("[对口型] 开始生成:", {
|
||||
videoId: video.id,
|
||||
voiceId: voice.voice_id,
|
||||
voiceType: voice.type,
|
||||
textLen: state.scriptText.length,
|
||||
})
|
||||
const asset = await getAssetById(video.id)
|
||||
console.log("[对口型] getAssetById 响应:", {
|
||||
id: asset?.id,
|
||||
file_url: asset?.file_url?.substring(0, 100),
|
||||
})
|
||||
const videoUrl = asset?.file_url
|
||||
if (!videoUrl) {
|
||||
console.error("[对口型] file_url 为空,asset:", asset)
|
||||
setShowLipsyncModal(false)
|
||||
message.error("获取出镜视频播放地址失败,请重新选择素材")
|
||||
return
|
||||
}
|
||||
// ② 模式A TTS直生:video_url + voice_id + script_text,语速/情绪英文枚举透传(#1822)
|
||||
const payload = {
|
||||
// ② voice_id(预设/克隆 UUID 均由后端内部调 TTS)+ script_text + video_url
|
||||
const job = await createLipsyncJob({
|
||||
voice_id: voice.voice_id,
|
||||
script_text: state.scriptText,
|
||||
video_url: videoUrl,
|
||||
speed: state.speed, // 语速 0.5~2.0
|
||||
emotion: normalizeEmotion(state.emotion), // natural/excited/calm/friendly
|
||||
}
|
||||
console.log("[对口型] createLipsyncJob 请求:", payload)
|
||||
const job = await createLipsyncJob(payload)
|
||||
console.log("[对口型] createLipsyncJob 响应:", { id: job.id, status: job.status })
|
||||
})
|
||||
state.setLipsyncJob(job)
|
||||
message.success("对口型任务已提交,生成中…")
|
||||
// 开始轮询
|
||||
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
|
||||
lipsyncTimerRef.current = setInterval(async () => {
|
||||
try {
|
||||
const updated = await getLipsyncJob(job.id)
|
||||
state.setLipsyncJob(updated)
|
||||
console.log("[对口型] 轮询状态:", {
|
||||
id: updated.id,
|
||||
status: updated.status,
|
||||
error: updated.error_message,
|
||||
})
|
||||
if (updated.status === "completed") {
|
||||
if (updated.status === "completed" || updated.status === "failed") {
|
||||
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
|
||||
setLipsyncStatus("completed")
|
||||
setTimeout(() => {
|
||||
setShowLipsyncModal(false)
|
||||
if (updated.status === "completed") {
|
||||
message.success("对口型视频生成完成")
|
||||
}, 1000)
|
||||
} else if (updated.status === "failed") {
|
||||
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
|
||||
setLipsyncStatus("failed")
|
||||
setLipsyncErrorMessage(updated.error_message || "对口型生成失败")
|
||||
} else {
|
||||
message.error(updated.error_message || "对口型生成失败")
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[对口型] 轮询错误:", err)
|
||||
} catch {
|
||||
// 忽略轮询错误(轮询期间不打扰用户)
|
||||
}
|
||||
}, 3000)
|
||||
} catch (err) {
|
||||
console.error("[对口型] 创建失败:", {
|
||||
status: (err as { response?: { status?: number } })?.response?.status,
|
||||
data: (err as { response?: { data?: unknown } })?.response?.data,
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
setShowLipsyncModal(false)
|
||||
// ② 接口失败弹错误提示,不只 console
|
||||
console.error("对口型任务创建失败:", err)
|
||||
message.error(err instanceof Error ? err.message : "对口型任务提交失败,请重试")
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state.selectedVideo, state.selectedVoice, state.scriptText, state.speed, state.emotion])
|
||||
|
||||
// 取消对口型生成
|
||||
const handleCancelLipsync = useCallback(() => {
|
||||
if (lipsyncTimerRef.current) {
|
||||
clearInterval(lipsyncTimerRef.current)
|
||||
lipsyncTimerRef.current = null
|
||||
}
|
||||
setShowLipsyncModal(false)
|
||||
setLipsyncStatus("generating")
|
||||
setLipsyncErrorMessage("")
|
||||
}, [])
|
||||
}, [state.selectedVideo, state.selectedVoice, state.scriptText])
|
||||
|
||||
// 清理轮询
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
|
||||
if (renderTimerRef.current) clearInterval(renderTimerRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
/* ── 生成视频(含实时进度轮询) ── */
|
||||
/* ── 生成视频 ── */
|
||||
const handleGenerate = useCallback(async () => {
|
||||
// ② 前置条件提示(#1809)
|
||||
if (!state.lipsyncJob || state.lipsyncJob.status !== "completed") {
|
||||
message.warning("请先生成对口型视频,待对口型完成后再提交渲染")
|
||||
return
|
||||
}
|
||||
state.setIsGenerating(true)
|
||||
try {
|
||||
const job = await submitRender({
|
||||
await submitRender({
|
||||
lipsync_job_id: state.lipsyncJob.id,
|
||||
script_id: state.script?.id,
|
||||
b_roll_segments: state.bRollSegments.map((seg) => ({
|
||||
script_segment_index: seg.script_segment_index,
|
||||
asset_url: seg.asset.file_url || "",
|
||||
mode: seg.mode,
|
||||
start_time: seg.start_time,
|
||||
end_time: seg.end_time,
|
||||
pip_position: seg.pip_position,
|
||||
pip_scale: seg.pip_scale,
|
||||
})) as never,
|
||||
title_config: buildTitleConfigPayload(state.titleConfig),
|
||||
cover_config: buildCoverConfigPayload(state.coverConfig, state.coverConfig.smart_cover_url),
|
||||
b_roll_segments: state.bRollSegments as never,
|
||||
title_config: state.titleConfig as unknown as Record<string, unknown>,
|
||||
cover_config: state.coverConfig as unknown as Record<string, unknown>,
|
||||
resolution: state.resolution,
|
||||
})
|
||||
|
||||
// 打开渲染进度弹窗,启动轮询
|
||||
setShowRenderModal(true)
|
||||
setRenderStatus("generating")
|
||||
setRenderProgress(job.progress ?? 0)
|
||||
setRenderErrorMessage("")
|
||||
|
||||
if (renderTimerRef.current) clearInterval(renderTimerRef.current)
|
||||
renderTimerRef.current = setInterval(async () => {
|
||||
try {
|
||||
const updated = await getRenderJob(job.id)
|
||||
setRenderProgress(updated.progress ?? 0)
|
||||
if (updated.status === "completed") {
|
||||
if (renderTimerRef.current) clearInterval(renderTimerRef.current)
|
||||
renderTimerRef.current = null
|
||||
setRenderStatus("completed")
|
||||
message.success("视频已生成并保存到成片库")
|
||||
} else if (updated.status === "failed") {
|
||||
if (renderTimerRef.current) clearInterval(renderTimerRef.current)
|
||||
renderTimerRef.current = null
|
||||
setRenderStatus("failed")
|
||||
setRenderErrorMessage(updated.error_message || "渲染失败,请重试")
|
||||
}
|
||||
} catch (pollErr) {
|
||||
console.error("[渲染] 轮询失败:", pollErr)
|
||||
}
|
||||
}, 3000)
|
||||
message.success("渲染任务已提交,可在视频管理中查看进度")
|
||||
} catch (err) {
|
||||
console.error("渲染任务提交失败:", err)
|
||||
message.error(err instanceof Error ? err.message : "渲染任务提交失败,请重试")
|
||||
@@ -255,50 +129,14 @@ const AiAvatarPage: React.FC = () => {
|
||||
state.setIsGenerating(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state.lipsyncJob, state.script, state.bRollSegments, state.titleConfig, state.coverConfig])
|
||||
|
||||
/* ── 关闭渲染进度弹窗 ── */
|
||||
const handleCancelRender = useCallback(() => {
|
||||
if (renderTimerRef.current) {
|
||||
clearInterval(renderTimerRef.current)
|
||||
renderTimerRef.current = null
|
||||
}
|
||||
setShowRenderModal(false)
|
||||
setRenderStatus("generating")
|
||||
setRenderProgress(0)
|
||||
setRenderErrorMessage("")
|
||||
}, [])
|
||||
|
||||
/* ── 智能封面:调后端 MediaKit 选帧接口(#1822) ── */
|
||||
const handleSmartCover = useCallback(async () => {
|
||||
// 基于对口型成片抽帧,必须先完成对口型
|
||||
const videoUrl = state.lipsyncJob?.output_video_url
|
||||
if (state.lipsyncJob?.status !== "completed" || !videoUrl) {
|
||||
message.warning("请先生成对口型视频,完成后再智能获取封面")
|
||||
return
|
||||
}
|
||||
setSmartCoverLoading(true)
|
||||
try {
|
||||
const res = await generateSmartCover(videoUrl, 5)
|
||||
if (res.cover_url) {
|
||||
state.setCoverConfig((prev) => ({
|
||||
...prev,
|
||||
mode: "auto_frame",
|
||||
smart_cover_url: res.cover_url,
|
||||
thumbnail_url: res.cover_url,
|
||||
}))
|
||||
message.success("智能封面已生成")
|
||||
} else {
|
||||
message.error(res.message || "智能封面生成失败,请稍后重试")
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("智能封面生成失败:", err)
|
||||
message.error(err instanceof Error ? err.message : "智能封面生成失败,请重试")
|
||||
} finally {
|
||||
setSmartCoverLoading(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [state.lipsyncJob])
|
||||
}, [
|
||||
state.lipsyncJob,
|
||||
state.script,
|
||||
state.bRollSegments,
|
||||
state.titleConfig,
|
||||
state.coverConfig,
|
||||
state.resolution,
|
||||
])
|
||||
|
||||
/* ── 配置汇总 ── */
|
||||
const summary = {
|
||||
@@ -316,147 +154,95 @@ const AiAvatarPage: React.FC = () => {
|
||||
<div className="aa-page-header">
|
||||
<h1>AI数字人</h1>
|
||||
</div>
|
||||
|
||||
{/* 步骤切换导航条 */}
|
||||
<div className="aa-step-nav">
|
||||
<span className={`aa-step-nav__item${currentStep === 1 ? " active" : ""}`}>
|
||||
1. 视频 / 配音 / 文案
|
||||
</span>
|
||||
<span className={`aa-step-nav__item${currentStep === 2 ? " active" : ""}`}>
|
||||
2. 对口型 / 标题 / 封面 / 生成
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="aa-page-body">
|
||||
{/* ════ 步骤 1:出镜视频 / 配音库 / 文案 ════ */}
|
||||
{currentStep === 1 && (
|
||||
<>
|
||||
{/* 面板1:出镜视频 */}
|
||||
<div className={`aa-panel aa-panel--s1${collapsed.video ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("video")}>
|
||||
<span className="aa-panel__title">出镜视频</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelVideoSelector
|
||||
selectedVideo={state.selectedVideo}
|
||||
onSelectVideo={() => state.setShowAssetPicker(true)}
|
||||
onRemoveVideo={state.removeVideo}
|
||||
titleConfig={state.titleConfig}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* 面板1:出镜视频 */}
|
||||
<div className={`aa-panel aa-panel--p1${collapsed.video ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("video")}>
|
||||
<span className="aa-panel__title">出镜视频</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelVideoSelector
|
||||
selectedVideo={state.selectedVideo}
|
||||
onSelectVideo={() => state.setShowAssetPicker(true)}
|
||||
onRemoveVideo={state.removeVideo}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 面板2:配音库 */}
|
||||
<div className={`aa-panel aa-panel--s1${collapsed.voice ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("voice")}>
|
||||
<span className="aa-panel__title">配音库</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelVoiceSelector
|
||||
voiceSource={state.voiceSource}
|
||||
onVoiceSourceChange={state.setVoiceSource}
|
||||
selectedVoice={state.selectedVoice}
|
||||
onSelectVoice={state.setSelectedVoice}
|
||||
emotion={state.emotion}
|
||||
onEmotionChange={state.setEmotion}
|
||||
speed={state.speed}
|
||||
onSpeedChange={state.setSpeed}
|
||||
language={state.language}
|
||||
onLanguageChange={state.setLanguage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* 面板2:配音库 */}
|
||||
<div className={`aa-panel aa-panel--p2${collapsed.voice ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("voice")}>
|
||||
<span className="aa-panel__title">配音库</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelVoiceSelector
|
||||
voiceSource={state.voiceSource}
|
||||
onVoiceSourceChange={state.setVoiceSource}
|
||||
selectedVoice={state.selectedVoice}
|
||||
onSelectVoice={state.setSelectedVoice}
|
||||
emotion={state.emotion}
|
||||
onEmotionChange={state.setEmotion}
|
||||
speed={state.speed}
|
||||
onSpeedChange={state.setSpeed}
|
||||
language={state.language}
|
||||
onLanguageChange={state.setLanguage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 面板3:文案 */}
|
||||
<div className={`aa-panel aa-panel--s1-wide${collapsed.script ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("script")}>
|
||||
<span className="aa-panel__title">文案 & 对口型</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelScript
|
||||
scriptText={state.scriptText}
|
||||
onScriptTextChange={state.setScriptText}
|
||||
onOpenScriptModal={() => state.setShowScriptModal(true)}
|
||||
/>
|
||||
<div className="aa-step-btn-row">
|
||||
<button type="button" className="aa-btn aa-btn--primary" onClick={handleNextStep}>
|
||||
下一步 →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{/* 面板3:文案 & 对口型 */}
|
||||
<div className={`aa-panel aa-panel--p3${collapsed.script ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("script")}>
|
||||
<span className="aa-panel__title">文案 & 对口型</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelScriptAndLipsync
|
||||
scriptText={state.scriptText}
|
||||
onScriptTextChange={state.setScriptText}
|
||||
onOpenScriptModal={() => state.setShowScriptModal(true)}
|
||||
lipsyncJob={state.lipsyncJob}
|
||||
onGenerateLipsync={handleGenerateLipsync}
|
||||
bRollSegments={state.bRollSegments}
|
||||
onOpenBRollModal={() => state.setShowBRollModal(true)}
|
||||
onRemoveBRoll={state.removeBRollSegment}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ════ 步骤 2:对口型预览(含插入画面)/ 标题配置 / 封面&生成 ════ */}
|
||||
{currentStep === 2 && (
|
||||
<>
|
||||
{/* 面板:对口型预览 + 插入画面 */}
|
||||
<div className={`aa-panel aa-panel--s2-wide${collapsed.lipsync ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("lipsync")}>
|
||||
<span className="aa-panel__title">对口型预览</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelLipsyncPreview
|
||||
lipsyncJob={state.lipsyncJob}
|
||||
onGenerateLipsync={handleGenerateLipsync}
|
||||
bRollSegments={state.bRollSegments}
|
||||
onOpenBRollModal={() => state.setShowBRollModal(true)}
|
||||
onRemoveBRoll={state.removeBRollSegment}
|
||||
titleConfig={state.titleConfig}
|
||||
onTitlePositionChange={(pos) => state.updateTitleConfig(pos)}
|
||||
/>
|
||||
<div className="aa-step-btn-row">
|
||||
<button type="button" className="aa-btn" onClick={handlePrevStep}>
|
||||
← 上一步
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 面板4:标题配置 */}
|
||||
<div className={`aa-panel aa-panel--p4${collapsed.title ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("title")}>
|
||||
<span className="aa-panel__title">标题配置</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelTitleConfig titleConfig={state.titleConfig} onUpdate={state.updateTitleConfig} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 面板4:标题配置 */}
|
||||
<div className={`aa-panel aa-panel--s2${collapsed.title ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("title")}>
|
||||
<span className="aa-panel__title">标题配置</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelTitleConfig
|
||||
titleConfig={state.titleConfig}
|
||||
onUpdate={state.updateTitleConfig}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 面板5:封面 & 生成 */}
|
||||
<div className={`aa-panel aa-panel--s2${collapsed.cover ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("cover")}>
|
||||
<span className="aa-panel__title">封面 & 生成</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelCoverAndGenerate
|
||||
coverConfig={state.coverConfig}
|
||||
onCoverConfigChange={(partial) =>
|
||||
state.setCoverConfig((prev) => ({ ...prev, ...partial }))
|
||||
}
|
||||
onSmartCover={handleSmartCover}
|
||||
smartCoverLoading={smartCoverLoading}
|
||||
canSmartCover={state.lipsyncJob?.status === "completed"}
|
||||
resolution={state.resolution}
|
||||
onResolutionChange={state.setResolution}
|
||||
isGenerating={state.isGenerating}
|
||||
onGenerate={handleGenerate}
|
||||
summary={summary}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{/* 面板5:封面 & 生成 */}
|
||||
<div className={`aa-panel aa-panel--p5${collapsed.cover ? " collapsed" : ""}`}>
|
||||
<div className="aa-panel__header" onClick={() => togglePanel("cover")}>
|
||||
<span className="aa-panel__title">封面 & 生成</span>
|
||||
<span className="aa-panel__toggle">▼</span>
|
||||
</div>
|
||||
<div className="aa-panel__body">
|
||||
<PanelCoverAndGenerate
|
||||
coverConfig={state.coverConfig}
|
||||
onCoverConfigChange={(partial) =>
|
||||
state.setCoverConfig((prev) => ({ ...prev, ...partial }))
|
||||
}
|
||||
resolution={state.resolution}
|
||||
onResolutionChange={state.setResolution}
|
||||
isGenerating={state.isGenerating}
|
||||
onGenerate={handleGenerate}
|
||||
summary={summary}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 素材库弹窗 */}
|
||||
@@ -490,180 +276,6 @@ const AiAvatarPage: React.FC = () => {
|
||||
onRemove={state.removeBRollSegment}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 对口型生成弹窗 */}
|
||||
{showLipsyncModal && (
|
||||
<div className="aa-modal-overlay">
|
||||
<div className="aa-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="aa-modal__header">
|
||||
<span className="aa-modal__title">对口型生成</span>
|
||||
<button className="aa-modal__close" onClick={handleCancelLipsync}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className="aa-modal__body"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
padding: "40px 20px",
|
||||
}}
|
||||
>
|
||||
{lipsyncStatus === "generating" && (
|
||||
<>
|
||||
<div className="aa-lipsync-spinner" />
|
||||
<div style={{ marginTop: 20, fontSize: 15, color: "#1a1a2e" }}>
|
||||
对口型视频生成中…
|
||||
</div>
|
||||
<div style={{ marginTop: 8, fontSize: 13, color: "#8c8ca1" }}>
|
||||
请勿关闭页面,完成后将自动提示
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{lipsyncStatus === "completed" && (
|
||||
<>
|
||||
<div style={{ fontSize: 48 }}>✅</div>
|
||||
<div style={{ marginTop: 16, fontSize: 15, color: "#1a1a2e" }}>
|
||||
对口型视频生成完成
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{lipsyncStatus === "failed" && (
|
||||
<>
|
||||
<div style={{ fontSize: 48 }}>❌</div>
|
||||
<div style={{ marginTop: 16, fontSize: 15, color: "#1a1a2e" }}>
|
||||
对口型生成失败
|
||||
</div>
|
||||
{lipsyncErrorMessage && (
|
||||
<div style={{ marginTop: 8, fontSize: 13, color: "#ff4d4f" }}>
|
||||
{lipsyncErrorMessage}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="aa-modal__footer">
|
||||
{lipsyncStatus === "generating" && (
|
||||
<button className="aa-btn aa-btn--danger" onClick={handleCancelLipsync}>
|
||||
取消生成
|
||||
</button>
|
||||
)}
|
||||
{lipsyncStatus !== "generating" && (
|
||||
<button className="aa-btn" onClick={handleCancelLipsync}>
|
||||
关闭
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 渲染进度弹窗 */}
|
||||
{showRenderModal && (
|
||||
<div className="aa-modal-overlay">
|
||||
<div className="aa-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="aa-modal__header">
|
||||
<span className="aa-modal__title">视频渲染</span>
|
||||
<button className="aa-modal__close" onClick={handleCancelRender}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className="aa-modal__body"
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
padding: "40px 20px",
|
||||
}}
|
||||
>
|
||||
{renderStatus === "generating" && (
|
||||
<>
|
||||
<div className="aa-lipsync-spinner" />
|
||||
<div style={{ marginTop: 20, fontSize: 15, color: "#1a1a2e" }}>
|
||||
正在生成视频,请稍后
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
fontSize: 32,
|
||||
fontWeight: 700,
|
||||
color: "#1890ff",
|
||||
}}
|
||||
>
|
||||
{renderProgress}%
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 12,
|
||||
width: "80%",
|
||||
height: 8,
|
||||
backgroundColor: "#f0f0f0",
|
||||
borderRadius: 4,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: `${renderProgress}%`,
|
||||
height: "100%",
|
||||
backgroundColor: "#1890ff",
|
||||
borderRadius: 4,
|
||||
transition: "width 0.5s ease",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginTop: 12, fontSize: 13, color: "#8c8ca1" }}>
|
||||
请勿关闭页面,完成后将自动提示
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{renderStatus === "completed" && (
|
||||
<>
|
||||
<div style={{ fontSize: 48 }}>✅</div>
|
||||
<div style={{ marginTop: 16, fontSize: 15, color: "#1a1a2e" }}>
|
||||
视频已保存到成片库
|
||||
</div>
|
||||
<button
|
||||
className="aa-btn"
|
||||
style={{ marginTop: 16 }}
|
||||
onClick={() => {
|
||||
setShowRenderModal(false)
|
||||
navigate("/app/products")
|
||||
}}
|
||||
>
|
||||
📁 查看成片
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{renderStatus === "failed" && (
|
||||
<>
|
||||
<div style={{ fontSize: 48 }}>❌</div>
|
||||
<div style={{ marginTop: 16, fontSize: 15, color: "#1a1a2e" }}>视频渲染失败</div>
|
||||
{renderErrorMessage && (
|
||||
<div style={{ marginTop: 8, fontSize: 13, color: "#ff4d4f" }}>
|
||||
{renderErrorMessage}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="aa-modal__footer">
|
||||
{renderStatus === "generating" && (
|
||||
<button className="aa-btn aa-btn--danger" onClick={handleCancelRender}>
|
||||
关闭窗口
|
||||
</button>
|
||||
)}
|
||||
{renderStatus !== "generating" && (
|
||||
<button className="aa-btn" onClick={handleCancelRender}>
|
||||
关闭
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* AI数字人 — API 封装(#1822 契约对齐)
|
||||
* AI数字人 — API 封装
|
||||
*/
|
||||
import apiClient from "@/api/client"
|
||||
import type { Script, LipsyncJob, RenderJob, BRollSegment } from "../types"
|
||||
@@ -28,26 +28,17 @@ export const deleteScript = async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/scripts/${id}`)
|
||||
}
|
||||
|
||||
/* ── 素材单查(拿到 file_url 作为对口型的 video_url) ── */
|
||||
/* ── 素材单查(用于拿到 file_url 传给对口型等新接口) ── */
|
||||
export const getAssetById = async (id: string): Promise<{ file_url?: string; id: string }> => {
|
||||
const response = await apiClient.get<{ file_url?: string; id: string }>(`/assets/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
/* ── 对口型(模式A:TTS 直生,后端内部合成音频;不要先调 TTS 拿 audio_url) ── */
|
||||
/* ── 对口型 ── */
|
||||
export const createLipsyncJob = async (data: {
|
||||
/** 人物视频 URL(MP4);由素材 id 经 getAssetById 拿 file_url,禁止传 video_asset_id */
|
||||
video_url: string
|
||||
/** 音色 ID(预置音色 或 克隆音色 profile UUID,后端会解析) */
|
||||
voice_id: string
|
||||
/** 要合成的文案(手动输入或文案库内容) */
|
||||
script_text: string
|
||||
/** 语速 0.5~2.0,默认 1.0 */
|
||||
speed?: number
|
||||
/** 情绪英文枚举:natural/excited/calm/friendly */
|
||||
emotion?: string
|
||||
enable_video_loop?: boolean
|
||||
project_id?: string
|
||||
video_url: string
|
||||
}): Promise<LipsyncJob> => {
|
||||
const response = await apiClient.post<LipsyncJob>("/lipsync/jobs", data)
|
||||
return response.data
|
||||
@@ -58,19 +49,6 @@ export const getLipsyncJob = async (id: string): Promise<LipsyncJob> => {
|
||||
return response.data
|
||||
}
|
||||
|
||||
/* ── 智能封面(MediaKit 抽帧 + 质量评分选最佳帧,独立于渲染任务) ── */
|
||||
export const generateSmartCover = async (
|
||||
video_url: string,
|
||||
max_frames = 5,
|
||||
): Promise<{ cover_url: string; status: string; message: string }> => {
|
||||
const response = await apiClient.post<{ cover_url: string; status: string; message: string }>(
|
||||
"/ai-avatar/render/smart-cover",
|
||||
{ video_url, max_frames },
|
||||
{ timeout: 60000 },
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
|
||||
/* ── 渲染 ── */
|
||||
export const submitRender = async (data: {
|
||||
lipsync_job_id: string
|
||||
@@ -79,6 +57,7 @@ export const submitRender = async (data: {
|
||||
title_config?: Record<string, unknown>
|
||||
cover_config?: Record<string, unknown>
|
||||
project_id?: string
|
||||
resolution?: string
|
||||
}): Promise<RenderJob> => {
|
||||
const response = await apiClient.post<RenderJob>("/ai-avatar/render", data)
|
||||
return response.data
|
||||
|
||||
@@ -17,10 +17,6 @@ interface PanelCoverAndGenerateProps {
|
||||
onResolutionChange: (r: string) => void
|
||||
isGenerating: boolean
|
||||
onGenerate: () => void
|
||||
/** 智能获取封面(MediaKit 选帧) */
|
||||
onSmartCover: () => void
|
||||
smartCoverLoading: boolean
|
||||
canSmartCover: boolean
|
||||
/** 配置汇总信息 */
|
||||
summary: {
|
||||
videoName: string | null
|
||||
@@ -54,9 +50,6 @@ const PanelCoverAndGenerate: React.FC<PanelCoverAndGenerateProps> = ({
|
||||
onResolutionChange,
|
||||
isGenerating,
|
||||
onGenerate,
|
||||
onSmartCover,
|
||||
smartCoverLoading,
|
||||
canSmartCover,
|
||||
summary,
|
||||
}) => {
|
||||
const uploadInputRef = useRef<HTMLInputElement>(null)
|
||||
@@ -76,10 +69,9 @@ const PanelCoverAndGenerate: React.FC<PanelCoverAndGenerateProps> = ({
|
||||
e.target.value = ""
|
||||
}
|
||||
|
||||
/** 智能获取封面(调后端 MediaKit 抽帧评分选最佳帧,#1822) */
|
||||
const handleSmartCover = () => {
|
||||
/** 从视频截取(使用配置的帧时间,默认首帧) */
|
||||
const handleCaptureFromVideo = () => {
|
||||
onCoverConfigChange({ mode: "auto_frame" })
|
||||
onSmartCover()
|
||||
}
|
||||
|
||||
const lipsync = summary.lipsyncStatus ? LIPSYNC_STATUS_LABEL[summary.lipsyncStatus] : null
|
||||
@@ -101,11 +93,9 @@ const PanelCoverAndGenerate: React.FC<PanelCoverAndGenerateProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
className={`aa-btn aa-btn--ghost${coverConfig.mode === "auto_frame" ? " active" : ""}`}
|
||||
onClick={handleSmartCover}
|
||||
disabled={smartCoverLoading || !canSmartCover}
|
||||
title={canSmartCover ? "基于对口型成片智能选帧" : "请先完成对口型生成"}
|
||||
onClick={handleCaptureFromVideo}
|
||||
>
|
||||
{smartCoverLoading ? "⏳ 智能选帧中…" : "🎬 智能获取封面"}
|
||||
🎬 从视频截取
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* AI数字人 — 文案面板(步骤1用)
|
||||
* 文案库选择 / 手动输入 + 字数统计
|
||||
*/
|
||||
import { useState } from "react"
|
||||
|
||||
interface PanelScriptProps {
|
||||
scriptText: string
|
||||
onScriptTextChange: (text: string) => void
|
||||
onOpenScriptModal: () => void
|
||||
}
|
||||
|
||||
type ScriptTab = "library" | "manual"
|
||||
|
||||
export function PanelScript({
|
||||
scriptText,
|
||||
onScriptTextChange,
|
||||
onOpenScriptModal,
|
||||
}: PanelScriptProps) {
|
||||
const [scriptTab, setScriptTab] = useState<ScriptTab>("library")
|
||||
|
||||
return (
|
||||
<div className="aa-script-lipsync">
|
||||
{/* ── Tab 切换 ── */}
|
||||
<div className="aa-script-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`aa-script-tab${scriptTab === "library" ? " active" : ""}`}
|
||||
onClick={() => setScriptTab("library")}
|
||||
>
|
||||
从文案库选择
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`aa-script-tab${scriptTab === "manual" ? " active" : ""}`}
|
||||
onClick={() => setScriptTab("manual")}
|
||||
>
|
||||
手动输入
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{scriptTab === "library" && (
|
||||
<button
|
||||
type="button"
|
||||
className="aa-btn aa-btn--ghost aa-btn--full"
|
||||
style={{ marginBottom: 8 }}
|
||||
onClick={onOpenScriptModal}
|
||||
>
|
||||
📚 从文案库选择文案
|
||||
</button>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
className="aa-textarea"
|
||||
value={scriptText}
|
||||
readOnly={scriptTab === "library"}
|
||||
placeholder={
|
||||
scriptTab === "library" ? "点击上方按钮,从文案库选择文案…" : "请输入数字人口播文案…"
|
||||
}
|
||||
onChange={(e) => onScriptTextChange(e.target.value)}
|
||||
/>
|
||||
<div className="aa-char-count">{scriptText.length} 字</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PanelScript
|
||||
Executable → Regular
+63
-109
@@ -1,23 +1,23 @@
|
||||
/**
|
||||
* AI数字人 — 对口型预览面板(步骤2用)
|
||||
* B-roll 画面插入 + 对口型视频预览 + 生成/重新生成按钮
|
||||
* v3.1: 预览容器按 1/2 缩放、标题实时叠加预览
|
||||
* AI数字人 — 文案 & 对口型面板(面板4)
|
||||
* 上半区:文案(文案库选择 / 手动输入);下半区:对口型视频预览(9:16)+ B-roll 画面
|
||||
*/
|
||||
import React, { useRef } from "react"
|
||||
import type { LipsyncJob, BRollSegment, AiAvatarTitleConfig } from "../types"
|
||||
import { useState } from "react"
|
||||
import type { LipsyncJob, BRollSegment } from "../types"
|
||||
|
||||
interface PanelLipsyncPreviewProps {
|
||||
interface PanelScriptAndLipsyncProps {
|
||||
scriptText: string
|
||||
onScriptTextChange: (text: string) => void
|
||||
onOpenScriptModal: () => void
|
||||
lipsyncJob: LipsyncJob | null
|
||||
onGenerateLipsync: () => void
|
||||
bRollSegments: BRollSegment[]
|
||||
onOpenBRollModal: () => void
|
||||
onRemoveBRoll: (id: string) => void
|
||||
/** 标题配置(实时叠加预览用) */
|
||||
titleConfig?: AiAvatarTitleConfig
|
||||
/** 标题位置变更回调(拖拽结束时调用) */
|
||||
onTitlePositionChange?: (pos: { pos_x: number; pos_y: number }) => void
|
||||
}
|
||||
|
||||
type ScriptTab = "library" | "manual"
|
||||
|
||||
const BROLL_MODE_LABEL: Record<BRollSegment["mode"], string> = {
|
||||
fullscreen: "全屏",
|
||||
pip: "画中画",
|
||||
@@ -29,18 +29,19 @@ function formatTime(seconds: number): string {
|
||||
return `${m}:${s.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
export function PanelLipsyncPreview({
|
||||
export function PanelScriptAndLipsync({
|
||||
scriptText,
|
||||
onScriptTextChange,
|
||||
onOpenScriptModal,
|
||||
lipsyncJob,
|
||||
onGenerateLipsync,
|
||||
bRollSegments,
|
||||
onOpenBRollModal,
|
||||
onRemoveBRoll,
|
||||
titleConfig,
|
||||
onTitlePositionChange,
|
||||
}: PanelLipsyncPreviewProps) {
|
||||
const titleDragRef = useRef<HTMLDivElement>(null)
|
||||
const draggingTitleRef = useRef(false)
|
||||
const previewContainerRef = useRef<HTMLDivElement>(null)
|
||||
}: PanelScriptAndLipsyncProps) {
|
||||
const [scriptTab, setScriptTab] = useState<ScriptTab>("library")
|
||||
|
||||
/* 对口型状态判断 */
|
||||
const isGenerating = lipsyncJob?.status === "pending" || lipsyncJob?.status === "processing"
|
||||
const isDone = lipsyncJob?.status === "completed"
|
||||
const isFailed = lipsyncJob?.status === "failed"
|
||||
@@ -52,66 +53,48 @@ export function PanelLipsyncPreview({
|
||||
? "排队中…"
|
||||
: "对口型生成中…"
|
||||
|
||||
/** 标题叠加样式 */
|
||||
const titleOverlayStyle: React.CSSProperties | null = titleConfig?.title
|
||||
? {
|
||||
position: "absolute",
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
color: titleConfig.color || "#ffffff",
|
||||
fontFamily: titleConfig.font || "思源黑体",
|
||||
fontSize: `${(titleConfig.size || 36) * 0.55}px`, // 预览等比缩
|
||||
fontWeight: titleConfig.bold ? 700 : 400,
|
||||
fontStyle: titleConfig.italic ? "italic" : "normal",
|
||||
textAlign: "center",
|
||||
width: "90%",
|
||||
padding: "4px 8px",
|
||||
textShadow: titleConfig.shadow ? "0 2px 4px rgba(0,0,0,0.8)" : undefined,
|
||||
WebkitTextStroke: titleConfig.stroke ? "1.5px #000" : undefined,
|
||||
...(titleConfig.position === "top"
|
||||
? { top: 8 }
|
||||
: titleConfig.position === "bottom"
|
||||
? { bottom: 8 }
|
||||
: { top: "50%", transform: "translateX(-50%) translateY(-50%)" }),
|
||||
}
|
||||
: null
|
||||
|
||||
const handleTitlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!onTitlePositionChange || !previewContainerRef.current) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
;(e.target as Element).setPointerCapture(e.pointerId)
|
||||
draggingTitleRef.current = true
|
||||
;(e.currentTarget as HTMLDivElement).style.cursor = "grabbing"
|
||||
}
|
||||
const handleTitlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!draggingTitleRef.current || !previewContainerRef.current) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (titleDragRef.current) {
|
||||
const rect = previewContainerRef.current.getBoundingClientRect()
|
||||
const relX = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
|
||||
const relY = Math.max(0, Math.min(rect.height, e.clientY - rect.top))
|
||||
const xpct = (relX / rect.width) * 100
|
||||
const ypct = (relY / rect.height) * 100
|
||||
titleDragRef.current.style.left = `${xpct}%`
|
||||
titleDragRef.current.style.top = `${ypct}%`
|
||||
}
|
||||
}
|
||||
const handleTitlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!draggingTitleRef.current) return
|
||||
draggingTitleRef.current = false
|
||||
if (onTitlePositionChange && previewContainerRef.current) {
|
||||
const rect = previewContainerRef.current.getBoundingClientRect()
|
||||
const relX = Math.max(0, Math.min(rect.width, e.clientX - rect.left))
|
||||
const relY = Math.max(0, Math.min(rect.height, e.clientY - rect.top))
|
||||
onTitlePositionChange({ pos_x: relX, pos_y: relY })
|
||||
}
|
||||
;(e.currentTarget as HTMLDivElement).style.cursor = "grab"
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="aa-script-lipsync">
|
||||
{/* ── 上半区:文案 ── */}
|
||||
<div className="aa-script-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`aa-script-tab${scriptTab === "library" ? " active" : ""}`}
|
||||
onClick={() => setScriptTab("library")}
|
||||
>
|
||||
从文案库选择
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`aa-script-tab${scriptTab === "manual" ? " active" : ""}`}
|
||||
onClick={() => setScriptTab("manual")}
|
||||
>
|
||||
手动输入
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{scriptTab === "library" && (
|
||||
<button
|
||||
type="button"
|
||||
className="aa-btn aa-btn--ghost aa-btn--full"
|
||||
style={{ marginBottom: 8 }}
|
||||
onClick={onOpenScriptModal}
|
||||
>
|
||||
📚 从文案库选择文案
|
||||
</button>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
className="aa-textarea"
|
||||
value={scriptText}
|
||||
readOnly={scriptTab === "library"}
|
||||
placeholder={
|
||||
scriptTab === "library" ? "点击上方按钮,从文案库选择文案…" : "请输入数字人口播文案…"
|
||||
}
|
||||
onChange={(e) => onScriptTextChange(e.target.value)}
|
||||
/>
|
||||
<div className="aa-char-count">{scriptText.length} 字</div>
|
||||
|
||||
{/* ── B-roll 画面 ── */}
|
||||
<div className="aa-lipsync-section">
|
||||
<div className="aa-lipsync-section__title">
|
||||
@@ -174,36 +157,13 @@ export function PanelLipsyncPreview({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── 对口型预览(v3.1: 缩放1/2 + 标题叠加) ─ */}
|
||||
{/* ── 下半区:对口型预览(竖屏 9:16) ── */}
|
||||
<div className="aa-lipsync-section">
|
||||
<div className="aa-lipsync-section__title">对口型预览</div>
|
||||
|
||||
<div className="aa-lipsync-preview" ref={previewContainerRef}>
|
||||
<div className="aa-lipsync-preview">
|
||||
{isDone && lipsyncJob?.output_video_url ? (
|
||||
<div style={{ position: "relative", width: "100%", height: "100%" }}>
|
||||
<video src={lipsyncJob.output_video_url} controls />
|
||||
{titleOverlayStyle && (
|
||||
<div
|
||||
ref={titleDragRef}
|
||||
style={{
|
||||
...titleOverlayStyle,
|
||||
cursor: onTitlePositionChange ? "grab" : "default",
|
||||
pointerEvents: onTitlePositionChange ? "auto" : "none",
|
||||
}}
|
||||
onPointerDown={handleTitlePointerDown}
|
||||
onPointerMove={handleTitlePointerMove}
|
||||
onPointerUp={handleTitlePointerUp}
|
||||
onPointerCancel={handleTitlePointerUp}
|
||||
>
|
||||
{titleConfig!.title.split(/[//]/).map((part, i) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <br />}
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<video src={lipsyncJob.output_video_url} controls />
|
||||
) : isGenerating ? (
|
||||
<div style={{ width: "80%", textAlign: "center", color: "#fff" }}>
|
||||
<div style={{ fontSize: 13, marginBottom: 8 }}>
|
||||
@@ -223,13 +183,7 @@ export function PanelLipsyncPreview({
|
||||
<div style={{ fontSize: 28, marginBottom: 8 }}>❌</div>
|
||||
<div>对口型生成失败</div>
|
||||
{lipsyncJob?.error_message && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
marginTop: 4,
|
||||
color: "#fca5a5",
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 11, marginTop: 4, color: "#fca5a5" }}>
|
||||
{lipsyncJob.error_message}
|
||||
</div>
|
||||
)}
|
||||
@@ -265,4 +219,4 @@ export function PanelLipsyncPreview({
|
||||
)
|
||||
}
|
||||
|
||||
export default PanelLipsyncPreview
|
||||
export default PanelScriptAndLipsync
|
||||
@@ -7,17 +7,16 @@
|
||||
* - AiAvatarTitleConfig ↔ TitleSettings 的双向适配
|
||||
* - 自动生成字幕开关
|
||||
*/
|
||||
import React, { useMemo, useState, useEffect } from "react"
|
||||
import { Input } from "antd"
|
||||
import React, { useMemo, useState } from "react"
|
||||
import TitleStylePanel from "@/pages/generate/components/title/TitleStylePanel"
|
||||
import TitleLibraryAutoComplete from "@/pages/generate/components/title/TitleLibraryAutoComplete"
|
||||
import type { TitleOption } from "@/pages/generate/components/title/TitleLibraryAutoComplete"
|
||||
import type { TitleSettings } from "@/pages/generate/types"
|
||||
import { POSITION_OPTIONS, FONT_OPTIONS, TITLE_PRESETS } from "@/pages/generate/constants"
|
||||
import {
|
||||
POSITION_OPTIONS,
|
||||
FONT_OPTIONS,
|
||||
TITLE_PRESETS,
|
||||
getFontFamily,
|
||||
} from "@/pages/generate/constants"
|
||||
import type { AiAvatarTitleConfig } from "../types"
|
||||
import { getTitles } from "@/api/titles"
|
||||
|
||||
const { TextArea } = Input
|
||||
|
||||
interface PanelTitleConfigProps {
|
||||
titleConfig: AiAvatarTitleConfig
|
||||
@@ -28,14 +27,6 @@ const PanelTitleConfig: React.FC<PanelTitleConfigProps> = ({ titleConfig, onUpda
|
||||
/** TitleStylePanel 内部高亮的预设 key(面板本地状态) */
|
||||
const [activePreset, setActivePreset] = useState<string | null>(null)
|
||||
|
||||
/** 标题库选项(复用智能剪辑的标题库) */
|
||||
const [titleOptions, setTitleOptions] = useState<TitleOption[]>([])
|
||||
useEffect(() => {
|
||||
getTitles()
|
||||
.then((items) => setTitleOptions(items.map((t) => ({ label: t.content, value: t.content }))))
|
||||
.catch(() => setTitleOptions([]))
|
||||
}, [])
|
||||
|
||||
/** AiAvatarTitleConfig → TitleSettings(补齐 aiAutoSelect / 自由坐标字段) */
|
||||
const titleSettings: TitleSettings = useMemo(
|
||||
() => ({
|
||||
@@ -71,32 +62,37 @@ const PanelTitleConfig: React.FC<PanelTitleConfigProps> = ({ titleConfig, onUpda
|
||||
|
||||
return (
|
||||
<div className="aa-title-config">
|
||||
{/* 主标题输入 — TextArea 多行 + 标题库选择 */}
|
||||
{/* 主标题输入 */}
|
||||
<div className="aa-form-field">
|
||||
<label className="aa-label">主标题</label>
|
||||
<TextArea
|
||||
className="aa-title-input"
|
||||
placeholder="输入视频标题(支持 / 分行)"
|
||||
<input
|
||||
className="aa-input aa-title-input"
|
||||
type="text"
|
||||
placeholder="输入视频标题(留空则不显示标题)"
|
||||
value={titleConfig.title}
|
||||
autoSize={{ minRows: 2, maxRows: 4 }}
|
||||
maxLength={200}
|
||||
maxLength={30}
|
||||
onChange={(e) => onUpdate({ title: e.target.value })}
|
||||
style={{ fontSize: 15 }}
|
||||
/>
|
||||
<div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<span style={{ fontSize: 12, color: "#8c8ca1", whiteSpace: "nowrap" }}>📚 标题库</span>
|
||||
<TitleLibraryAutoComplete
|
||||
key={titleConfig.title}
|
||||
placeholder="选择标题填入上方"
|
||||
value=""
|
||||
onChange={(val) => {
|
||||
if (val) onUpdate({ title: val })
|
||||
{titleConfig.title && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 13,
|
||||
padding: "6px 8px",
|
||||
background: "#f8f8fc",
|
||||
borderRadius: 6,
|
||||
fontFamily: getFontFamily(titleConfig.font),
|
||||
fontWeight: titleConfig.bold ? 700 : 400,
|
||||
fontStyle: titleConfig.italic ? "italic" : "normal",
|
||||
color: titleConfig.color,
|
||||
textShadow: titleConfig.shadow ? "1px 1px 3px rgba(0,0,0,0.6)" : undefined,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
options={titleOptions}
|
||||
maxLength={200}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</div>
|
||||
>
|
||||
{titleConfig.title}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 标题样式:直接复用智能剪辑 TitleStylePanel(位置/字体/字号/样式/预设) */}
|
||||
|
||||
@@ -4,15 +4,12 @@
|
||||
* - 已选视频:竖屏 9:16 预览播放器 + 视频信息卡片 + 移除按钮
|
||||
*/
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
import type { AiAvatarTitleConfig } from "../types"
|
||||
import { getFontFamily } from "@/pages/generate/constants"
|
||||
|
||||
export interface PanelVideoSelectorProps {
|
||||
selectedVideo: AssetItem | null
|
||||
/** 触发打开素材库弹窗 */
|
||||
onSelectVideo: () => void
|
||||
onRemoveVideo: () => void
|
||||
titleConfig?: AiAvatarTitleConfig
|
||||
}
|
||||
|
||||
/** 格式化时长(秒 → mm:ss) */
|
||||
@@ -27,7 +24,6 @@ export function PanelVideoSelector({
|
||||
selectedVideo,
|
||||
onSelectVideo,
|
||||
onRemoveVideo,
|
||||
titleConfig,
|
||||
}: PanelVideoSelectorProps) {
|
||||
/* 未选视频:虚线上传区,点击打开素材库弹窗 */
|
||||
if (!selectedVideo) {
|
||||
@@ -57,42 +53,13 @@ export function PanelVideoSelector({
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 竖屏 9:16 视频预览播放器 + 标题实时预览 */}
|
||||
<div className="aa-video-preview" style={{ position: "relative" }}>
|
||||
{/* 竖屏 9:16 视频预览播放器 */}
|
||||
<div className="aa-video-preview">
|
||||
{fileUrl ? (
|
||||
<video src={fileUrl} poster={selectedVideo.thumbnail_url} controls playsInline />
|
||||
) : (
|
||||
<div className="aa-video-preview__placeholder">视频暂不可预览</div>
|
||||
)}
|
||||
{titleConfig?.title && (
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
...(titleConfig.position === "top"
|
||||
? { top: "10%" }
|
||||
: titleConfig.position === "bottom"
|
||||
? { bottom: "10%" }
|
||||
: { top: "50%", transform: "translate(-50%, -50%)" }),
|
||||
fontSize: Math.max(titleConfig.size, 32),
|
||||
fontFamily: getFontFamily(titleConfig.font),
|
||||
color: titleConfig.color,
|
||||
fontWeight: titleConfig.bold ? 700 : 400,
|
||||
fontStyle: titleConfig.italic ? "italic" : "normal",
|
||||
textShadow: "0 2px 4px rgba(0,0,0,0.5)",
|
||||
WebkitTextStroke: "2px #000",
|
||||
pointerEvents: "none",
|
||||
zIndex: 10,
|
||||
maxWidth: "90%",
|
||||
textAlign: "center",
|
||||
whiteSpace: "pre-wrap",
|
||||
lineHeight: 1.3,
|
||||
}}
|
||||
>
|
||||
{titleConfig.title}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 视频信息卡片:文件名 / 时长 / 分辨率 */}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useEffect, useRef, useState } from "react"
|
||||
import { message } from "antd"
|
||||
import { fetchVoices } from "@/api/voices/voices"
|
||||
import { previewTts } from "@/api/tts"
|
||||
import { normalizeEmotion } from "../utils/contract"
|
||||
import type { UnifiedVoiceItem } from "@/api/voices/types"
|
||||
import {
|
||||
type VoiceSource,
|
||||
@@ -93,14 +92,11 @@ export function PanelVoiceSelector({
|
||||
|
||||
/** 用指定 URL 真实播放(抽取公共) */
|
||||
const playAudioUrl = (voiceId: string, url: string) => {
|
||||
// 临时兼容:后端 /tts/preview 返回 HTTP URL,staging 是 HTTPS,Mixed Content 会阻止加载
|
||||
// OSS 同时支持 HTTP/HTTPS,直接替换协议即可
|
||||
const safeUrl = url.startsWith("http://") ? url.replace("http://", "https://") : url
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause()
|
||||
audioRef.current = null
|
||||
}
|
||||
const audio = new Audio(safeUrl)
|
||||
const audio = new Audio(url)
|
||||
audioRef.current = audio
|
||||
setPreviewingId(voiceId)
|
||||
audio.onended = () => {
|
||||
@@ -151,8 +147,7 @@ export function PanelVoiceSelector({
|
||||
const res = await previewTts({
|
||||
text: VOICE_PREVIEW_TEXT,
|
||||
voice_id: targetId,
|
||||
speed: speed, // 透传用户选择的语速(#1822)
|
||||
emotion: normalizeEmotion(emotion), // 情绪中文→英文枚举
|
||||
speed: 1.0,
|
||||
})
|
||||
console.log("[AI数字人-克隆试听] previewTts 响应:", {
|
||||
audio_url: res.audio_url?.substring(0, 80),
|
||||
@@ -252,7 +247,7 @@ export function PanelVoiceSelector({
|
||||
type="button"
|
||||
className="aa-voice-card__preview"
|
||||
title={previewingId === voice.id ? "停止试听" : "试听"}
|
||||
disabled={voice.type === "preset" && !previewUrl}
|
||||
disabled={!previewUrl}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handlePreview(voice)
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
/**
|
||||
* AI数字人 — 标题库选择弹窗
|
||||
* 复用智能剪辑的标题库 API,选择标题后填入输入框
|
||||
*/
|
||||
import React, { useEffect, useState } from "react"
|
||||
import { getTitles } from "@/api/titles"
|
||||
import type { TitleItem } from "@/api/titles/types"
|
||||
|
||||
interface TitleLibraryModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSelect: (title: string) => void
|
||||
}
|
||||
|
||||
const TitleLibraryModal: React.FC<TitleLibraryModalProps> = ({ open, onClose, onSelect }) => {
|
||||
const [titles, setTitles] = useState<TitleItem[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [search, setSearch] = useState("")
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setLoading(true)
|
||||
getTitles()
|
||||
.then((items) => setTitles(items))
|
||||
.catch(() => setTitles([]))
|
||||
.finally(() => setLoading(false))
|
||||
}, [open])
|
||||
|
||||
const filtered = titles.filter(
|
||||
(t) => !search || t.content.toLowerCase().includes(search.toLowerCase()),
|
||||
)
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="aa-modal-overlay" onClick={onClose}>
|
||||
<div className="aa-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 600 }}>
|
||||
<div className="aa-modal__header">
|
||||
<span className="aa-modal__title">从标题库选择</span>
|
||||
<button className="aa-modal__close" onClick={onClose}></button>
|
||||
</div>
|
||||
<div className="aa-modal__body">
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<input
|
||||
className="aa-input"
|
||||
placeholder="搜索标题..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{loading ? (
|
||||
<div style={{ textAlign: "center", padding: 40, color: "#8c8ca1" }}>加载中...</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div style={{ textAlign: "center", padding: 40, color: "#8c8ca1" }}>
|
||||
暂无标题,请先在标题库创建
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ maxHeight: 400, overflowY: "auto" }}>
|
||||
{filtered.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
style={{
|
||||
padding: "12px 16px",
|
||||
marginBottom: 8,
|
||||
background: "#f8f8fc",
|
||||
borderRadius: 8,
|
||||
cursor: "pointer",
|
||||
transition: "background 0.2s",
|
||||
}}
|
||||
onMouseEnter={(e) => (e.currentTarget.style.background = "#eef0ff")}
|
||||
onMouseLeave={(e) => (e.currentTarget.style.background = "#f8f8fc")}
|
||||
onClick={() => {
|
||||
onSelect(t.content)
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 14, color: "#1a1a2e", marginBottom: 4 }}>{t.content}</div>
|
||||
<div style={{ fontSize: 12, color: "#8c8ca1" }}>
|
||||
{t.word_count ?? t.content.length}字 ·{" "}
|
||||
{t.created_at ? new Date(t.created_at).toLocaleDateString() : ""}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="aa-modal__footer">
|
||||
<button className="aa-btn" onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TitleLibraryModal
|
||||
@@ -77,9 +77,6 @@ export interface AiAvatarTitleConfig {
|
||||
shadow: boolean
|
||||
color: string
|
||||
auto_subtitle: boolean
|
||||
/** 自定义位置坐标(position=custom 时生效,像素) */
|
||||
pos_x?: number
|
||||
pos_y?: number
|
||||
}
|
||||
|
||||
/* ── 封面配置 ── */
|
||||
@@ -89,8 +86,6 @@ export interface AiAvatarCoverConfig {
|
||||
frame_time: number
|
||||
upload_url: string | null
|
||||
thumbnail_url: string | null
|
||||
/** 智能封面(MediaKit 选帧)返回的 OSS 非临时 URL(#1822) */
|
||||
smart_cover_url: string | null
|
||||
}
|
||||
|
||||
/* ── 渲染任务 ── */
|
||||
@@ -108,7 +103,7 @@ export interface RenderJob {
|
||||
/* ── 默认值 ── */
|
||||
export const DEFAULT_TITLE_CONFIG: AiAvatarTitleConfig = {
|
||||
title: "",
|
||||
position: "bottom",
|
||||
position: "top",
|
||||
font: "思源黑体",
|
||||
size: 28,
|
||||
bold: true,
|
||||
@@ -117,8 +112,6 @@ export const DEFAULT_TITLE_CONFIG: AiAvatarTitleConfig = {
|
||||
shadow: false,
|
||||
color: "#ffffff",
|
||||
auto_subtitle: true,
|
||||
pos_x: undefined,
|
||||
pos_y: undefined,
|
||||
}
|
||||
|
||||
export const DEFAULT_COVER_CONFIG: AiAvatarCoverConfig = {
|
||||
@@ -127,5 +120,4 @@ export const DEFAULT_COVER_CONFIG: AiAvatarCoverConfig = {
|
||||
frame_time: 0,
|
||||
upload_url: null,
|
||||
thumbnail_url: null,
|
||||
smart_cover_url: null,
|
||||
}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* AI数字人 — 前后端接口契约转换工具(#1822)
|
||||
*
|
||||
* 以 packages/domain/video_filter_builder.py 的 build_title_drawtext_filter() 为唯一口径
|
||||
* (契约文档第 5 节的 titles[]/fontSize/frame/start/end 为误写,后端不认,禁止使用)。
|
||||
*/
|
||||
import type { AiAvatarTitleConfig, AiAvatarCoverConfig, VoiceEmotion } from "../types"
|
||||
|
||||
/* ── 情绪:中文 → 英文(防御性映射;state 默认已是英文) ── */
|
||||
const EMOTION_ZH_TO_EN: Record<string, VoiceEmotion> = {
|
||||
自然: "natural",
|
||||
兴奋: "excited",
|
||||
沉稳: "calm",
|
||||
亲切: "friendly",
|
||||
}
|
||||
const VALID_EMOTIONS: VoiceEmotion[] = ["natural", "excited", "calm", "friendly"]
|
||||
|
||||
/** 归一化为后端英文枚举 natural/excited/calm/friendly;非法/空值回退 natural。 */
|
||||
export function normalizeEmotion(raw: string | undefined | null): VoiceEmotion {
|
||||
if (!raw) return "natural"
|
||||
const v = raw.trim()
|
||||
if ((VALID_EMOTIONS as string[]).includes(v)) return v as VoiceEmotion
|
||||
return EMOTION_ZH_TO_EN[v] ?? "natural"
|
||||
}
|
||||
|
||||
/* ── 标题:前端 state → 后端 build_title_drawtext_filter 字段(单个 title_config dict) ── */
|
||||
/**
|
||||
* 后端真实字段:text(或content)、font(或font_preset)、font_size(或size)、
|
||||
* font_color(或color,可传 #RRGGBB)、position(top/center/bottom/custom)、
|
||||
* enabled、bold、stroke{enabled,width,color}、shadow{enabled,color,offset_x,offset_y}、
|
||||
* pos_x/pos_y(custom 时)。
|
||||
* 口播标题默认 position=bottom(不传后端会默认 top 跑到画面顶部)。
|
||||
*/
|
||||
export function buildTitleConfigPayload(cfg: AiAvatarTitleConfig): Record<string, unknown> {
|
||||
const text = (cfg.title || "").trim()
|
||||
if (!text) return {}
|
||||
const position = cfg.position || "bottom"
|
||||
const payload: Record<string, unknown> = {
|
||||
text,
|
||||
enabled: true,
|
||||
font: cfg.font || "思源黑体",
|
||||
font_size: Math.round(cfg.size) || 36,
|
||||
font_color: cfg.color || "#ffffff",
|
||||
position,
|
||||
bold: !!cfg.bold,
|
||||
stroke: cfg.stroke ? { enabled: true, width: 2, color: "#000000" } : { enabled: false },
|
||||
shadow: cfg.shadow
|
||||
? { enabled: true, color: "#000000", offset_x: 2, offset_y: 2 }
|
||||
: { enabled: false },
|
||||
}
|
||||
// 自定义坐标(custom 位置)
|
||||
if (position === "custom" && typeof cfg.pos_x === "number" && typeof cfg.pos_y === "number") {
|
||||
payload.pos_x = cfg.pos_x
|
||||
payload.pos_y = cfg.pos_y
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
/* ── 封面:前端 state → 后端 render cover_config ── */
|
||||
export function buildCoverConfigPayload(
|
||||
cfg: AiAvatarCoverConfig,
|
||||
smartCoverUrl: string | null,
|
||||
): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = {
|
||||
enabled: !!cfg.enabled,
|
||||
mode: cfg.mode,
|
||||
// build_cover_extract_command 读取 timestamp(截帧秒数)
|
||||
timestamp: cfg.frame_time || 0,
|
||||
}
|
||||
if (smartCoverUrl) payload.cover_url = smartCoverUrl
|
||||
// 自定义上传:blob: 本地预览地址无法给后端,仅 OSS URL 可用
|
||||
if (cfg.mode === "upload" && cfg.upload_url && !cfg.upload_url.startsWith("blob:")) {
|
||||
payload.upload_url = cfg.upload_url
|
||||
}
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { useBatchDelete } from "./useBatchDelete"
|
||||
export { useBatchTag } from "./useBatchTag"
|
||||
export { useBatchClassify } from "./useBatchClassify"
|
||||
export { useBatchMark } from "./useBatchMark"
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import { batchClassifyAssets, type BatchOperationResult } from "@/api/assets"
|
||||
|
||||
interface UseBatchClassifyOptions {
|
||||
selectedIds: Set<string>
|
||||
queryClient: ReturnType<typeof import("@tanstack/react-query").useQueryClient>
|
||||
showResult: (result: BatchOperationResult, title: string, clear?: boolean) => void
|
||||
}
|
||||
|
||||
export const useBatchClassify = ({
|
||||
selectedIds,
|
||||
queryClient,
|
||||
showResult,
|
||||
}: UseBatchClassifyOptions) => {
|
||||
const [classifyModalOpen, setClassifyModalOpen] = useState(false)
|
||||
const [batchCategory, setBatchCategory] = useState("")
|
||||
const [batchLoading, setBatchLoading] = useState(false)
|
||||
|
||||
const handleBatchClassify = useCallback(async () => {
|
||||
if (!batchCategory) {
|
||||
message.warning("请选择分类")
|
||||
return
|
||||
}
|
||||
const ids = Array.from(selectedIds)
|
||||
setBatchLoading(true)
|
||||
try {
|
||||
const result = await batchClassifyAssets({
|
||||
asset_ids: ids,
|
||||
category: batchCategory,
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ["assets"] })
|
||||
showResult(result, "批量改分类")
|
||||
setClassifyModalOpen(false)
|
||||
setBatchCategory("")
|
||||
if (result.failure_count === 0) {
|
||||
message.success(`成功将 ${result.success_count} 个素材改为「${batchCategory}」`)
|
||||
} else {
|
||||
message.warning(
|
||||
`改分类完成:成功 ${result.success_count} 个,失败 ${result.failure_count} 个`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
message.error("批量改分类失败,请重试")
|
||||
} finally {
|
||||
setBatchLoading(false)
|
||||
}
|
||||
}, [batchCategory, selectedIds, queryClient, showResult])
|
||||
|
||||
return {
|
||||
classifyModalOpen,
|
||||
setClassifyModalOpen,
|
||||
batchCategory,
|
||||
setBatchCategory,
|
||||
batchLoading,
|
||||
handleBatchClassify,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import { batchDeleteAssets, type BatchOperationResult } from "@/api/assets"
|
||||
|
||||
interface UseBatchDeleteOptions {
|
||||
selectedIds: Set<string>
|
||||
invalidateAssets: () => void
|
||||
showResult: (result: BatchOperationResult, title: string, clear?: boolean) => void
|
||||
}
|
||||
|
||||
export const useBatchDelete = ({
|
||||
selectedIds,
|
||||
invalidateAssets,
|
||||
showResult,
|
||||
}: UseBatchDeleteOptions) => {
|
||||
const [batchLoading, setBatchLoading] = useState(false)
|
||||
|
||||
const handleBatchDelete = useCallback(async () => {
|
||||
const ids = Array.from(selectedIds)
|
||||
setBatchLoading(true)
|
||||
try {
|
||||
const result = await batchDeleteAssets(ids)
|
||||
invalidateAssets()
|
||||
showResult(result, "批量删除")
|
||||
if (result.failure_count === 0) {
|
||||
message.success(`成功删除 ${result.success_count} 个素材`)
|
||||
} else {
|
||||
message.warning(
|
||||
`删除完成:成功 ${result.success_count} 个,失败 ${result.failure_count} 个`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
message.error("批量删除失败,请重试")
|
||||
} finally {
|
||||
setBatchLoading(false)
|
||||
}
|
||||
}, [selectedIds, invalidateAssets, showResult])
|
||||
|
||||
return { batchLoading, handleBatchDelete }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import { batchMarkAssets, type BatchOperationResult } from "@/api/assets"
|
||||
import type { SmartViewType } from "../../../components/BatchMarkModal"
|
||||
import { SMART_VIEW_LABELS } from "../constants"
|
||||
|
||||
interface UseBatchMarkOptions {
|
||||
selectedIds: Set<string>
|
||||
queryClient: ReturnType<typeof import("@tanstack/react-query").useQueryClient>
|
||||
showResult: (result: BatchOperationResult, title: string, clear?: boolean) => void
|
||||
}
|
||||
|
||||
export const useBatchMark = ({ selectedIds, queryClient, showResult }: UseBatchMarkOptions) => {
|
||||
const [markModalOpen, setMarkModalOpen] = useState(false)
|
||||
const [batchSmartView, setBatchSmartView] = useState<SmartViewType>("recommended")
|
||||
const [batchLoading, setBatchLoading] = useState(false)
|
||||
|
||||
const handleBatchMark = useCallback(async () => {
|
||||
const ids = Array.from(selectedIds)
|
||||
setBatchLoading(true)
|
||||
try {
|
||||
const result = await batchMarkAssets({
|
||||
asset_ids: ids,
|
||||
smart_view: batchSmartView,
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ["assets"] })
|
||||
showResult(result, "批量智能标记")
|
||||
setMarkModalOpen(false)
|
||||
if (result.failure_count === 0) {
|
||||
message.success(
|
||||
`成功将 ${result.success_count} 个素材标记为「${SMART_VIEW_LABELS[batchSmartView]}」`,
|
||||
)
|
||||
} else {
|
||||
message.warning(
|
||||
`智能标记完成:成功 ${result.success_count} 个,失败 ${result.failure_count} 个`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
message.error("批量智能标记失败,请重试")
|
||||
} finally {
|
||||
setBatchLoading(false)
|
||||
}
|
||||
}, [batchSmartView, selectedIds, queryClient, showResult])
|
||||
|
||||
return {
|
||||
markModalOpen,
|
||||
setMarkModalOpen,
|
||||
batchSmartView,
|
||||
setBatchSmartView,
|
||||
batchLoading,
|
||||
handleBatchMark,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useState, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import { batchTagAssets, type BatchOperationResult } from "@/api/assets"
|
||||
|
||||
interface UseBatchTagOptions {
|
||||
selectedIds: Set<string>
|
||||
queryClient: ReturnType<typeof import("@tanstack/react-query").useQueryClient>
|
||||
showResult: (result: BatchOperationResult, title: string, clear?: boolean) => void
|
||||
}
|
||||
|
||||
export const useBatchTag = ({ selectedIds, queryClient, showResult }: UseBatchTagOptions) => {
|
||||
const [tagModalOpen, setTagModalOpen] = useState(false)
|
||||
const [batchTagInput, setBatchTagInput] = useState("")
|
||||
const [batchTags, setBatchTags] = useState<string[]>([])
|
||||
const [tagMode, setTagMode] = useState<"add" | "replace">("add")
|
||||
const [batchLoading, setBatchLoading] = useState(false)
|
||||
|
||||
const handleBatchTag = useCallback(async () => {
|
||||
if (batchTags.length === 0) {
|
||||
message.warning("请至少输入一个标签")
|
||||
return
|
||||
}
|
||||
const ids = Array.from(selectedIds)
|
||||
setBatchLoading(true)
|
||||
try {
|
||||
const result = await batchTagAssets({
|
||||
asset_ids: ids,
|
||||
tags: batchTags,
|
||||
mode: tagMode,
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ["assets"] })
|
||||
showResult(result, "批量打标签")
|
||||
setTagModalOpen(false)
|
||||
setBatchTags([])
|
||||
setBatchTagInput("")
|
||||
setTagMode("add")
|
||||
if (result.failure_count === 0) {
|
||||
message.success(`成功为 ${result.success_count} 个素材打标签`)
|
||||
} else {
|
||||
message.warning(
|
||||
`打标签完成:成功 ${result.success_count} 个,失败 ${result.failure_count} 个`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
message.error("批量打标签失败,请重试")
|
||||
} finally {
|
||||
setBatchLoading(false)
|
||||
}
|
||||
}, [batchTags, selectedIds, tagMode, queryClient, showResult])
|
||||
|
||||
const handleTagInputKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && batchTagInput.trim()) {
|
||||
e.preventDefault()
|
||||
const tag = batchTagInput.trim()
|
||||
if (!batchTags.includes(tag)) {
|
||||
setBatchTags([...batchTags, tag])
|
||||
}
|
||||
setBatchTagInput("")
|
||||
}
|
||||
},
|
||||
[batchTagInput, batchTags],
|
||||
)
|
||||
|
||||
const removeBatchTag = useCallback(
|
||||
(tag: string) => {
|
||||
setBatchTags(batchTags.filter((t) => t !== tag))
|
||||
},
|
||||
[batchTags],
|
||||
)
|
||||
|
||||
return {
|
||||
tagModalOpen,
|
||||
setTagModalOpen,
|
||||
batchTagInput,
|
||||
setBatchTagInput,
|
||||
batchTags,
|
||||
setBatchTags,
|
||||
tagMode,
|
||||
setTagMode,
|
||||
batchLoading,
|
||||
handleBatchTag,
|
||||
handleTagInputKeyDown,
|
||||
removeBatchTag,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* @deprecated 请从 ./batch/ 目录导入子模块
|
||||
* 保持向后兼容,re-export 所有批量操作 Hook
|
||||
*/
|
||||
export { useBatchDelete } from "./batch/useBatchDelete"
|
||||
export { useBatchTag } from "./batch/useBatchTag"
|
||||
export { useBatchClassify } from "./batch/useBatchClassify"
|
||||
export { useBatchMark } from "./batch/useBatchMark"
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* LayerConfig 入口(向后兼容)
|
||||
* 实际实现位于 ./layer-config/ 目录
|
||||
*/
|
||||
export { default } from "./layer-config"
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 混剪图层列表
|
||||
*/
|
||||
import React from "react"
|
||||
import type { PipLayer } from "@/pages/editing-planner/types"
|
||||
import { LAYER_COLORS } from "@/pages/editing-planner/constants/pipConfig"
|
||||
|
||||
interface LayerListProps {
|
||||
layers: PipLayer[]
|
||||
selectedId: string
|
||||
onSelect: (id: string) => void
|
||||
onAdd: () => void
|
||||
onDelete: (id: string) => void
|
||||
}
|
||||
|
||||
const LayerList: React.FC<LayerListProps> = ({ layers, selectedId, onSelect, onAdd, onDelete }) => {
|
||||
return (
|
||||
<div className="pip-layer-list">
|
||||
<div className="pip-toolbar" style={{ marginBottom: 8 }}>
|
||||
<button className="pip-add-btn" onClick={onAdd}>
|
||||
+ 添加图层
|
||||
</button>
|
||||
</div>
|
||||
{layers.length === 0 ? (
|
||||
<div className="pip-layer-empty">暂无图层,点击上方添加</div>
|
||||
) : (
|
||||
layers.map((layer, idx) => (
|
||||
<div
|
||||
key={layer.id}
|
||||
className={`pip-layer-item${selectedId === layer.id ? " active" : ""}`}
|
||||
onClick={() => onSelect(layer.id)}
|
||||
>
|
||||
{layer.thumbnail_url || layer.material_url ? (
|
||||
<img
|
||||
className="pip-layer-thumb"
|
||||
src={layer.thumbnail_url || layer.material_url}
|
||||
alt={layer.name}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="pip-layer-thumb"
|
||||
style={{
|
||||
background: LAYER_COLORS[idx % LAYER_COLORS.length],
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<span className="pip-layer-name">{layer.name}</span>
|
||||
<button
|
||||
className="pip-layer-delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(layer.id)
|
||||
}}
|
||||
title="删除图层"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LayerList
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import React from "react"
|
||||
import type { PipLayer, PipGridPosition } from "@/pages/editing-planner/types"
|
||||
import { GRID_POSITIONS } from "@/pages/editing-planner/constants/pipConfig"
|
||||
|
||||
interface LayerPositionSizeProps {
|
||||
layer: PipLayer
|
||||
onUpdate: (id: string, partial: Partial<PipLayer>) => void
|
||||
onGridClick: (pos: PipGridPosition) => void
|
||||
onWidthChange: (val: number) => void
|
||||
onHeightChange: (val: number) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 图层位置与尺寸配置面板
|
||||
*/
|
||||
export const LayerPositionSize: React.FC<LayerPositionSizeProps> = ({
|
||||
layer,
|
||||
onUpdate,
|
||||
onGridClick,
|
||||
onWidthChange,
|
||||
onHeightChange,
|
||||
}) => (
|
||||
<>
|
||||
{/* 素材类型 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">素材类型</label>
|
||||
<div className="pip-type-btns">
|
||||
<button
|
||||
className={`pip-type-btn${layer.material_type === "image" ? " active" : ""}`}
|
||||
onClick={() => onUpdate(layer.id, { material_type: "image" })}
|
||||
>
|
||||
🖼️ 图片
|
||||
</button>
|
||||
<button
|
||||
className={`pip-type-btn${layer.material_type === "video" ? " active" : ""}`}
|
||||
onClick={() => onUpdate(layer.id, { material_type: "video" })}
|
||||
>
|
||||
🎬 视频
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 素材 URL */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">
|
||||
{layer.material_type === "image" ? "图片" : "视频"} URL
|
||||
</label>
|
||||
<input
|
||||
className="pip-input"
|
||||
type="text"
|
||||
placeholder={
|
||||
layer.material_type === "image"
|
||||
? "https://example.com/image.png"
|
||||
: "https://example.com/video.mp4"
|
||||
}
|
||||
value={layer.material_url}
|
||||
onChange={(e) => onUpdate(layer.id, { material_url: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 位置:九宫格 + 坐标 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">位置</label>
|
||||
<div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
|
||||
<div className="pip-grid">
|
||||
{GRID_POSITIONS.map((pos) => (
|
||||
<button
|
||||
key={pos}
|
||||
className={`pip-grid-btn${layer.grid_position === pos ? " active" : ""}`}
|
||||
onClick={() => onGridClick(pos)}
|
||||
>
|
||||
<span className="pip-grid-dot" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="pip-field-row" style={{ flex: 1 }}>
|
||||
<div>
|
||||
<label className="pip-field-label">X (%)</label>
|
||||
<input
|
||||
className="pip-number"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
value={layer.x}
|
||||
onChange={(e) => onUpdate(layer.id, { x: Number(e.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="pip-field-label">Y (%)</label>
|
||||
<input
|
||||
className="pip-number"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
value={layer.y}
|
||||
onChange={(e) => onUpdate(layer.id, { y: Number(e.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 尺寸 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">尺寸</label>
|
||||
<div className="pip-slider-row">
|
||||
<span style={{ fontSize: 12, color: "#999", width: 20 }}>宽</span>
|
||||
<input
|
||||
className="pip-slider"
|
||||
type="range"
|
||||
min={10}
|
||||
max={80}
|
||||
value={layer.width}
|
||||
onChange={(e) => onWidthChange(Number(e.target.value))}
|
||||
/>
|
||||
<span className="pip-slider-value">{layer.width}%</span>
|
||||
</div>
|
||||
<div className="pip-slider-row" style={{ marginTop: 6 }}>
|
||||
<span style={{ fontSize: 12, color: "#999", width: 20 }}>高</span>
|
||||
<input
|
||||
className="pip-slider"
|
||||
type="range"
|
||||
min={10}
|
||||
max={80}
|
||||
value={layer.height}
|
||||
onChange={(e) => onHeightChange(Number(e.target.value))}
|
||||
/>
|
||||
<span className="pip-slider-value">{layer.height}%</span>
|
||||
</div>
|
||||
<div
|
||||
className="pip-lock-row"
|
||||
style={{ marginTop: 6 }}
|
||||
onClick={() => onUpdate(layer.id, { aspect_lock: !layer.aspect_lock })}
|
||||
>
|
||||
<span className="pip-lock-icon">{layer.aspect_lock ? "🔒" : "🔓"}</span>
|
||||
<span>{layer.aspect_lock ? "已锁定比例" : "锁定宽高比"}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 圆角 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">圆角</label>
|
||||
<div className="pip-slider-row">
|
||||
<input
|
||||
className="pip-slider"
|
||||
type="range"
|
||||
min={0}
|
||||
max={50}
|
||||
value={layer.border_radius}
|
||||
onChange={(e) => onUpdate(layer.id, { border_radius: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="pip-slider-value">{layer.border_radius}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 透明度 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">透明度</label>
|
||||
<div className="pip-slider-row">
|
||||
<input
|
||||
className="pip-slider"
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={layer.opacity}
|
||||
onChange={(e) => onUpdate(layer.id, { opacity: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="pip-slider-value">{layer.opacity}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import React from "react"
|
||||
import type { PipLayer, PipAnimType, PipSlideDirection } from "@/pages/editing-planner/types"
|
||||
import { ANIM_OPTIONS, SLIDE_DIR_OPTIONS } from "@/pages/editing-planner/constants/pipConfig"
|
||||
|
||||
interface LayerTimingAnimationProps {
|
||||
layer: PipLayer
|
||||
totalDuration: number
|
||||
onUpdate: (id: string, partial: Partial<PipLayer>) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 图层时间与动画配置面板
|
||||
*/
|
||||
export const LayerTimingAnimation: React.FC<LayerTimingAnimationProps> = ({
|
||||
layer,
|
||||
totalDuration,
|
||||
onUpdate,
|
||||
}) => (
|
||||
<>
|
||||
{/* 时间 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">时间</label>
|
||||
<div className="pip-field-row">
|
||||
<div>
|
||||
<label className="pip-field-label">开始 (s)</label>
|
||||
<input
|
||||
className="pip-number"
|
||||
type="number"
|
||||
min={0}
|
||||
max={totalDuration || 999}
|
||||
step={0.1}
|
||||
value={layer.start_time}
|
||||
onChange={(e) => onUpdate(layer.id, { start_time: Number(e.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="pip-field-label">持续 (s)</label>
|
||||
<input
|
||||
className="pip-number"
|
||||
type="number"
|
||||
min={0.1}
|
||||
max={totalDuration || 999}
|
||||
step={0.1}
|
||||
value={layer.duration}
|
||||
onChange={(e) => onUpdate(layer.id, { duration: Number(e.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 入场动画 */}
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">入场动画</label>
|
||||
<select
|
||||
className="pip-select"
|
||||
value={layer.animation}
|
||||
onChange={(e) => onUpdate(layer.id, { animation: e.target.value as PipAnimType })}
|
||||
>
|
||||
{ANIM_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* 滑入方向(仅 slide_in 时显示) */}
|
||||
{layer.animation === "slide_in" && (
|
||||
<div className="pip-field">
|
||||
<label className="pip-field-label">滑入方向</label>
|
||||
<select
|
||||
className="pip-select"
|
||||
value={layer.slide_direction}
|
||||
onChange={(e) =>
|
||||
onUpdate(layer.id, { slide_direction: e.target.value as PipSlideDirection })
|
||||
}
|
||||
>
|
||||
{SLIDE_DIR_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
import React from "react"
|
||||
import type { PipLayer } from "@/pages/editing-planner/types"
|
||||
import { LAYER_COLORS } from "@/pages/editing-planner/constants/pipConfig"
|
||||
|
||||
interface PipPreviewProps {
|
||||
layers: PipLayer[]
|
||||
selectedId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* PIP 图层迷你预览组件
|
||||
*/
|
||||
export const PipPreview: React.FC<PipPreviewProps> = ({ layers, selectedId }) => (
|
||||
<div className="pip-preview-box">
|
||||
{layers.map((l, idx) => (
|
||||
<div
|
||||
key={l.id}
|
||||
className={`pip-preview-layer${selectedId === l.id ? " selected" : ""}`}
|
||||
style={{
|
||||
left: `${l.x}%`,
|
||||
top: `${l.y}%`,
|
||||
width: `${l.width}%`,
|
||||
height: `${l.height}%`,
|
||||
background: LAYER_COLORS[idx % LAYER_COLORS.length],
|
||||
opacity: l.opacity / 100,
|
||||
borderRadius: `${l.border_radius}%`,
|
||||
}}
|
||||
>
|
||||
<span className="pip-preview-label">{l.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 混剪单图层配置区
|
||||
*/
|
||||
import React from "react"
|
||||
import type { PipLayer, PipGridPosition } from "@/pages/editing-planner/types"
|
||||
import { PipPreview } from "./PipPreview"
|
||||
import { LayerPositionSize } from "./LayerPositionSize"
|
||||
import { LayerTimingAnimation } from "./LayerTimingAnimation"
|
||||
|
||||
interface LayerConfigProps {
|
||||
layer: PipLayer | null
|
||||
layers: PipLayer[]
|
||||
totalDuration: number
|
||||
onUpdate: (id: string, partial: Partial<PipLayer>) => void
|
||||
onGridClick: (pos: PipGridPosition) => void
|
||||
onWidthChange: (val: number) => void
|
||||
onHeightChange: (val: number) => void
|
||||
}
|
||||
|
||||
const LayerConfig: React.FC<LayerConfigProps> = ({
|
||||
layer,
|
||||
layers,
|
||||
totalDuration,
|
||||
onUpdate,
|
||||
onGridClick,
|
||||
onWidthChange,
|
||||
onHeightChange,
|
||||
}) => {
|
||||
if (!layer) {
|
||||
return (
|
||||
<div className="pip-config-area">
|
||||
<div className="pip-config-empty">选择或添加图层以配置</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pip-config-area">
|
||||
{/* 迷你预览 */}
|
||||
<PipPreview layers={layers} selectedId={layer.id} />
|
||||
|
||||
{/* 位置与尺寸 */}
|
||||
<LayerPositionSize
|
||||
layer={layer}
|
||||
onUpdate={onUpdate}
|
||||
onGridClick={onGridClick}
|
||||
onWidthChange={onWidthChange}
|
||||
onHeightChange={onHeightChange}
|
||||
/>
|
||||
|
||||
{/* 时间与动画 */}
|
||||
<LayerTimingAnimation layer={layer} totalDuration={totalDuration} onUpdate={onUpdate} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LayerConfig
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 贴纸素材库(emoji / 图片 / 文字花字)
|
||||
*/
|
||||
import React, { useState } from "react"
|
||||
import type { StickerType, TextStickerPreset } from "@/pages/editing-planner/types"
|
||||
import {
|
||||
EMOJI_LIST,
|
||||
STICKER_TYPE_TABS,
|
||||
TEXT_PRESET_STYLES,
|
||||
TEXT_STICKER_PRESET_LABELS,
|
||||
} from "@/pages/editing-planner/constants/sticker"
|
||||
|
||||
interface StickerLibraryProps {
|
||||
activeTab: StickerType
|
||||
onTabChange: (tab: StickerType) => void
|
||||
onAddSticker: (type: StickerType, content: string) => void
|
||||
}
|
||||
|
||||
const StickerLibrary: React.FC<StickerLibraryProps> = ({
|
||||
activeTab,
|
||||
onTabChange,
|
||||
onAddSticker,
|
||||
}) => {
|
||||
const [textInput, setTextInput] = useState("")
|
||||
const imageInputRef = React.useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleAddImage = () => {
|
||||
const val = imageInputRef.current?.value.trim()
|
||||
if (val) {
|
||||
onAddSticker("image", val)
|
||||
if (imageInputRef.current) imageInputRef.current.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
const handleAddText = () => {
|
||||
if (textInput.trim()) {
|
||||
onAddSticker("text", textInput.trim())
|
||||
setTextInput("")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 类型 Tab */}
|
||||
<div className="sticker-tabs">
|
||||
{STICKER_TYPE_TABS.map((t) => (
|
||||
<button
|
||||
key={t.value}
|
||||
className={`sticker-tab${activeTab === t.value ? " active" : ""}`}
|
||||
onClick={() => onTabChange(t.value)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Tab 内容区 */}
|
||||
<div className="sticker-tab-content">
|
||||
{/* Emoji 素材库 */}
|
||||
{activeTab === "emoji" && (
|
||||
<div className="sticker-emoji-grid">
|
||||
{EMOJI_LIST.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
className="sticker-emoji-btn"
|
||||
onClick={() => onAddSticker("emoji", emoji)}
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 图片贴纸 */}
|
||||
{activeTab === "image" && (
|
||||
<div className="sticker-image-input">
|
||||
<input
|
||||
ref={imageInputRef}
|
||||
type="text"
|
||||
className="sticker-url-input"
|
||||
placeholder="输入图片 URL 添加贴纸..."
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && e.currentTarget.value.trim()) {
|
||||
handleAddImage()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button className="sticker-url-add-btn" onClick={handleAddImage}>
|
||||
添加
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 文字花字 */}
|
||||
{activeTab === "text" && (
|
||||
<div className="sticker-text-section">
|
||||
<div className="sticker-text-input-row">
|
||||
<input
|
||||
type="text"
|
||||
className="sticker-text-input"
|
||||
placeholder="输入文字内容..."
|
||||
value={textInput}
|
||||
onChange={(e) => setTextInput(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
className="sticker-text-add-btn"
|
||||
disabled={!textInput.trim()}
|
||||
onClick={handleAddText}
|
||||
>
|
||||
添加
|
||||
</button>
|
||||
</div>
|
||||
<div className="sticker-text-presets">
|
||||
<div className="sticker-preset-title">花字预设预览</div>
|
||||
<div className="sticker-preset-grid">
|
||||
{(Object.keys(TEXT_STICKER_PRESET_LABELS) as TextStickerPreset[]).map((p) => (
|
||||
<div
|
||||
key={p}
|
||||
className="sticker-preset-preview"
|
||||
style={{
|
||||
background:
|
||||
p === "bubble"
|
||||
? "rgba(0,0,0,0.5)"
|
||||
: p === "gradient"
|
||||
? "linear-gradient(90deg,#f093fb,#f5576c)"
|
||||
: "#1a1a2e",
|
||||
}}
|
||||
>
|
||||
<span style={TEXT_PRESET_STYLES[p]}>示例</span>
|
||||
<div className="sticker-preset-name">{TEXT_STICKER_PRESET_LABELS[p]}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default StickerLibrary
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* 已添加贴纸列表
|
||||
*/
|
||||
import React from "react"
|
||||
import type { StickerItem } from "@/pages/editing-planner/types"
|
||||
|
||||
interface StickerListProps {
|
||||
items: StickerItem[]
|
||||
selectedId: string | null
|
||||
onSelect: (id: string) => void
|
||||
onDelete: (id: string) => void
|
||||
}
|
||||
|
||||
const StickerList: React.FC<StickerListProps> = ({ items, selectedId, onSelect, onDelete }) => {
|
||||
if (items.length === 0) return null
|
||||
|
||||
const getDisplayContent = (item: StickerItem) => {
|
||||
if (item.type === "emoji") return { icon: item.content, name: "表情贴纸" }
|
||||
if (item.type === "text") return { icon: "T", name: item.content.slice(0, 10) }
|
||||
return { icon: "🖼", name: "图片贴纸" }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="sticker-list-section">
|
||||
<div className="sticker-section-title">已添加贴纸 ({items.length})</div>
|
||||
<div className="sticker-list">
|
||||
{items.map((item) => {
|
||||
const { icon, name } = getDisplayContent(item)
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`sticker-list-item${selectedId === item.id ? " active" : ""}`}
|
||||
onClick={() => onSelect(item.id)}
|
||||
>
|
||||
<span className="sticker-list-icon">{icon}</span>
|
||||
<span className="sticker-list-name">{name}</span>
|
||||
<button
|
||||
className="sticker-list-delete"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete(item.id)
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StickerList
|
||||
@@ -0,0 +1,39 @@
|
||||
import React from "react"
|
||||
import type { StickerItem } from "@/pages/editing-planner/types"
|
||||
import { TEXT_PRESET_STYLES } from "@/pages/editing-planner/constants/sticker"
|
||||
|
||||
interface StickerPreviewProps {
|
||||
sticker: StickerItem
|
||||
}
|
||||
|
||||
export const StickerPreview: React.FC<StickerPreviewProps> = ({ sticker }) => (
|
||||
<div className="sticker-preview-box">
|
||||
<div
|
||||
className="sticker-preview-item"
|
||||
style={{
|
||||
left: `${sticker.x}%`,
|
||||
top: `${sticker.y}%`,
|
||||
width: `${sticker.width}%`,
|
||||
height: `${sticker.height}%`,
|
||||
transform: `translate(-50%, -50%) rotate(${sticker.rotation}deg)`,
|
||||
opacity: sticker.opacity / 100,
|
||||
fontSize: sticker.type === "text" ? `${sticker.font_size}px` : undefined,
|
||||
...TEXT_PRESET_STYLES[sticker.text_preset],
|
||||
}}
|
||||
>
|
||||
{sticker.type === "emoji" && sticker.content}
|
||||
{sticker.type === "text" && sticker.content}
|
||||
{sticker.type === "image" && (
|
||||
<img
|
||||
src={sticker.content}
|
||||
alt="sticker"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
objectFit: "contain",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 选中贴纸的属性编辑器
|
||||
*/
|
||||
import React from "react"
|
||||
import type { StickerItem } from "@/pages/editing-planner/types"
|
||||
import { StickerPreview } from "./StickerPreview"
|
||||
import { TextStickerPropsEditor } from "./TextStickerPropsEditor"
|
||||
|
||||
interface StickerPropsEditorProps {
|
||||
sticker: StickerItem
|
||||
totalDuration: number
|
||||
onUpdate: (id: string, partial: Partial<StickerItem>) => void
|
||||
}
|
||||
|
||||
const StickerPropsEditor: React.FC<StickerPropsEditorProps> = ({
|
||||
sticker,
|
||||
totalDuration,
|
||||
onUpdate,
|
||||
}) => {
|
||||
return (
|
||||
<div className="sticker-props-section">
|
||||
<div className="sticker-section-title">属性调整</div>
|
||||
|
||||
{/* 位置 */}
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">位置 X</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={0}
|
||||
max={100}
|
||||
value={sticker.x}
|
||||
onChange={(e) => onUpdate(sticker.id, { x: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.x}%</span>
|
||||
</div>
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">位置 Y</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={0}
|
||||
max={100}
|
||||
value={sticker.y}
|
||||
onChange={(e) => onUpdate(sticker.id, { y: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.y}%</span>
|
||||
</div>
|
||||
|
||||
{/* 尺寸 */}
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">大小</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={5}
|
||||
max={50}
|
||||
value={sticker.width}
|
||||
onChange={(e) =>
|
||||
onUpdate(sticker.id, {
|
||||
width: Number(e.target.value),
|
||||
height: Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.width}%</span>
|
||||
</div>
|
||||
|
||||
{/* 旋转 */}
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">旋转</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={-180}
|
||||
max={180}
|
||||
value={sticker.rotation}
|
||||
onChange={(e) => onUpdate(sticker.id, { rotation: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.rotation}°</span>
|
||||
</div>
|
||||
|
||||
{/* 透明度 */}
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">透明度</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={0}
|
||||
max={100}
|
||||
value={sticker.opacity}
|
||||
onChange={(e) => onUpdate(sticker.id, { opacity: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.opacity}%</span>
|
||||
</div>
|
||||
|
||||
{/* 时间 */}
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">开始</span>
|
||||
<input
|
||||
type="number"
|
||||
className="sticker-prop-number"
|
||||
min={0}
|
||||
max={totalDuration}
|
||||
step={0.1}
|
||||
value={sticker.start_time}
|
||||
onChange={(e) => onUpdate(sticker.id, { start_time: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-label">时长</span>
|
||||
<input
|
||||
type="number"
|
||||
className="sticker-prop-number"
|
||||
min={0}
|
||||
max={totalDuration}
|
||||
step={0.1}
|
||||
value={sticker.duration}
|
||||
onChange={(e) => onUpdate(sticker.id, { duration: Number(e.target.value) })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 文字贴纸特有属性 */}
|
||||
<TextStickerPropsEditor sticker={sticker} onUpdate={onUpdate} />
|
||||
|
||||
{/* 预览 */}
|
||||
<StickerPreview sticker={sticker} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StickerPropsEditor
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import React from "react"
|
||||
import type { StickerItem, TextStickerPreset } from "@/pages/editing-planner/types"
|
||||
import { TEXT_STICKER_PRESET_LABELS } from "@/pages/editing-planner/constants/sticker"
|
||||
|
||||
interface TextStickerPropsEditorProps {
|
||||
sticker: StickerItem
|
||||
onUpdate: (id: string, partial: Partial<StickerItem>) => void
|
||||
}
|
||||
|
||||
export const TextStickerPropsEditor: React.FC<TextStickerPropsEditorProps> = ({
|
||||
sticker,
|
||||
onUpdate,
|
||||
}) => {
|
||||
if (sticker.type !== "text") return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">花字</span>
|
||||
<select
|
||||
className="sticker-prop-select"
|
||||
value={sticker.text_preset}
|
||||
onChange={(e) =>
|
||||
onUpdate(sticker.id, { text_preset: e.target.value as TextStickerPreset })
|
||||
}
|
||||
>
|
||||
{(Object.keys(TEXT_STICKER_PRESET_LABELS) as TextStickerPreset[]).map((p) => (
|
||||
<option key={p} value={p}>
|
||||
{TEXT_STICKER_PRESET_LABELS[p]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">字号</span>
|
||||
<input
|
||||
type="range"
|
||||
className="sticker-prop-slider"
|
||||
min={12}
|
||||
max={72}
|
||||
value={sticker.font_size}
|
||||
onChange={(e) => onUpdate(sticker.id, { font_size: Number(e.target.value) })}
|
||||
/>
|
||||
<span className="sticker-prop-value">{sticker.font_size}px</span>
|
||||
</div>
|
||||
<div className="sticker-prop-row">
|
||||
<span className="sticker-prop-label">颜色</span>
|
||||
<input
|
||||
type="color"
|
||||
className="sticker-prop-color"
|
||||
value={sticker.text_color}
|
||||
onChange={(e) => onUpdate(sticker.id, { text_color: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* TTS 滑块组件(语速/语调/音量)
|
||||
*/
|
||||
import React from "react"
|
||||
import { Slider } from "antd"
|
||||
|
||||
interface TtsSliderProps {
|
||||
label: string
|
||||
value: number
|
||||
min: number
|
||||
max: number
|
||||
step: number
|
||||
unit?: string
|
||||
onChange: (val: number) => void
|
||||
marks?: string[]
|
||||
tooltipFormatter?: (v: number) => string
|
||||
}
|
||||
|
||||
const TtsSlider: React.FC<TtsSliderProps> = ({
|
||||
label,
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
unit = "",
|
||||
onChange,
|
||||
marks,
|
||||
tooltipFormatter,
|
||||
}) => {
|
||||
const displayValue =
|
||||
unit === "x"
|
||||
? `${value.toFixed(2)}x`
|
||||
: label === "语调"
|
||||
? `${value > 0 ? "+" : ""}${value} 半音`
|
||||
: `${value}${unit}`
|
||||
|
||||
return (
|
||||
<div className="tts-slider-section">
|
||||
<div className="tts-slider-header">
|
||||
<span className="tts-slider-label">{label}</span>
|
||||
<span className="tts-slider-value">{displayValue}</span>
|
||||
</div>
|
||||
<Slider
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={value}
|
||||
onChange={(v) => onChange(v as number)}
|
||||
tooltip={tooltipFormatter ? { formatter: (v) => tooltipFormatter(v as number) } : undefined}
|
||||
/>
|
||||
{marks && (
|
||||
<div className="tts-slider-marks">
|
||||
{marks.map((m, i) => (
|
||||
<span key={i}>{m}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TtsSlider
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* TTS 音色选择组件
|
||||
*/
|
||||
import React from "react"
|
||||
import type { TTSVoice } from "@/api/tts"
|
||||
import { VOICE_CATEGORY_MAP } from "../../constants/tts"
|
||||
|
||||
interface VoiceSelectorProps {
|
||||
voices: TTSVoice[]
|
||||
voicesLoading: boolean
|
||||
selectedVoiceId: string
|
||||
onVoiceSelect: (voiceId: string) => void
|
||||
}
|
||||
|
||||
const VoiceSelector: React.FC<VoiceSelectorProps> = ({
|
||||
voices,
|
||||
voicesLoading,
|
||||
selectedVoiceId,
|
||||
onVoiceSelect,
|
||||
}) => {
|
||||
const voiceCategories = Object.entries(VOICE_CATEGORY_MAP)
|
||||
|
||||
return (
|
||||
<div className="tts-voice-section">
|
||||
<div className="tts-voice-label">
|
||||
选择音色
|
||||
{voicesLoading && <span className="tts-voice-loading">加载中...</span>}
|
||||
</div>
|
||||
<div className="tts-voice-grid">
|
||||
{voiceCategories.map(([cat, info]) => {
|
||||
const voice = voices.find((v) => v.category === cat)
|
||||
const isSelected = voice && selectedVoiceId === voice.id
|
||||
return (
|
||||
<button
|
||||
key={cat}
|
||||
className={`tts-voice-card${isSelected ? " active" : ""}`}
|
||||
onClick={() => voice && onVoiceSelect(voice.id)}
|
||||
disabled={!voice || voicesLoading}
|
||||
>
|
||||
<span className="tts-voice-card-icon">{info.icon}</span>
|
||||
<span className="tts-voice-card-name">{voice?.name || info.label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceSelector
|
||||
@@ -548,21 +548,10 @@ const GeneratePage: React.FC = () => {
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 16,
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
style={{
|
||||
textAlign: "center",
|
||||
marginBottom: 12,
|
||||
fontSize: "1.5rem",
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
🎬 确认生成
|
||||
</h2>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
|
||||
@@ -36,10 +36,10 @@ import "@/pages/assets/hooks/useLibraryManagement"
|
||||
import "@/pages/assets/hooks/useAssetUpload"
|
||||
import "@/pages/assets/hooks/useAssetSelection"
|
||||
import "@/pages/assets/hooks/useAssetOperations"
|
||||
import "@/pages/assets/hooks/asset-operations/batch-operations/useBatchDelete"
|
||||
import "@/pages/assets/hooks/asset-operations/batch-operations/useBatchTag"
|
||||
import "@/pages/assets/hooks/asset-operations/batch-operations/useBatchClassify"
|
||||
import "@/pages/assets/hooks/asset-operations/batch-operations/useBatchMark"
|
||||
import "@/pages/assets/hooks/asset-operations/batch/useBatchDelete"
|
||||
import "@/pages/assets/hooks/asset-operations/batch/useBatchTag"
|
||||
import "@/pages/assets/hooks/asset-operations/batch/useBatchClassify"
|
||||
import "@/pages/assets/hooks/asset-operations/batch/useBatchMark"
|
||||
|
||||
describe("AssetLibrary module smoke test", () => {
|
||||
it("should load all asset modules", () => {
|
||||
|
||||
@@ -53,6 +53,13 @@ import "@/pages/editing-planner/components/clip-properties/SubtitleSettingsSecti
|
||||
import "@/pages/editing-planner/components/clip-properties/BgmSettingsSection"
|
||||
import "@/pages/editing-planner/components/clip-properties/ClipDetailSection"
|
||||
import "@/pages/editing-planner/components/clip-properties/StatsSection"
|
||||
import "@/pages/editing-planner/components/pip-config/LayerList"
|
||||
import "@/pages/editing-planner/components/pip-config/LayerConfig"
|
||||
import "@/pages/editing-planner/components/sticker/StickerLibrary"
|
||||
import "@/pages/editing-planner/components/sticker/StickerList"
|
||||
import "@/pages/editing-planner/components/sticker/StickerPropsEditor"
|
||||
import "@/pages/editing-planner/components/sticker/StickerPreview"
|
||||
import "@/pages/editing-planner/components/sticker/TextStickerPropsEditor"
|
||||
import "@/pages/editing-planner/components/filter/FilterPresetGrid"
|
||||
import "@/pages/editing-planner/components/filter/FilterManualAdjust"
|
||||
import "@/pages/editing-planner/components/intro-outro/IntroOutroBlock"
|
||||
@@ -60,6 +67,8 @@ import "@/pages/editing-planner/components/subtitle-style/SubtitlePreview"
|
||||
import "@/pages/editing-planner/components/subtitle-style/SubtitleModeSwitch"
|
||||
import "@/pages/editing-planner/components/subtitle-style/SubtitlePositionSelector"
|
||||
import "@/pages/editing-planner/components/subtitle-style/SubtitleEffectButtons"
|
||||
import "@/pages/editing-planner/components/tts/VoiceSelector"
|
||||
import "@/pages/editing-planner/components/tts/TtsSlider"
|
||||
import "@/pages/editing-planner/components/watermark/WatermarkTypeTabs"
|
||||
import "@/pages/editing-planner/components/watermark/ImageWatermarkSection"
|
||||
import "@/pages/editing-planner/components/watermark/TextWatermarkSection"
|
||||
|
||||
@@ -37,7 +37,6 @@ celery_app.conf.imports = (
|
||||
"worker_app.tasks._startup",
|
||||
"apps.worker.video_processing.dedup",
|
||||
"worker_app.tasks.cleanup",
|
||||
"apps.api.app.tasks.lipsync_tts",
|
||||
)
|
||||
|
||||
# Celery Beat 定时任务调度
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
# AI 数字人前后端接口契约(#1797 / #1822)
|
||||
|
||||
> 分支:`fix/ai-avatar-v3-1797`
|
||||
> 范围:TTS→对口型链路打通、语速/情绪透传、封面智能选帧、标题字段对齐
|
||||
> 本文档为前后端联调的唯一字段口径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 对口型创建接口 `POST /api/v1/lipsync/jobs`
|
||||
|
||||
支持两种输入模式,**二选一**:
|
||||
|
||||
### 模式 A(推荐):TTS 直生 —— 传音色 + 文案,后端内部合成音频
|
||||
|
||||
前端无需先调 TTS。后端收到请求后:先调 CosyVoice 合成音频 → 转存 OSS → 再提交 MediaKit 对口型。
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"video_url": "https://oss.../person.mp4", // 必填,人物视频(MP4)
|
||||
"voice_id": "cosyvoice-v3-flash-99-xxxx", // 必填,音色 ID(预置音色 或 克隆 profile UUID)
|
||||
"script_text": "省是浙江省,市是永康市……", // 必填,要合成的文案
|
||||
"speed": 1.0, // 可选,语速 0.5~2.0,默认 1.0
|
||||
"emotion": "excited", // 可选,情绪,见 §3
|
||||
"enable_video_loop": false, // 可选,音频长于视频时是否循环画面
|
||||
"project_id": "" // 可选
|
||||
}
|
||||
```
|
||||
|
||||
### 模式 B:直接音频 —— 前端已准备好音频
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"video_url": "https://oss.../person.mp4", // 必填
|
||||
"audio_url": "https://oss.../voice.mp3", // 必填,mp3/aac/wav/m4a/flac
|
||||
"enable_video_loop": false
|
||||
}
|
||||
```
|
||||
|
||||
### 校验与错误码
|
||||
|
||||
| 场景 | HTTP | detail.code |
|
||||
|------|------|-------------|
|
||||
| 既无 audio_url 又无 voice_id+script_text | 422 | (schema 校验) |
|
||||
| video_url 非 MP4 / audio_url 格式不支持 | 422 | (schema 校验) |
|
||||
| 克隆音色不属于当前用户 | 403 | `VoiceForbidden` |
|
||||
| 克隆音色尚未合成完成 | 400 | `VoiceNotReady` |
|
||||
| TTS 合成失败(如 CosyVoice 欠费) | 502 | `TTSSynthesisFailed` |
|
||||
| MediaKit 提交失败 | 502 | `*`(透传 MediaKit code) |
|
||||
|
||||
### 轮询
|
||||
|
||||
- `GET /api/v1/lipsync/jobs/{id}`:非终态任务先返回 DB 缓存,**后台异步刷新 MediaKit**(不会阻塞轮询)。
|
||||
- `status` 流转:`pending` → `submitted` → `running`/`processing`(MediaKit 中间态同步)→ `completed` / `failed`。
|
||||
- `completed` 时 `output_video_url` 为**已转存自家 OSS 的非临时 URL**(不会过期)。
|
||||
- 前端每 3s 轮询,命中 `completed`/`failed` 即停。
|
||||
|
||||
---
|
||||
|
||||
## 2. TTS 合成接口语速/情绪透传
|
||||
|
||||
- `POST /api/v1/tts/synthesize`(异步任务)与 `POST /api/v1/tts/preview`(即时试听)均新增:
|
||||
- `speed`:float,0.5~2.0,默认 1.0 → 透传 CosyVoice payload 的 `rate`
|
||||
- `emotion`:string,见 §3 映射 → 透传 `emotion`
|
||||
- 透传链路:`route → CreateTTSJobUseCase(metadata) → TTSJobWorkflow.start_synthesis / 分段合成 → CosyVoiceService.submit_synthesize_task(rate/emotion)`。
|
||||
- 分段合成(长文案)与失败重合成路径同样透传 speed/emotion。
|
||||
|
||||
---
|
||||
|
||||
## 3. 情绪枚举(前后端统一)
|
||||
|
||||
前端把中文选项映射成英文后传后端;后端同时接受中文/英文,非法值忽略(走默认自然)。
|
||||
|
||||
| 前端选项 | 传参值 | CosyVoice 枚举 |
|
||||
|---------|--------|---------------|
|
||||
| 自然 | `natural` | natural |
|
||||
| 兴奋 | `excited` | excited |
|
||||
| 沉稳 | `calm` | calm |
|
||||
| 亲切 | `friendly` | friendly |
|
||||
|
||||
后端 `normalize_emotion()` 也接受中文(自然/兴奋/沉稳/亲切)做兜底映射。
|
||||
|
||||
---
|
||||
|
||||
## 4. 智能封面接口 `POST /api/v1/ai-avatar/render/smart-cover`
|
||||
|
||||
独立接口,**不依赖渲染任务**,前端「智能获取封面」按钮直接调用。
|
||||
|
||||
**请求**
|
||||
```jsonc
|
||||
{
|
||||
"video_url": "https://oss.../avatar_output.mp4", // 必填,数字人视频
|
||||
"max_frames": 5 // 可选,抽帧数量 1~10,默认 5
|
||||
}
|
||||
```
|
||||
|
||||
**响应**
|
||||
```jsonc
|
||||
{
|
||||
"cover_url": "https://oss.../ai-avatar/covers/xxx/cover_yy.jpg", // OSS 非临时 URL
|
||||
"status": "completed", // completed / fallback_failed
|
||||
"message": "" // 失败原因
|
||||
}
|
||||
```
|
||||
|
||||
**实现**:复用智能剪辑同款能力 —— MediaKit `extract_frames(SpecifiedFrames)` 抽 5 帧 → `cover_frame_scorer.score_frames`(清晰度+亮度+色彩)评分选最佳 → 转存 OSS。
|
||||
**不再使用 FFmpeg 简单首帧**。渲染管线最终封面也优先走该智能选帧,MediaKit 不可用时才回退 FFmpeg。
|
||||
|
||||
---
|
||||
|
||||
## 5. 渲染接口 `POST /api/v1/ai-avatar/render`
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"lipsync_job_id": "7c29a3b2-...", // 必填,已 completed 的对口型任务
|
||||
"script_id": "", // 可选!见下方说明
|
||||
"b_roll_segments": [], // 可选,B-roll 片段
|
||||
"title_config": { ... }, // 可选,单个标题配置 dict(见 §6)
|
||||
"cover_config": { ... }, // 可选,封面配置(建议改用 smart-cover)
|
||||
"project_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
**`script_id` 是否必填:可选。**
|
||||
- 从文案库选了文案时传对应文案 ID(后端做归属校验)。
|
||||
- **手动输入文案、走 TTS 直生模式时不传(留空)即可**——渲染管线不依赖文案内容,`script_id` 仅用于归属校验。留空不会卡手动文案用户。
|
||||
|
||||
---
|
||||
|
||||
## 6. 标题配置 `title_config` 字段清单(以 build_title_drawtext_filter 为准)
|
||||
|
||||
渲染请求收的是**单个 `title_config` dict**(不是 `titles[]` 数组),字段与 `packages/domain/video_filter_builder.py` 的 `build_title_drawtext_filter()` 完全对齐:
|
||||
|
||||
| 字段 | 别名 | 类型 | 必填 | 默认 | 说明 |
|
||||
|------|------|------|------|------|------|
|
||||
| `text` | `content` | string | ✅ | — | 标题文字;为空或 `enabled=false` 时不渲染标题 |
|
||||
| `enabled` | — | bool | ❌ | `true` | 是否启用标题;false 跳过 |
|
||||
| `font` | `font_preset` | string | ❌ | 思源黑体 | 字体名(后端按名字解析字体文件) |
|
||||
| `font_size` | `size` | int | ❌ | 36 | 字号(像素) |
|
||||
| `font_color` | `color` | string | ❌ | `#ffffff` | 文字颜色,`#RRGGBB`;后端自动去掉 `#`,也可传 `RRGGBB` 或颜色名 |
|
||||
| `position` | — | string | ❌ | `top` | 预设位置:`top`(y=50) / `center`(垂直居中) / `bottom`(底部上移50px) / `custom` |
|
||||
| `pos_x` | — | int/float | ❌ | — | 自定义 X 坐标(像素),仅 `position=custom` 生效 |
|
||||
| `pos_y` | — | int/float | ❌ | — | 自定义 Y 坐标(像素),仅 `position=custom` 生效 |
|
||||
| `bold` | — | bool | ❌ | `true` | 粗体(Bold 字体变体,回退 borderw 模拟) |
|
||||
| `stroke` | — | bool/object | ❌ | — | 描边。`true`=黑描边宽2;object 见下 |
|
||||
| `stroke.enabled` | — | bool | ❌ | true | 是否描边 |
|
||||
| `stroke.width` | — | int | ❌ | 2 | 描边宽度 |
|
||||
| `stroke.color` | — | string | ❌ | `#000000` | 描边颜色 |
|
||||
| `shadow` | — | bool/object | ❌ | — | 阴影。`true`=黑色阴影偏移2px;object 见下 |
|
||||
| `shadow.enabled` | — | bool | ❌ | true | 是否阴影 |
|
||||
| `shadow.color` | — | string | ❌ | `#000000` | 阴影颜色 |
|
||||
| `shadow.offset_x` | — | int | ❌ | 2 | 阴影 X 偏移 |
|
||||
| `shadow.offset_y` | — | int | ❌ | 2 | 阴影 Y 偏移 |
|
||||
|
||||
**前端注意事项**
|
||||
- 标题是**整条成片一个标题**(单个 dict),不是按时间段的标题数组;没有 `start`/`end`/`frame`/`fontSize` 这些字段。
|
||||
- 位置用 `position` 四档枚举;自由摆放用 `position="custom"` + `pos_x`/`pos_y`(像素坐标,非比例)。
|
||||
- 颜色统一传 `#RRGGBB` 即可,后端会处理 `#`;三档预设位置下标题始终水平居中。
|
||||
- `stroke`/`shadow` 传 `true` 用默认样式,或传 object 精细控制颜色/宽度/偏移。
|
||||
|
||||
---
|
||||
|
||||
## 7. 前端对接清单
|
||||
|
||||
1. 对口型:改用**模式 A**(voice_id + script_text + speed + emotion),不要再先调 TTS 拿 audio_url。
|
||||
2. 音色 ID:`voice_id` 可直接传克隆音色的 profile UUID,后端会解析为 CosyVoice voice_id(与 /tts 一致)。
|
||||
3. 情绪下拉:自然/兴奋/沉稳/亲切 → natural/excited/calm/friendly。
|
||||
4. 封面:点「智能获取封面」→ POST `/ai-avatar/render/smart-cover`,用返回的 `cover_url`。
|
||||
5. 渲染:手动文案直生场景 `script_id` 留空;标题传**单个** `title_config` dict(字段见 §6)。
|
||||
6. 轮询:识别 `running` 等中间态,不要只认 `submitted`。
|
||||
@@ -128,9 +128,9 @@ services:
|
||||
- xiaoxia-net
|
||||
|
||||
# 健康检查配置
|
||||
# 注:容器内无 pgrep/ps,扫描 /proc 所有进程的 cmdline 查找 celery 进程
|
||||
# 注:celery inspect ping 依赖 broker 连接,在容器内不可靠,改用进程检查
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "grep -lq celery /proc/[0-9]*/cmdline 2>/dev/null || exit 1"]
|
||||
test: ["CMD-SHELL", "for pid in /proc/[0-9]*/cmdline; do if grep -ql celery \"$pid\" 2>/dev/null; then exit 0; fi; done; exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
@@ -155,7 +155,7 @@ docker run -d \
|
||||
--restart unless-stopped \
|
||||
--cpus 2 \
|
||||
--memory 2g \
|
||||
--health-cmd "sh -c \"grep -lq celery /proc/[0-9]*/cmdline 2>/dev/null || exit 1\"" \
|
||||
--health-cmd "sh -c \"for pid in /proc/[0-9]*/cmdline; do if grep -ql celery \"$pid\" 2>/dev/null; then exit 0; fi; done; exit 1\"" \
|
||||
--health-interval 30s \
|
||||
--health-timeout 10s \
|
||||
--health-retries 3 \
|
||||
|
||||
@@ -116,7 +116,7 @@ docker run -d \
|
||||
-v "$GENERATED_DIR:/app/generated" \
|
||||
--restart unless-stopped \
|
||||
--label com.centurylinklabs.watchtower.enable=true \
|
||||
--health-cmd "sh -c \"grep -lq celery /proc/[0-9]*/cmdline 2>/dev/null || exit 1\"" \
|
||||
--health-cmd "sh -c \"for pid in /proc/[0-9]*/cmdline; do if grep -ql celery \"$pid\" 2>/dev/null; then exit 0; fi; done; exit 1\"" \
|
||||
--health-interval 30s \
|
||||
--health-timeout 10s \
|
||||
--health-retries 3 \
|
||||
|
||||
@@ -38,10 +38,6 @@ RUN chmod +x /usr/local/bin/entrypoint-worker.sh
|
||||
# 业务代码(变化最频繁,放最后)
|
||||
COPY apps/worker/ /app/apps/worker/
|
||||
|
||||
# 健康检查:扫描所有进程的 cmdline 查找 celery 进程
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD grep -lq celery /proc/[0-9]*/cmdline 2>/dev/null || exit 1
|
||||
|
||||
USER celery
|
||||
WORKDIR /app/apps/worker
|
||||
CMD ["/usr/local/bin/entrypoint-worker.sh"]
|
||||
|
||||
@@ -684,15 +684,9 @@ class LipsyncJobModel(Base):
|
||||
|
||||
# 输入参数
|
||||
video_url = Column(Text, nullable=False)
|
||||
audio_url = Column(Text, nullable=True) # 直生模式(voice_id+script_text)下 TTS 合成后回填
|
||||
audio_url = Column(Text, nullable=False)
|
||||
enable_video_loop = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
# TTS 直生字段:传音色 + 文案,由后端先合成音频再对口型
|
||||
voice_id = Column(String(200), nullable=False, default="")
|
||||
script_text = Column(Text, nullable=False, default="")
|
||||
speed = Column(Float, nullable=False, default=1.0)
|
||||
emotion = Column(String(20), nullable=False, default="")
|
||||
|
||||
# MediaKit 任务状态
|
||||
mediakit_task_id = Column(String(200), nullable=False, default="", index=True)
|
||||
status = Column(
|
||||
@@ -721,8 +715,7 @@ class AiAvatarRenderJob(Base):
|
||||
|
||||
# 输入参数
|
||||
lipsync_job_id = Column(String(36), nullable=False)
|
||||
# 文案 ID 可选:手动输入文案(TTS 直生)场景不关联文案库条目
|
||||
script_id = Column(String(36), nullable=False, default="")
|
||||
script_id = Column(String(36), nullable=False)
|
||||
b_roll_segments = Column(JSON, nullable=False, default=list)
|
||||
# b_roll_segments 格式: [{"script_segment_index": 0, "asset_url": "...", "mode": "fullscreen|pip", "start_time": 5.0, "end_time": 10.0}, ...]
|
||||
title_config = Column(JSON, nullable=False, default=dict)
|
||||
|
||||
@@ -25,35 +25,6 @@ from packages.shared.config import get_shared_settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# CosyVoice 支持的情绪:中文标签 → API 英文值
|
||||
EMOTION_MAP = {
|
||||
"自然": "natural",
|
||||
"兴奋": "excited",
|
||||
"沉稳": "calm",
|
||||
"亲切": "friendly",
|
||||
"natural": "natural",
|
||||
"excited": "excited",
|
||||
"calm": "calm",
|
||||
"friendly": "friendly",
|
||||
}
|
||||
VALID_EMOTIONS = {"natural", "excited", "calm", "friendly"}
|
||||
|
||||
|
||||
def normalize_emotion(emotion: str) -> str:
|
||||
"""将前端情绪值归一化为 CosyVoice 英文枚举。
|
||||
|
||||
支持中文(自然/兴奋/沉稳/亲切)和英文;非法值返回空串(不传,走默认)。
|
||||
"""
|
||||
if not emotion:
|
||||
return ""
|
||||
key = emotion.strip().lower()
|
||||
mapped = EMOTION_MAP.get(emotion.strip()) or EMOTION_MAP.get(key)
|
||||
if mapped and mapped in VALID_EMOTIONS:
|
||||
return mapped
|
||||
logger.warning("未知的 emotion 值,忽略: %r", emotion)
|
||||
return ""
|
||||
|
||||
|
||||
class CosyVoiceError(Exception):
|
||||
"""CosyVoice API 调用异常。"""
|
||||
|
||||
@@ -460,7 +431,6 @@ class CosyVoiceService:
|
||||
format: str = "",
|
||||
speed: float = 1.0,
|
||||
volume: int = 50,
|
||||
emotion: str = "",
|
||||
) -> dict:
|
||||
"""提交语音合成任务(同步非流式,直接返回结果).
|
||||
|
||||
@@ -474,7 +444,6 @@ class CosyVoiceService:
|
||||
format: 输出格式(mp3/wav/pcm),空表示使用配置默认值
|
||||
speed: 语速(0.5-2.0),1.0 为正常速度
|
||||
volume: 音量(0-100),默认 50
|
||||
emotion: 情绪(natural/excited/calm/friendly),空串不传
|
||||
|
||||
Returns:
|
||||
dict: {"audio_url": str, "request_id": str,
|
||||
@@ -494,20 +463,17 @@ class CosyVoiceService:
|
||||
|
||||
settings = get_shared_settings()
|
||||
|
||||
input_payload: dict[str, Any] = {
|
||||
"text": text,
|
||||
"voice": voice_id,
|
||||
"format": format or settings.cosyvoice_format,
|
||||
"sample_rate": sample_rate or settings.cosyvoice_sample_rate,
|
||||
"rate": speed,
|
||||
"volume": volume,
|
||||
payload = {
|
||||
"model": self._model,
|
||||
"input": {
|
||||
"text": text,
|
||||
"voice": voice_id,
|
||||
"format": format or settings.cosyvoice_format,
|
||||
"sample_rate": sample_rate or settings.cosyvoice_sample_rate,
|
||||
"rate": speed,
|
||||
"volume": volume,
|
||||
},
|
||||
}
|
||||
# 情绪:归一化(中文→英文)后透传;空/非法则不传,走 CosyVoice 默认
|
||||
norm_emotion = normalize_emotion(emotion)
|
||||
if norm_emotion:
|
||||
input_payload["emotion"] = norm_emotion
|
||||
|
||||
payload = {"model": self._model, "input": input_payload}
|
||||
|
||||
response = self._call_api(
|
||||
method="POST",
|
||||
@@ -524,10 +490,6 @@ class CosyVoiceService:
|
||||
if not audio_url:
|
||||
raise CosyVoiceError(f"CosyVoice API 未返回 audio_url: {response}")
|
||||
|
||||
# DashScope 返回 http://,统一升级为 https://
|
||||
if audio_url.startswith("http://"):
|
||||
audio_url = audio_url.replace("http://", "https://", 1)
|
||||
|
||||
return {
|
||||
"task_id": "", # 同步接口无 task_id,兼容旧接口
|
||||
"audio_url": audio_url,
|
||||
@@ -555,7 +517,6 @@ class CosyVoiceService:
|
||||
format: str = "",
|
||||
speed: float = 1.0,
|
||||
volume: int = 50,
|
||||
emotion: str = "",
|
||||
timeout: float = 120.0,
|
||||
) -> SynthesizeResult:
|
||||
"""语音合成(同步非流式).
|
||||
@@ -587,7 +548,6 @@ class CosyVoiceService:
|
||||
format=format,
|
||||
speed=speed,
|
||||
volume=volume,
|
||||
emotion=emotion,
|
||||
)
|
||||
|
||||
return SynthesizeResult(
|
||||
|
||||
@@ -143,16 +143,11 @@ class TTSWorkflowService:
|
||||
return self._start_segment_synthesis(job)
|
||||
|
||||
try:
|
||||
_meta = dict(job.metadata)
|
||||
_speed = float(_meta.get("speed", 1.0) or 1.0)
|
||||
_emotion = str(_meta.get("emotion", "") or "")
|
||||
submit_result = self.cosyvoice_service.submit_synthesize_task(
|
||||
text=job.input_text,
|
||||
voice_id=job.voice_id,
|
||||
sample_rate=job.sample_rate,
|
||||
format=job.format,
|
||||
speed=_speed,
|
||||
emotion=_emotion,
|
||||
)
|
||||
|
||||
# 保存 task_id / request_id 到 metadata
|
||||
@@ -288,7 +283,6 @@ class TTSWorkflowService:
|
||||
job_metadata = job.metadata or {}
|
||||
speed = float(job_metadata.get("speed", 1.0))
|
||||
volume = int(job_metadata.get("volume", 50))
|
||||
emotion = str(job_metadata.get("emotion", "") or "")
|
||||
|
||||
result = self.cosyvoice_service.submit_synthesize_task(
|
||||
text=job.input_text,
|
||||
@@ -297,7 +291,6 @@ class TTSWorkflowService:
|
||||
format=job.format,
|
||||
speed=speed,
|
||||
volume=volume,
|
||||
emotion=emotion,
|
||||
)
|
||||
audio_url = result.get("audio_url", "")
|
||||
if not audio_url:
|
||||
@@ -408,9 +401,6 @@ class TTSWorkflowService:
|
||||
"""
|
||||
max_workers = min(len(segments), _MAX_SEGMENT_WORKERS)
|
||||
results: list[dict | None] = [None] * len(segments)
|
||||
_seg_meta = job.metadata or {}
|
||||
_seg_speed = float(_seg_meta.get("speed", 1.0) or 1.0)
|
||||
_seg_emotion = str(_seg_meta.get("emotion", "") or "")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
future_to_idx = {}
|
||||
@@ -421,8 +411,6 @@ class TTSWorkflowService:
|
||||
voice_id=job.voice_id,
|
||||
sample_rate=job.sample_rate,
|
||||
format=job.format,
|
||||
speed=_seg_speed,
|
||||
emotion=_seg_emotion,
|
||||
)
|
||||
future_to_idx[future] = idx
|
||||
|
||||
@@ -512,7 +500,6 @@ class TTSWorkflowService:
|
||||
job_metadata = job.metadata or {}
|
||||
speed = float(job_metadata.get("speed", 1.0))
|
||||
volume = int(job_metadata.get("volume", 50))
|
||||
emotion = str(job_metadata.get("emotion", "") or "")
|
||||
|
||||
# 分段文本(用于缺失段重新合成)
|
||||
segments = split_text(job.input_text, max_chars=_SEGMENT_THRESHOLD)
|
||||
@@ -547,7 +534,6 @@ class TTSWorkflowService:
|
||||
format=job.format,
|
||||
speed=speed,
|
||||
volume=volume,
|
||||
emotion=emotion,
|
||||
)
|
||||
future_to_idx[future] = idx
|
||||
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI中自动修复代码格式(Python: black + isort + ruff | Frontend: prettier),并推送回原分支。
|
||||
"""CI中自动修复代码格式(Python: black + isort | Frontend: prettier),并推送回原分支。
|
||||
|
||||
- PR事件:所有PR只要Code Quality因格式问题失败,自动修复并push回源分支
|
||||
- Push事件(develop/main):自动修复并push回原分支,保持主干格式永远正确
|
||||
- 防循环:修复commit带 [skip ci-format-check] 标记,检测到该标记则跳过修复
|
||||
- black/isort/prettier 修格式;ruff check --fix --unsafe-fixes 自动修复
|
||||
ruff 可修复的 lint 规则(含 F401 未使用 import 等 unsafe fix)
|
||||
- ruff 目标范围与 validate_style.sh 的检查范围对齐:apps packages tests
|
||||
(alembic/scripts 不在 ruff 检查范围内,不做修复)
|
||||
- 只修格式(black/isort/prettier),ruff逻辑类错误不动
|
||||
当code quality检查因格式问题失败时触发。
|
||||
"""
|
||||
|
||||
@@ -138,7 +135,7 @@ def get_pr_head_branch(pr_number, api_url, token):
|
||||
|
||||
|
||||
def fix_python(target_py_files, scan_mode):
|
||||
"""修复 Python 文件 (black 格式化 + isort 排序 + ruff lint 自动修复)"""
|
||||
"""修复 Python 文件格式 (black + isort)"""
|
||||
if not target_py_files:
|
||||
print("没有需要修复的 Python 文件,跳过")
|
||||
return
|
||||
@@ -149,48 +146,14 @@ def fix_python(target_py_files, scan_mode):
|
||||
result = run(f"python3 -m black {target_str}", check=False)
|
||||
print(result.stdout[-500:] if result.stdout else "")
|
||||
if result.returncode != 0:
|
||||
print("black执行失败,但继续尝试isort/ruff", file=sys.stderr)
|
||||
print("black执行失败,但继续尝试isort", file=sys.stderr)
|
||||
|
||||
print()
|
||||
print("--- isort 排序 ---")
|
||||
result = run(f"python3 -m isort {target_str}", check=False)
|
||||
print(result.stdout[-500:] if result.stdout else "")
|
||||
if result.returncode != 0:
|
||||
print("isort执行失败,继续尝试ruff", file=sys.stderr)
|
||||
|
||||
# ruff lint 自动修复
|
||||
# 与 validate_style.sh 的检查范围对齐:只修 apps/packages/tests
|
||||
# (alembic 在 pyproject.toml 中被 exclude,scripts 不在 ruff 检查范围内)
|
||||
ruff_scopes = ("apps/", "packages/", "tests/")
|
||||
ruff_files = [f for f in target_py_files if f.startswith(ruff_scopes)]
|
||||
if scan_mode != "incremental":
|
||||
ruff_targets = "apps packages tests"
|
||||
elif ruff_files:
|
||||
ruff_targets = " ".join(ruff_files)
|
||||
else:
|
||||
ruff_targets = ""
|
||||
|
||||
if ruff_targets:
|
||||
# ruff 由 style job 的 requirements-dev.txt 安装;不可用时跳过(不阻断 black/isort 的修复)
|
||||
avail = run("python3 -m ruff --version", check=False)
|
||||
if avail.returncode != 0:
|
||||
print("ruff 不可用,跳过 ruff 自动修复", file=sys.stderr)
|
||||
else:
|
||||
print()
|
||||
print("--- ruff lint 自动修复 (--fix --unsafe-fixes) ---")
|
||||
# --unsafe-fixes 用于启用 F401(未使用 import)等 ruff 归类为 unsafe 的自动修复;
|
||||
# 安全性由修复后重跑的完整 CI(单测/构建/staging 健康检查)兜底
|
||||
result = run(
|
||||
f"python3 -m ruff check {ruff_targets} --fix --unsafe-fixes",
|
||||
check=False,
|
||||
)
|
||||
print(result.stdout[-1500:] if result.stdout else "")
|
||||
if result.returncode != 0:
|
||||
# 可能是仍有不可自动修复的 lint 错误(留待 style check 再次拦截),或修复过程出错
|
||||
print("ruff 自动修复后仍有未修复项或执行失败,剩余问题由 style check 继续拦截", file=sys.stderr)
|
||||
else:
|
||||
print()
|
||||
print("增量模式且无 apps/packages/tests 范围内的 Python 变更,跳过 ruff 自动修复")
|
||||
print("isort执行失败", file=sys.stderr)
|
||||
|
||||
|
||||
def fix_frontend(target_fe_files, scan_mode, repo_root):
|
||||
@@ -371,7 +334,7 @@ def main():
|
||||
# 提交修复
|
||||
run("git clean -fd")
|
||||
run("git add -u")
|
||||
run('git commit -m "style: auto-format with black + isort + ruff + prettier [skip ci-format-check]"')
|
||||
run('git commit -m "style: auto-format with black + isort + prettier [skip ci-format-check]"')
|
||||
|
||||
# 推送(head_branch已从ensure_git_repo获取)
|
||||
print(f"\nPR来源分支: {head_branch}")
|
||||
|
||||
@@ -1,365 +0,0 @@
|
||||
"""#1822 情绪/语速透传 + 对口型 TTS 直生 + 智能封面 单元测试.
|
||||
|
||||
CI 增量映射:
|
||||
cosyvoice_service.normalize_emotion / payload emotion
|
||||
lipsync_service TTS 直生分支(voice_id+script_text)
|
||||
ai_avatar_cover_service 智能选帧
|
||||
"""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("JWT_SECRET_KEY", "dev-secret-key-for-testing")
|
||||
|
||||
|
||||
# ── 情绪归一化 ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_normalize_emotion_english_values():
|
||||
from packages.application.cosyvoice_service import normalize_emotion
|
||||
|
||||
assert normalize_emotion("natural") == "natural"
|
||||
assert normalize_emotion("excited") == "excited"
|
||||
assert normalize_emotion("calm") == "calm"
|
||||
assert normalize_emotion("friendly") == "friendly"
|
||||
# 大小写 / 空白容错
|
||||
assert normalize_emotion(" Excited ") == "excited"
|
||||
|
||||
|
||||
def test_normalize_emotion_chinese_values():
|
||||
from packages.application.cosyvoice_service import normalize_emotion
|
||||
|
||||
assert normalize_emotion("自然") == "natural"
|
||||
assert normalize_emotion("兴奋") == "excited"
|
||||
assert normalize_emotion("沉稳") == "calm"
|
||||
assert normalize_emotion("亲切") == "friendly"
|
||||
|
||||
|
||||
def test_normalize_emotion_invalid_returns_empty():
|
||||
from packages.application.cosyvoice_service import normalize_emotion
|
||||
|
||||
assert normalize_emotion("") == ""
|
||||
assert normalize_emotion("angry") == ""
|
||||
assert normalize_emotion("喜怒哀乐") == ""
|
||||
|
||||
|
||||
# ── CosyVoice payload 携带 emotion + rate ──────────────────────────────
|
||||
|
||||
|
||||
def _make_service_with_captured_client(captured: dict):
|
||||
"""构造 CosyVoiceService,拦截 post 请求体到 captured['json']."""
|
||||
import httpx as _httpx
|
||||
|
||||
from packages.application import cosyvoice_service as mod
|
||||
|
||||
mock_client = MagicMock(spec=_httpx.Client)
|
||||
resp = MagicMock()
|
||||
resp.status_code = 200
|
||||
resp.json.return_value = {
|
||||
"request_id": "req-1",
|
||||
"output": {"audio": {"url": "https://tts/a.mp3", "duration": 1.0}},
|
||||
}
|
||||
resp.raise_for_status = MagicMock()
|
||||
|
||||
def fake_request(method, url, headers, json, timeout):
|
||||
captured["json"] = json
|
||||
return resp
|
||||
|
||||
mock_client.request.side_effect = fake_request
|
||||
|
||||
with patch.object(mod, "get_shared_settings") as settings_patch:
|
||||
s = MagicMock()
|
||||
s.cosyvoice_api_key = "sk-test"
|
||||
s.cosyvoice_base_url = "https://x/api/v1"
|
||||
s.cosyvoice_model = "cosyvoice-v3-flash"
|
||||
s.cosyvoice_clone_model = "voice-enrollment"
|
||||
s.cosyvoice_format = "mp3"
|
||||
s.cosyvoice_sample_rate = 22050
|
||||
s.cosyvoice_voice = "longxiaochun"
|
||||
settings_patch.return_value = s
|
||||
svc = mod.CosyVoiceService(http_client=mock_client)
|
||||
return svc
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_includes_emotion_and_rate():
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
svc.submit_synthesize_task(text="你好", voice_id="v-1", speed=1.5, emotion="兴奋")
|
||||
|
||||
inp = captured["json"]["input"]
|
||||
assert inp["emotion"] == "excited"
|
||||
assert inp["rate"] == 1.5
|
||||
|
||||
|
||||
def test_submit_synthesize_payload_omits_emotion_when_empty():
|
||||
captured: dict = {}
|
||||
svc = _make_service_with_captured_client(captured)
|
||||
|
||||
svc.submit_synthesize_task(text="你好", voice_id="v-1")
|
||||
|
||||
assert "emotion" not in captured["json"]["input"]
|
||||
|
||||
|
||||
# ── 对口型 TTS 直生分支 ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _lipsync_service_with_mocks():
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
db = MagicMock()
|
||||
client = MagicMock()
|
||||
client.is_available = True
|
||||
client.submit_lipsync.return_value = {
|
||||
"success": True,
|
||||
"task_id": "mk-1",
|
||||
"request_id": "req-1",
|
||||
}
|
||||
cosy = MagicMock()
|
||||
cosy.submit_synthesize_task.return_value = {
|
||||
"audio_url": "https://tts/raw.mp3",
|
||||
"request_id": "tts-req",
|
||||
"audio_duration": 3.0,
|
||||
}
|
||||
svc = LipsyncService(db, client=client, cosyvoice_service=cosy, voice_clone_repo=MagicMock())
|
||||
# _resolve_voice_id 默认原样返回(repo.get 返回 None)
|
||||
svc._voice_clone_repo.get.return_value = None
|
||||
return svc, client, cosy
|
||||
|
||||
|
||||
def test_create_job_tts_direct_mode_synthesizes_audio():
|
||||
svc, client, cosy = _lipsync_service_with_mocks()
|
||||
|
||||
with patch("app.services.lipsync_service.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-123")
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://oss/person.mp4",
|
||||
voice_id="cosy-v1",
|
||||
script_text="你好世界",
|
||||
speed=1.2,
|
||||
emotion="兴奋",
|
||||
)
|
||||
|
||||
# v4: TTS 模式下 create_job 返回 tts_processing 状态,dispatch Celery 任务
|
||||
assert job.status == "tts_processing"
|
||||
assert job.emotion == "excited"
|
||||
assert job.speed == 1.2
|
||||
# 不直接调用 CosyVoice(由 Celery 任务处理)
|
||||
cosy.submit_synthesize_task.assert_not_called()
|
||||
# 不直接提交 MediaKit(由 Celery 任务处理)
|
||||
client.submit_lipsync.assert_not_called()
|
||||
# dispatch 了 Celery 任务
|
||||
mock_task.apply_async.assert_called_once()
|
||||
|
||||
|
||||
def test_create_job_direct_audio_mode_skips_tts():
|
||||
svc, client, cosy = _lipsync_service_with_mocks()
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://oss/person.mp4",
|
||||
audio_url="https://oss/ready.mp3",
|
||||
)
|
||||
|
||||
cosy.submit_synthesize_task.assert_not_called()
|
||||
_, submit_kwargs = client.submit_lipsync.call_args
|
||||
assert submit_kwargs["audio_url"] == "https://oss/ready.mp3"
|
||||
|
||||
|
||||
def test_create_job_tts_failure_raises():
|
||||
"""v4: TTS 模式下 create_job 不再同步失败,而是 dispatch Celery 任务。
|
||||
TTS 合成失败由 Celery 任务内部处理并更新 job 状态。"""
|
||||
svc, client, cosy = _lipsync_service_with_mocks()
|
||||
|
||||
with patch("app.services.lipsync_service.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-456")
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://oss/person.mp4",
|
||||
voice_id="v-1",
|
||||
script_text="文本",
|
||||
)
|
||||
|
||||
# create_job 成功返回 tts_processing,不直接调用 TTS
|
||||
assert job.status == "tts_processing"
|
||||
cosy.submit_synthesize_task.assert_not_called()
|
||||
client.submit_lipsync.assert_not_called()
|
||||
mock_task.apply_async.assert_called_once()
|
||||
|
||||
|
||||
# ── refresh 同步中间状态 ────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_refresh_syncs_running_status():
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
db = MagicMock()
|
||||
client = MagicMock()
|
||||
client.get_task_status.return_value = {"success": True, "status": "running"}
|
||||
svc = LipsyncService(db, client=client)
|
||||
|
||||
job = MagicMock()
|
||||
job.status = "submitted"
|
||||
job.mediakit_task_id = "mk-1"
|
||||
job.id = "j-1"
|
||||
svc.get_job = MagicMock(return_value=job)
|
||||
|
||||
result = svc.refresh_job_status("j-1", "user-1")
|
||||
assert result.status == "running"
|
||||
|
||||
|
||||
# ── 智能封面 ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_smart_cover_selects_best_frame_and_persists():
|
||||
from app.services import ai_avatar_cover_service as cov
|
||||
|
||||
snapshots = [
|
||||
{"image_url": "https://mk/f0.jpg"},
|
||||
{"image_url": "https://mk/f1.jpg"},
|
||||
]
|
||||
with (
|
||||
patch("packages.shared.mediakit_client.get_mediakit_client") as mk_patch,
|
||||
patch("packages.shared.cover_frame_scorer.score_frames") as score_patch,
|
||||
patch("httpx.Client") as http_client_cls,
|
||||
patch("packages.shared.storage.get_shared_storage_service") as storage_patch,
|
||||
):
|
||||
mk = MagicMock()
|
||||
mk.is_available = True
|
||||
mk.extract_frames.return_value = snapshots
|
||||
mk_patch.return_value = mk
|
||||
# score_frames 把 f1 选为最佳
|
||||
score_patch.side_effect = lambda cands: [
|
||||
{"url": "https://mk/f1.jpg", "score": 90.0, "image_path": cands[1]["image_path"]},
|
||||
{"url": "https://mk/f0.jpg", "score": 60.0, "image_path": cands[0]["image_path"]},
|
||||
]
|
||||
# httpx.Client 连接池 mock
|
||||
client_instance = MagicMock()
|
||||
resp = MagicMock()
|
||||
resp.content = b"IMGDATA"
|
||||
resp.raise_for_status = MagicMock()
|
||||
client_instance.get.return_value = resp
|
||||
client_instance.__enter__ = MagicMock(return_value=client_instance)
|
||||
client_instance.__exit__ = MagicMock(return_value=False)
|
||||
http_client_cls.return_value = client_instance
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
# video_url 不是自家 OSS,不重签
|
||||
storage.get_download_url.side_effect = lambda url, **kw: f"{url}?signed=1"
|
||||
storage.upload_file.return_value = "https://oss.example.com/cover.jpg"
|
||||
storage_patch.return_value = storage
|
||||
|
||||
url = cov.generate_smart_cover("https://other-host/avatar.mp4", job_id="job-1")
|
||||
|
||||
assert "signed=1" in url or url == "https://oss.example.com/cover.jpg"
|
||||
mk.extract_frames.assert_called_once()
|
||||
score_patch.assert_called_once()
|
||||
# 验证使用了增大的轮询参数
|
||||
call_kwargs = mk.extract_frames.call_args
|
||||
assert call_kwargs.kwargs.get("poll_interval") == 3.0 or call_kwargs[1].get("poll_interval") == 3.0
|
||||
assert call_kwargs.kwargs.get("max_poll_attempts") == 20 or call_kwargs[1].get("max_poll_attempts") == 20
|
||||
|
||||
|
||||
def test_smart_cover_returns_empty_when_mediakit_unavailable():
|
||||
from app.services import ai_avatar_cover_service as cov
|
||||
|
||||
with (
|
||||
patch("packages.shared.mediakit_client.get_mediakit_client") as mk_patch,
|
||||
patch("packages.shared.storage.get_shared_storage_service") as storage_patch,
|
||||
):
|
||||
mk = MagicMock()
|
||||
mk.is_available = False
|
||||
mk_patch.return_value = mk
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage_patch.return_value = storage
|
||||
url = cov.generate_smart_cover("https://oss.example.com/avatar.mp4")
|
||||
assert url == ""
|
||||
|
||||
|
||||
def test_sign_video_url_resigns_own_oss_url():
|
||||
"""自家 OSS 私有桶 URL 应被重签为长有效期预签名 URL"""
|
||||
from app.services.ai_avatar_cover_service import _sign_video_url_for_mediakit
|
||||
|
||||
with patch("packages.shared.storage.get_shared_storage_service") as storage_patch:
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage.get_download_url.return_value = "https://oss.example.com/file.mp4?Expires=xxx&Signature=yyy"
|
||||
storage_patch.return_value = storage
|
||||
|
||||
result = _sign_video_url_for_mediakit("https://oss.example.com/file.mp4")
|
||||
|
||||
assert "Signature=yyy" in result
|
||||
storage.get_download_url.assert_called_once()
|
||||
|
||||
|
||||
def test_sign_video_url_skips_external_url():
|
||||
"""外部 URL(非自家 OSS)应原样返回,不做重签"""
|
||||
from app.services.ai_avatar_cover_service import _sign_video_url_for_mediakit
|
||||
|
||||
with patch("packages.shared.storage.get_shared_storage_service") as storage_patch:
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage_patch.return_value = storage
|
||||
|
||||
result = _sign_video_url_for_mediakit("https://external-cdn.com/video.mp4")
|
||||
|
||||
assert result == "https://external-cdn.com/video.mp4"
|
||||
storage.get_download_url.assert_not_called()
|
||||
|
||||
|
||||
def test_extract_frames_uses_extended_poll_params():
|
||||
"""验证 select_best_cover_frame 使用增大后的轮询参数"""
|
||||
from app.services import ai_avatar_cover_service as cov
|
||||
|
||||
with (
|
||||
patch("packages.shared.mediakit_client.get_mediakit_client") as mk_patch,
|
||||
patch("packages.shared.storage.get_shared_storage_service") as storage_patch,
|
||||
):
|
||||
mk = MagicMock()
|
||||
mk.is_available = True
|
||||
mk.extract_frames.return_value = [{"image_url": "https://mk/f0.jpg"}]
|
||||
mk_patch.return_value = mk
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage_patch.return_value = storage
|
||||
|
||||
cov.select_best_cover_frame("https://other/avatar.mp4", max_frames=3)
|
||||
|
||||
call_kwargs = mk.extract_frames.call_args
|
||||
assert call_kwargs.kwargs.get("poll_interval") == 3.0 or call_kwargs[1].get("poll_interval") == 3.0
|
||||
assert call_kwargs.kwargs.get("max_poll_attempts") == 20 or call_kwargs[1].get("max_poll_attempts") == 20
|
||||
assert call_kwargs.kwargs.get("max_retries") == 1 or call_kwargs[1].get("max_retries") == 1
|
||||
|
||||
|
||||
# ── 渲染 script_id 可选(手动文案直生场景)──────────────────────────────
|
||||
|
||||
|
||||
def test_render_request_script_id_optional():
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "apps", "api"))
|
||||
from app.schemas.ai_avatar_render import CreateAiAvatarRenderRequest
|
||||
|
||||
# 手动文案直生:不传 script_id 也合法
|
||||
req = CreateAiAvatarRenderRequest(lipsync_job_id="j-1")
|
||||
assert req.script_id == ""
|
||||
|
||||
# 空白被 strip
|
||||
req2 = CreateAiAvatarRenderRequest(lipsync_job_id="j-1", script_id=" ")
|
||||
assert req2.script_id == ""
|
||||
|
||||
# title_config 是单个 dict
|
||||
req3 = CreateAiAvatarRenderRequest(
|
||||
lipsync_job_id="j-1",
|
||||
title_config={"text": "标题", "position": "top", "font_size": 40},
|
||||
)
|
||||
assert req3.title_config["position"] == "top"
|
||||
@@ -176,23 +176,13 @@ class TestSchemaValidation:
|
||||
script_id="script-1",
|
||||
)
|
||||
|
||||
def test_create_request_empty_script_id_normalized(self):
|
||||
"""script_id 改为可选(TTS 直生场景):空白值应规范化为空串而非抛错。"""
|
||||
def test_create_request_empty_script_id(self):
|
||||
from app.schemas.ai_avatar_render import CreateAiAvatarRenderRequest
|
||||
|
||||
req = CreateAiAvatarRenderRequest(
|
||||
lipsync_job_id="lipsync-1",
|
||||
script_id=" ",
|
||||
)
|
||||
assert req.script_id == ""
|
||||
|
||||
def test_create_request_empty_lipsync_job_id_raises(self):
|
||||
from app.schemas.ai_avatar_render import CreateAiAvatarRenderRequest
|
||||
|
||||
with pytest.raises(ValueError, match="lipsync_job_id 不能为空"):
|
||||
with pytest.raises(ValueError, match="script_id 不能为空"):
|
||||
CreateAiAvatarRenderRequest(
|
||||
lipsync_job_id=" ",
|
||||
script_id="script-1",
|
||||
lipsync_job_id="lipsync-1",
|
||||
script_id=" ",
|
||||
)
|
||||
|
||||
|
||||
@@ -519,103 +509,6 @@ class TestAiAvatarRenderService:
|
||||
# 不应执行渲染逻辑
|
||||
mock_db.commit.assert_not_called()
|
||||
|
||||
def test_execute_render_success_creates_clip_record(self):
|
||||
"""execute_render 完成后自动创建成片记录到成片库."""
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderService
|
||||
|
||||
mock_db = _make_mock_db()
|
||||
mock_lipsync_job = _make_mock_lipsync_job(
|
||||
status="completed",
|
||||
output_video_url="https://oss/lipsync.mp4",
|
||||
output_duration=30.0,
|
||||
)
|
||||
mock_job = _make_mock_render_job(
|
||||
job_id="render-ok",
|
||||
status="pending",
|
||||
output_video_url="",
|
||||
output_cover_url="",
|
||||
output_duration=0.0,
|
||||
)
|
||||
mock_filter = MagicMock()
|
||||
mock_filter.first.side_effect = [mock_job, mock_lipsync_job]
|
||||
mock_query = MagicMock()
|
||||
mock_query.filter.return_value = mock_filter
|
||||
mock_db.query.return_value = mock_query
|
||||
|
||||
svc = AiAvatarRenderService(mock_db)
|
||||
|
||||
with (
|
||||
patch.object(svc, "_download_video", return_value="/tmp/video.mp4"),
|
||||
patch.object(svc, "_upload_to_oss", side_effect=lambda path, key: f"https://oss/{key}"),
|
||||
patch("os.system", return_value=0),
|
||||
patch("tempfile.TemporaryDirectory") as tmpdir_mock,
|
||||
patch(
|
||||
"app.services.ai_avatar_cover_service.generate_smart_cover", return_value="https://oss/smart_cover.jpg"
|
||||
),
|
||||
patch("packages.domain.generated_video.GeneratedVideo.create") as gv_create,
|
||||
patch(
|
||||
"packages.adapters.sqlalchemy_impl.generated_video_repository.SQLAlchemyGeneratedVideoRepository"
|
||||
) as repo_cls,
|
||||
):
|
||||
import tempfile as _tf
|
||||
|
||||
tmpdir_mock.return_value.__enter__ = MagicMock(return_value="/tmp/testdir")
|
||||
tmpdir_mock.return_value.__exit__ = MagicMock(return_value=False)
|
||||
|
||||
mock_clip = MagicMock()
|
||||
mock_clip.id = "clip-001"
|
||||
gv_create.return_value = mock_clip
|
||||
mock_repo = MagicMock()
|
||||
repo_cls.return_value = mock_repo
|
||||
|
||||
svc.execute_render("render-ok")
|
||||
|
||||
assert mock_job.status == "completed"
|
||||
gv_create.assert_called_once()
|
||||
call_kwargs = gv_create.call_args
|
||||
assert "https://oss/" in call_kwargs.kwargs["file_url"]
|
||||
assert call_kwargs.kwargs["user_id"] == "user-1"
|
||||
mock_repo.create.assert_called_once_with(mock_clip)
|
||||
|
||||
def test_execute_render_clip_failure_does_not_affect_render(self):
|
||||
"""成片创建失败不影响渲染任务标记为成功."""
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderService
|
||||
|
||||
mock_db = _make_mock_db()
|
||||
mock_lipsync_job = _make_mock_lipsync_job(
|
||||
status="completed",
|
||||
output_video_url="https://oss/lipsync.mp4",
|
||||
output_duration=30.0,
|
||||
)
|
||||
mock_job = _make_mock_render_job(
|
||||
job_id="render-clip-fail",
|
||||
status="pending",
|
||||
output_video_url="",
|
||||
output_cover_url="",
|
||||
output_duration=0.0,
|
||||
)
|
||||
mock_filter = MagicMock()
|
||||
mock_filter.first.side_effect = [mock_job, mock_lipsync_job]
|
||||
mock_query = MagicMock()
|
||||
mock_query.filter.return_value = mock_filter
|
||||
mock_db.query.return_value = mock_query
|
||||
|
||||
svc = AiAvatarRenderService(mock_db)
|
||||
|
||||
with (
|
||||
patch.object(svc, "_download_video", return_value="/tmp/video.mp4"),
|
||||
patch.object(svc, "_upload_to_oss", side_effect=lambda path, key: f"https://oss/{key}"),
|
||||
patch("os.system", return_value=0),
|
||||
patch("tempfile.TemporaryDirectory") as tmpdir_mock,
|
||||
patch("app.services.ai_avatar_cover_service.generate_smart_cover", side_effect=RuntimeError("DB error")),
|
||||
):
|
||||
tmpdir_mock.return_value.__enter__ = MagicMock(return_value="/tmp/testdir")
|
||||
tmpdir_mock.return_value.__exit__ = MagicMock(return_value=False)
|
||||
svc.execute_render("render-clip-fail")
|
||||
|
||||
# 即使成片创建失败,渲染任务仍应标记为 completed
|
||||
assert mock_job.status == "completed"
|
||||
|
||||
def test_error_exception_has_code(self):
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderError
|
||||
|
||||
|
||||
+104
-336
@@ -35,14 +35,14 @@ def mock_mediakit():
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cosyvoice():
|
||||
"""Mock CosyVoice 服务(v3: service 内部走 submit_synthesize_task,返回 dict)."""
|
||||
"""Mock CosyVoice 服务."""
|
||||
service = MagicMock()
|
||||
service.submit_synthesize_task.return_value = {
|
||||
"audio_url": "https://oss.example.com/tts-output.mp3",
|
||||
"request_id": "tts-req-789",
|
||||
}
|
||||
# synthesize_speech 保留给直接同步调用场景
|
||||
service.synthesize_speech.return_value = MagicMock(audio_url="https://oss.example.com/tts-output.mp3")
|
||||
service.synthesize_speech.return_value = MagicMock(
|
||||
audio_url="https://oss.example.com/tts-output.mp3",
|
||||
duration=15.0,
|
||||
file_size=12345,
|
||||
request_id="tts-req-789",
|
||||
)
|
||||
return service
|
||||
|
||||
|
||||
@@ -172,129 +172,103 @@ class TestSchemaValidation:
|
||||
)
|
||||
assert "?token=" in req.video_url
|
||||
|
||||
def test_dual_mode_fields_present(self):
|
||||
"""v3 契约: 双模式——支持直接音频 audio_url,也支持 TTS 直生 voice_id+script_text."""
|
||||
from app.schemas.lipsync import CreateLipsyncJobRequest
|
||||
|
||||
fields = CreateLipsyncJobRequest.model_fields.keys()
|
||||
# 直接音频模式
|
||||
assert "audio_url" in fields
|
||||
# TTS 直生模式
|
||||
assert "voice_id" in fields
|
||||
assert "script_text" in fields
|
||||
# 语速/情绪透传
|
||||
assert "speed" in fields
|
||||
assert "emotion" in fields
|
||||
|
||||
def test_direct_audio_mode_accepted(self):
|
||||
"""v3 契约: 只传 audio_url(直接音频模式)也合法,无需 voice_id/script_text."""
|
||||
def test_no_audio_url_in_request(self):
|
||||
"""#1809: 请求体不应包含 audio_url 字段."""
|
||||
from app.schemas.lipsync import CreateLipsyncJobRequest
|
||||
|
||||
req = CreateLipsyncJobRequest(
|
||||
video_url="https://example.com/video.mp4",
|
||||
audio_url="https://example.com/audio.mp3",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="测试文本",
|
||||
)
|
||||
assert req.audio_url == "https://example.com/audio.mp3"
|
||||
|
||||
def test_neither_mode_rejected(self):
|
||||
"""v3 契约: audio_url 与 voice_id+script_text 都缺时应报错."""
|
||||
from app.schemas.lipsync import CreateLipsyncJobRequest
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
CreateLipsyncJobRequest(video_url="https://example.com/video.mp4")
|
||||
assert not hasattr(req, "audio_url")
|
||||
fields = req.model_fields.keys()
|
||||
assert "audio_url" not in fields
|
||||
assert "voice_id" in fields
|
||||
assert "script_text" in fields
|
||||
|
||||
|
||||
class TestLipsyncServiceUnit:
|
||||
"""Service 层单元测试(纯 mock,不依赖数据库)— #1809 更新."""
|
||||
|
||||
def test_create_job_success(self, mock_mediakit, mock_cosyvoice):
|
||||
"""TTS 直生——v4 异步模式:create_job 只创建 DB 记录 + dispatch Celery 任务."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
mock_repo.get.return_value = None # 预置音色,原样返回 voice_id
|
||||
mock_db.add = MagicMock()
|
||||
mock_db.flush = MagicMock()
|
||||
mock_db.commit = MagicMock()
|
||||
mock_db.refresh = MagicMock()
|
||||
|
||||
with patch(
|
||||
"app.services.lipsync_service.tts_synthesize_and_submit"
|
||||
) as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-123")
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
voice_clone_repo=mock_repo,
|
||||
)
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="大家好,欢迎来到直播间",
|
||||
speed=1.2,
|
||||
emotion="兴奋",
|
||||
)
|
||||
|
||||
# TTS 模式:异步返回,状态为 tts_processing
|
||||
assert job.status == "tts_processing"
|
||||
assert not job.audio_url # TTS 音频尚未合成(默认空字符串)
|
||||
# 不直接调用 CosyVoice
|
||||
mock_cosyvoice.submit_synthesize_task.assert_not_called()
|
||||
# dispatch 了 Celery 任务
|
||||
mock_task.apply_async.assert_called_once()
|
||||
# job 记录透传字段
|
||||
assert job.speed == 1.2
|
||||
assert job.emotion == "excited"
|
||||
# MediaKit 尚未提交(由 Celery 任务处理)
|
||||
mock_mediakit.submit_lipsync.assert_not_called()
|
||||
|
||||
def test_create_job_tts_failure(self, mock_mediakit):
|
||||
"""v4: TTS 模式下 create_job 不再同步失败,而是 dispatch Celery 任务。
|
||||
TTS 合成失败由 Celery 任务内部处理(见 test_lipsync_speed_optimization.py)。"""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
mock_repo.get.return_value = None
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
voice_clone_repo=mock_repo,
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="大家好,欢迎来到直播间",
|
||||
)
|
||||
|
||||
with patch(
|
||||
"app.services.lipsync_service.tts_synthesize_and_submit"
|
||||
) as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-456")
|
||||
assert job.status == "submitted"
|
||||
assert job.mediakit_task_id == "mk-task-123"
|
||||
# TTS 应该被调用
|
||||
mock_cosyvoice.synthesize_speech.assert_called_once_with(
|
||||
text="大家好,欢迎来到直播间",
|
||||
voice_id="longxiaochun_v3",
|
||||
)
|
||||
# MediaKit 应该用 TTS 生成的 audio_url
|
||||
mock_mediakit.submit_lipsync.assert_called_once()
|
||||
call_kwargs = mock_mediakit.submit_lipsync.call_args
|
||||
assert call_kwargs.kwargs["audio_url"] == "https://oss.example.com/tts-output.mp3"
|
||||
|
||||
job = svc.create_job(
|
||||
def test_create_job_tts_failure(self, mock_mediakit):
|
||||
"""TTS 合成失败时,应创建 failed 记录并抛出 CosyVoiceError."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
from packages.application.cosyvoice_service import CosyVoiceError
|
||||
|
||||
mock_cosyvoice = MagicMock()
|
||||
mock_cosyvoice.synthesize_speech.side_effect = CosyVoiceError("TTS 服务不可用")
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_db.add = MagicMock()
|
||||
mock_db.flush = MagicMock()
|
||||
mock_db.commit = MagicMock()
|
||||
mock_db.refresh = MagicMock()
|
||||
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
with pytest.raises(CosyVoiceError, match="TTS 服务不可用"):
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="测试文本",
|
||||
)
|
||||
|
||||
# TTS 模式下 create_job 成功返回,状态为 tts_processing
|
||||
assert job.status == "tts_processing"
|
||||
# 不应提交到 MediaKit
|
||||
mock_mediakit.submit_lipsync.assert_not_called()
|
||||
mock_task.apply_async.assert_called_once()
|
||||
# 应该记录了失败状态
|
||||
added_job = mock_db.add.call_args[0][0]
|
||||
assert added_job.status == "failed"
|
||||
assert "TTS" in added_job.error_message
|
||||
|
||||
def test_create_job_api_failure(self, mock_mediakit):
|
||||
"""MediaKit 提交失败(直传音频模式同步触发)."""
|
||||
def test_create_job_api_failure(self, mock_mediakit, mock_cosyvoice):
|
||||
"""MediaKit 提交失败."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
mock_mediakit.submit_lipsync.side_effect = MediaKitError("API 调用失败", code="SubmitFailed")
|
||||
|
||||
mock_db = MagicMock()
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit)
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
with pytest.raises(MediaKitError, match="API 调用失败"):
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
audio_url="https://example.com/audio.mp3",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="测试文本",
|
||||
)
|
||||
|
||||
def test_get_job_delegates_to_db(self, mock_mediakit, mock_cosyvoice):
|
||||
@@ -425,284 +399,78 @@ class TestLipsyncServiceUnit:
|
||||
assert result.status == "completed"
|
||||
|
||||
def test_create_job_stores_tts_audio_url(self, mock_mediakit, mock_cosyvoice):
|
||||
"""v4: TTS 模式下 create_job 返回 tts_processing 状态,audio_url 尚未设置(由 Celery 任务处理)."""
|
||||
"""#1809: 验证 job 的 audio_url 来自 TTS 合成结果."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
mock_repo.get.return_value = None
|
||||
mock_db.add = MagicMock()
|
||||
mock_db.flush = MagicMock()
|
||||
mock_db.commit = MagicMock()
|
||||
mock_db.refresh = MagicMock()
|
||||
|
||||
with patch(
|
||||
"app.services.lipsync_service.tts_synthesize_and_submit"
|
||||
) as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-789")
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
voice_clone_repo=mock_repo,
|
||||
)
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="my-clone-voice",
|
||||
script_text="这是一段测试文本",
|
||||
)
|
||||
|
||||
# TTS 模式下 create_job 返回 tts_processing 状态
|
||||
assert job.status == "tts_processing"
|
||||
# audio_url 尚未设置(由 Celery 任务异步处理),模型默认为空字符串
|
||||
assert not job.audio_url
|
||||
mock_task.apply_async.assert_called_once()
|
||||
|
||||
def test_create_job_direct_audio_skips_tts(self, mock_mediakit, mock_cosyvoice):
|
||||
"""v3: 直接音频模式(传 audio_url)不触发 TTS,原样把 audio_url 提交 MediaKit."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
mock_db = MagicMock()
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
cosyvoice_service=mock_cosyvoice,
|
||||
voice_clone_repo=MagicMock(),
|
||||
)
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
audio_url="https://example.com/direct-audio.mp3",
|
||||
voice_id="my-clone-voice",
|
||||
script_text="这是一段测试文本",
|
||||
)
|
||||
|
||||
mock_cosyvoice.submit_synthesize_task.assert_not_called()
|
||||
call_kwargs = mock_mediakit.submit_lipsync.call_args
|
||||
assert call_kwargs.kwargs["audio_url"] == "https://example.com/direct-audio.mp3"
|
||||
assert job.audio_url == "https://example.com/direct-audio.mp3"
|
||||
# job.audio_url 应该是 TTS 返回的 URL
|
||||
assert job.audio_url == "https://oss.example.com/tts-output.mp3"
|
||||
|
||||
|
||||
class TestErrorHandling:
|
||||
"""v3: 音色解析与错误码在 service 层处理,路由层做 HTTP 状态码映射."""
|
||||
"""#1809 补充:错误返回 400 而非 500."""
|
||||
|
||||
def test_voice_id_resolve_forbidden(self, mock_mediakit, mock_cosyvoice):
|
||||
"""v3: 克隆音色属于他人时 service._resolve_voice_id 抛 VoiceForbidden(路由映射 403)."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
def test_voice_id_resolve_failure_returns_400(self, mock_mediakit, mock_cosyvoice):
|
||||
"""voice_clone_repo 查询异常时返回 400 而非 500."""
|
||||
from app.api.routes.lipsync import _resolve_voice_id
|
||||
from fastapi import HTTPException
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
other_profile = MagicMock()
|
||||
other_profile.user_id = "user-other"
|
||||
other_profile.voice_id = "cv-voice-1"
|
||||
mock_repo.get.return_value = other_profile
|
||||
mock_repo.get.side_effect = Exception("DB connection error")
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
cosyvoice_service=mock_cosyvoice,
|
||||
voice_clone_repo=mock_repo,
|
||||
)
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_resolve_voice_id("bad-voice-id", "user-1", mock_repo)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "voice_id" in str(exc_info.value.detail)
|
||||
|
||||
with pytest.raises(MediaKitError) as exc_info:
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="clone-profile-id",
|
||||
script_text="测试",
|
||||
)
|
||||
assert exc_info.value.code == "VoiceForbidden"
|
||||
mock_mediakit.submit_lipsync.assert_not_called()
|
||||
|
||||
def test_voice_id_resolve_not_ready(self, mock_mediakit, mock_cosyvoice):
|
||||
"""v3: 克隆音色尚未生成 voice_id 时抛 VoiceNotReady(路由映射 400)."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
profile = MagicMock()
|
||||
profile.user_id = "user-1"
|
||||
profile.voice_id = "" # 克隆未完成
|
||||
mock_repo.get.return_value = profile
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
cosyvoice_service=mock_cosyvoice,
|
||||
voice_clone_repo=mock_repo,
|
||||
)
|
||||
|
||||
with pytest.raises(MediaKitError) as exc_info:
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="clone-profile-id",
|
||||
script_text="测试",
|
||||
)
|
||||
assert exc_info.value.code == "VoiceNotReady"
|
||||
|
||||
def test_tts_value_error_mapped_to_invalid_param(self, mock_mediakit):
|
||||
"""v4: TTS 模式下 create_job 不再同步调用 CosyVoice,
|
||||
而是 dispatch Celery 任务。ValueError 由 Celery 任务内部处理。"""
|
||||
def test_create_job_value_error_returns_400(self, mock_mediakit):
|
||||
"""ValueError(参数无效)返回 400 而非 500."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
mock_cosyvoice = MagicMock()
|
||||
mock_cosyvoice.submit_synthesize_task.side_effect = ValueError("voice_id 为空")
|
||||
mock_cosyvoice.synthesize_speech.side_effect = ValueError("voice_id 为空")
|
||||
|
||||
mock_db = MagicMock()
|
||||
mock_repo = MagicMock()
|
||||
mock_repo.get.return_value = None
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
voice_clone_repo=mock_repo,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"app.services.lipsync_service.tts_synthesize_and_submit"
|
||||
) as mock_task:
|
||||
mock_task.apply_async.return_value = MagicMock(id="celery-task-789")
|
||||
|
||||
# TTS 模式下 create_job 不再同步失败
|
||||
job = svc.create_job(
|
||||
# Service 层会 catch CosyVoiceError 但 ValueError 会穿透
|
||||
# 路由层 catch ValueError → 400
|
||||
with pytest.raises(ValueError):
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="some-voice",
|
||||
voice_id="",
|
||||
script_text="test",
|
||||
)
|
||||
|
||||
# 确认返回 tts_processing 状态
|
||||
assert job.status == "tts_processing"
|
||||
# TTS 合成由 Celery 任务处理,不直接调用 CosyVoice
|
||||
mock_cosyvoice.submit_synthesize_task.assert_not_called()
|
||||
mock_task.apply_async.assert_called_once()
|
||||
|
||||
def test_missing_both_inputs_raises_invalid_input(self, mock_mediakit, mock_cosyvoice):
|
||||
"""v3: 既无 audio_url 又无 voice_id+script_text 时抛 InvalidInput(路由映射 400)."""
|
||||
def test_create_job_unexpected_exception_returns_400(self, mock_mediakit):
|
||||
"""未预期的异常应被路由层捕获返回 400 而非 500."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
mock_cosyvoice = MagicMock()
|
||||
mock_cosyvoice.synthesize_speech.side_effect = RuntimeError("unexpected")
|
||||
|
||||
mock_db = MagicMock()
|
||||
svc = LipsyncService(
|
||||
mock_db,
|
||||
client=mock_mediakit,
|
||||
cosyvoice_service=mock_cosyvoice,
|
||||
voice_clone_repo=MagicMock(),
|
||||
)
|
||||
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
|
||||
|
||||
with pytest.raises(MediaKitError) as exc_info:
|
||||
with pytest.raises(RuntimeError):
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="test-voice",
|
||||
script_text="test",
|
||||
)
|
||||
assert exc_info.value.code == "InvalidInput"
|
||||
mock_cosyvoice.submit_synthesize_task.assert_not_called()
|
||||
mock_mediakit.submit_lipsync.assert_not_called()
|
||||
|
||||
|
||||
class TestSignMediaUrl403Fix:
|
||||
"""#1839 私有桶 OSS URL 重签:MediaKit GPU worker 拉取裸/过期 URL 会 403.
|
||||
|
||||
- 自家 OSS 的裸 public_url / 已过期短预签名 → 重签 7 天长有效期
|
||||
- 外部临时 URL(CosyVoice/MediaKit)→ 原样透传
|
||||
- 签名异常 → 降级原 URL,不阻断
|
||||
"""
|
||||
|
||||
OSS_PUBLIC_BASE = "https://xiaoxia-autocut.oss-cn-hangzhou.aliyuncs.com"
|
||||
|
||||
def _svc(self, mock_mediakit, mock_cosyvoice):
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
return LipsyncService(
|
||||
MagicMock(),
|
||||
client=mock_mediakit,
|
||||
cosyvoice_service=mock_cosyvoice,
|
||||
voice_clone_repo=MagicMock(),
|
||||
)
|
||||
|
||||
def test_own_oss_unsigned_url_gets_resigned(self, mock_mediakit, mock_cosyvoice):
|
||||
"""裸 public_url(不带签名,私有桶匿名 403)必须被重签."""
|
||||
from app.services.lipsync_service import MEDIAKIT_URL_TTL_SECONDS
|
||||
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
raw = f"{self.OSS_PUBLIC_BASE}/lipsync-tts/user-1/audio.mp3"
|
||||
signed = raw + "?Expires=999&Signature=abc&OSSAccessKeyId=key"
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = self.OSS_PUBLIC_BASE
|
||||
storage.get_download_url.return_value = signed
|
||||
with patch("app.services.lipsync_service.get_shared_storage_service", return_value=storage):
|
||||
out = svc._sign_media_url(raw)
|
||||
|
||||
assert out == signed
|
||||
storage.get_download_url.assert_called_once_with(raw, expires_seconds=MEDIAKIT_URL_TTL_SECONDS)
|
||||
assert MEDIAKIT_URL_TTL_SECONDS == 7 * 24 * 3600
|
||||
|
||||
def test_own_oss_expired_presign_gets_resigned(self, mock_mediakit, mock_cosyvoice):
|
||||
"""已带过期签名的旧预签名 URL 也要抽 key 后重签(不把旧 query 带进新签名)."""
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
old = f"{self.OSS_PUBLIC_BASE}/avatar/video.mp4?Expires=111&Signature=old"
|
||||
fresh = f"{self.OSS_PUBLIC_BASE}/avatar/video.mp4?Expires=999&Signature=fresh"
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = self.OSS_PUBLIC_BASE
|
||||
storage.get_download_url.return_value = fresh
|
||||
with patch("app.services.lipsync_service.get_shared_storage_service", return_value=storage):
|
||||
out = svc._sign_media_url(old)
|
||||
|
||||
assert out == fresh
|
||||
# 传给 get_download_url 的是原始完整 URL(内部抽 key),有效期 7 天
|
||||
called_url = storage.get_download_url.call_args.args[0]
|
||||
assert called_url == old
|
||||
|
||||
def test_external_url_passthrough(self, mock_mediakit, mock_cosyvoice):
|
||||
"""CosyVoice/MediaKit 外部临时链接不处理,原样透传."""
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
external = "https://cv-tts.cosyvoice.aliyuncs.com/output/x.mp3"
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = self.OSS_PUBLIC_BASE
|
||||
with patch("app.services.lipsync_service.get_shared_storage_service", return_value=storage):
|
||||
out = svc._sign_media_url(external)
|
||||
|
||||
assert out == external
|
||||
storage.get_download_url.assert_not_called()
|
||||
|
||||
def test_empty_url_returns_empty(self, mock_mediakit, mock_cosyvoice):
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
assert svc._sign_media_url("") == ""
|
||||
|
||||
def test_sign_error_falls_back_to_raw(self, mock_mediakit, mock_cosyvoice):
|
||||
"""签名抛异常时降级返回原 URL,不阻断对口型提交."""
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
raw = f"{self.OSS_PUBLIC_BASE}/lipsync-tts/u/a.mp3"
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = self.OSS_PUBLIC_BASE
|
||||
storage.get_download_url.side_effect = RuntimeError("oss down")
|
||||
with patch("app.services.lipsync_service.get_shared_storage_service", return_value=storage):
|
||||
out = svc._sign_media_url(raw)
|
||||
|
||||
assert out == raw
|
||||
|
||||
def test_create_job_resigns_oss_urls_before_submit(self, mock_mediakit, mock_cosyvoice):
|
||||
"""端到端:create_job 提交 MediaKit 前,自家 OSS 的 video_url 必须是重签后的长签名 URL."""
|
||||
svc = self._svc(mock_mediakit, mock_cosyvoice)
|
||||
raw_video = f"{self.OSS_PUBLIC_BASE}/avatar/person.mp4"
|
||||
signed_video = raw_video + "?Expires=999&Signature=fresh"
|
||||
raw_audio = f"{self.OSS_PUBLIC_BASE}/direct/audio.mp3"
|
||||
signed_audio = raw_audio + "?Expires=999&Signature=afresh"
|
||||
|
||||
storage = MagicMock()
|
||||
storage.public_url = self.OSS_PUBLIC_BASE
|
||||
storage.get_download_url.side_effect = lambda u, expires_seconds=0: (
|
||||
signed_video if u == raw_video else signed_audio
|
||||
)
|
||||
with patch("app.services.lipsync_service.get_shared_storage_service", return_value=storage):
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url=raw_video,
|
||||
audio_url=raw_audio,
|
||||
)
|
||||
|
||||
kw = mock_mediakit.submit_lipsync.call_args.kwargs
|
||||
assert kw["video_url"] == signed_video
|
||||
assert kw["audio_url"] == signed_audio
|
||||
|
||||
@@ -1,623 +0,0 @@
|
||||
"""AI 数字人口型视频生成速度优化 — 单元测试.
|
||||
|
||||
验证两个优化点:
|
||||
1. FFmpeg 编码 preset 从 fast 改为 veryfast(提速 30~50%)
|
||||
2. TTS 合成从同步改为 Celery 异步任务(API 响应从 6~35s 降到 <1s)
|
||||
|
||||
Issue: lipsync-speed-optimization
|
||||
"""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("JWT_SECRET_KEY", "dev-secret-key-for-testing")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# 优化1: FFmpeg 编码提速 — preset veryfast
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestFFmpegPresetOptimization:
|
||||
"""验证 FFmpeg 编码命令从 -preset fast 改为 -preset veryfast."""
|
||||
|
||||
def test_preset_is_veryfast(self):
|
||||
"""_build_ffmpeg_command 输出必须包含 -preset veryfast."""
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderService
|
||||
|
||||
svc = AiAvatarRenderService.__new__(AiAvatarRenderService)
|
||||
cmd = svc._build_ffmpeg_command(
|
||||
input_video="https://example.com/video.mp4",
|
||||
b_roll_segments=[],
|
||||
filter_complex="",
|
||||
final_label=None,
|
||||
output_path="/tmp/output.mp4",
|
||||
)
|
||||
assert "-preset veryfast" in cmd, f"期望 -preset veryfast,实际命令: {cmd}"
|
||||
|
||||
def test_preset_veryfast_with_filter(self):
|
||||
"""带滤镜场景下也必须使用 veryfast."""
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderService
|
||||
|
||||
svc = AiAvatarRenderService.__new__(AiAvatarRenderService)
|
||||
cmd = svc._build_ffmpeg_command(
|
||||
input_video="https://example.com/video.mp4",
|
||||
b_roll_segments=[],
|
||||
filter_complex="overlay=0:0",
|
||||
final_label="[v]",
|
||||
output_path="/tmp/output.mp4",
|
||||
)
|
||||
assert "-preset veryfast" in cmd
|
||||
assert "-filter_complex" in cmd
|
||||
|
||||
def test_preset_not_fast(self):
|
||||
"""确保不再使用旧的 -preset fast."""
|
||||
from app.services.ai_avatar_render_service import AiAvatarRenderService
|
||||
|
||||
svc = AiAvatarRenderService.__new__(AiAvatarRenderService)
|
||||
cmd = svc._build_ffmpeg_command(
|
||||
input_video="https://example.com/video.mp4",
|
||||
b_roll_segments=[],
|
||||
filter_complex="",
|
||||
final_label=None,
|
||||
output_path="/tmp/output.mp4",
|
||||
)
|
||||
# 确保是 veryfast 而不是 fast
|
||||
assert "-preset veryfast" in cmd
|
||||
# 排除 "fast" 单独出现(veryfast 包含 fast 子串,需精确判断)
|
||||
parts = cmd.split()
|
||||
preset_idx = parts.index("-preset")
|
||||
assert parts[preset_idx + 1] == "veryfast"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# 优化2: TTS 合成 Celery 异步化
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
def _make_service_with_mocks():
|
||||
"""构造 LipsyncService 测试实例及 mock 依赖."""
|
||||
from app.services.lipsync_service import LipsyncService
|
||||
|
||||
db = MagicMock()
|
||||
client = MagicMock()
|
||||
client.is_available = True
|
||||
client.submit_lipsync.return_value = {
|
||||
"success": True,
|
||||
"task_id": "mk-1",
|
||||
"request_id": "req-1",
|
||||
}
|
||||
cosy = MagicMock()
|
||||
cosy.submit_synthesize_task.return_value = {
|
||||
"audio_url": "https://tts/raw.mp3",
|
||||
"request_id": "tts-req",
|
||||
"audio_duration": 3.0,
|
||||
}
|
||||
svc = LipsyncService(db, client=client, cosyvoice_service=cosy, voice_clone_repo=MagicMock())
|
||||
# _resolve_voice_id 默认原样返回(repo.get 返回 None)
|
||||
svc._voice_clone_repo.get.return_value = None
|
||||
return svc, client, cosy
|
||||
|
||||
|
||||
class TestCreateJobAsyncTTS:
|
||||
"""验证 TTS 模式改为 Celery 异步后的行为."""
|
||||
|
||||
def test_tts_mode_returns_tts_processing_status(self):
|
||||
"""TTS 模式下 create_job 立即返回,状态为 tts_processing."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
with patch("app.services.lipsync_service.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.apply_async = MagicMock()
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="longxiaochun_v3",
|
||||
script_text="大家好",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
)
|
||||
|
||||
assert job.status == "tts_processing"
|
||||
|
||||
def test_tts_mode_dispatches_celery_task(self):
|
||||
"""TTS 模式必须 dispatch Celery 异步任务."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
with patch("app.services.lipsync_service.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.apply_async = MagicMock()
|
||||
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="v-1",
|
||||
script_text="测试文本",
|
||||
)
|
||||
|
||||
mock_task.apply_async.assert_called_once()
|
||||
call_kwargs = mock_task.apply_async.call_args
|
||||
args = call_kwargs.kwargs.get("args") or call_kwargs[1].get("args", call_kwargs[0][0] if call_kwargs[0] else ())
|
||||
assert args[1] == "user-1" # user_id
|
||||
assert args[2] == "v-1" # voice_id
|
||||
assert args[3] == "测试文本" # script_text
|
||||
|
||||
def test_tts_mode_celery_dispatch_failure_still_creates_job(self):
|
||||
"""Celery dispatch 失败时,job 记录已创建,状态保持 tts_processing."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
with patch("app.services.lipsync_service.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.apply_async = MagicMock(side_effect=Exception("Celery broker down"))
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="v-1",
|
||||
script_text="测试文本",
|
||||
)
|
||||
|
||||
# job 已创建
|
||||
assert job is not None
|
||||
assert job.status == "tts_processing"
|
||||
# MediaKit 未被调用
|
||||
client.submit_lipsync.assert_not_called()
|
||||
|
||||
def test_tts_mode_voice_validation_still_sync(self):
|
||||
"""TTS 模式下音色校验仍在 HTTP 请求中同步执行."""
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
# 模拟音色属于其他用户
|
||||
other_profile = MagicMock()
|
||||
other_profile.user_id = "user-other"
|
||||
svc._voice_clone_repo.get.return_value = other_profile
|
||||
|
||||
with patch("app.tasks.lipsync_tts.tts_synthesize_and_submit"):
|
||||
with pytest.raises(MediaKitError) as exc:
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
voice_id="clone-profile-id",
|
||||
script_text="测试",
|
||||
)
|
||||
assert exc.value.code == "VoiceForbidden"
|
||||
|
||||
def test_tts_mode_missing_input_raises_immediately(self):
|
||||
"""缺少 voice_id 或 script_text 时立即报错,不 dispatch Celery 任务."""
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
with patch("app.tasks.lipsync_tts.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.delay = MagicMock()
|
||||
|
||||
with pytest.raises(MediaKitError) as exc:
|
||||
svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
# 缺少 voice_id 和 script_text
|
||||
)
|
||||
assert exc.value.code == "InvalidInput"
|
||||
|
||||
# Celery 任务未被 dispatch
|
||||
mock_task.delay.assert_not_called()
|
||||
# TTS 和 MediaKit 均未调用
|
||||
cosy.submit_synthesize_task.assert_not_called()
|
||||
client.submit_lipsync.assert_not_called()
|
||||
|
||||
|
||||
class TestCreateJobDirectAudio:
|
||||
"""验证直接音频模式不受异步化影响."""
|
||||
|
||||
def test_direct_audio_still_submits_synchronously(self):
|
||||
"""直接音频模式仍然同步提交 MediaKit,状态为 submitted."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
with patch("app.tasks.lipsync_tts.tts_synthesize_and_submit") as mock_task:
|
||||
mock_task.delay = MagicMock()
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
audio_url="https://example.com/audio.mp3",
|
||||
)
|
||||
|
||||
assert job.status == "submitted"
|
||||
assert job.mediakit_task_id == "mk-1"
|
||||
client.submit_lipsync.assert_called_once()
|
||||
# TTS Celery 任务不应被调用
|
||||
mock_task.delay.assert_not_called()
|
||||
|
||||
def test_direct_audio_skips_tts(self):
|
||||
"""直接音频模式不调用 CosyVoice TTS."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
job = svc.create_job(
|
||||
user_id="user-1",
|
||||
video_url="https://example.com/video.mp4",
|
||||
audio_url="https://example.com/audio.mp3",
|
||||
)
|
||||
|
||||
cosy.submit_synthesize_task.assert_not_called()
|
||||
call_kwargs = client.submit_lipsync.call_args
|
||||
assert call_kwargs.kwargs["audio_url"] == "https://example.com/audio.mp3"
|
||||
|
||||
|
||||
class TestCancelJobTtsProcessing:
|
||||
"""验证 tts_processing 状态的任务可以被取消."""
|
||||
|
||||
def test_cancel_tts_processing(self):
|
||||
"""tts_processing 状态的任务可以成功取消."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.status = "tts_processing"
|
||||
mock_job.id = "job-1"
|
||||
svc.get_job = MagicMock(return_value=mock_job)
|
||||
|
||||
result = svc.cancel_job("job-1", "user-1")
|
||||
assert result.status == "cancelled"
|
||||
|
||||
def test_cancel_pending_still_works(self):
|
||||
"""pending 状态仍可取消."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.status = "pending"
|
||||
mock_job.id = "job-1"
|
||||
svc.get_job = MagicMock(return_value=mock_job)
|
||||
|
||||
result = svc.cancel_job("job-1", "user-1")
|
||||
assert result.status == "cancelled"
|
||||
|
||||
def test_cancel_submitted_still_works(self):
|
||||
"""submitted 状态仍可取消."""
|
||||
svc, client, cosy = _make_service_with_mocks()
|
||||
|
||||
mock_job = MagicMock()
|
||||
mock_job.status = "submitted"
|
||||
mock_job.id = "job-1"
|
||||
svc.get_job = MagicMock(return_value=mock_job)
|
||||
|
||||
result = svc.cancel_job("job-1", "user-1")
|
||||
assert result.status == "cancelled"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# lipsync_tts.py — Celery 异步任务单元测试
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
|
||||
class _FakeQuery:
|
||||
"""模拟 SQLAlchemy query.filter().first() 链式调用."""
|
||||
|
||||
def __init__(self, job):
|
||||
self._job = job
|
||||
|
||||
def filter(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._job
|
||||
|
||||
|
||||
def _make_fake_job(**kwargs):
|
||||
"""构造可 setattr 的 job 记录."""
|
||||
job = MagicMock()
|
||||
job.id = kwargs.get("job_id", "job-1")
|
||||
job.user_id = kwargs.get("user_id", "user-1")
|
||||
job.status = kwargs.get("status", "tts_processing")
|
||||
job.audio_url = kwargs.get("audio_url", "")
|
||||
job.video_url = kwargs.get("video_url", "https://oss/video.mp4")
|
||||
job.mediakit_task_id = kwargs.get("mediakit_task_id", "")
|
||||
job.enable_video_loop = kwargs.get("enable_video_loop", False)
|
||||
job.error_code = ""
|
||||
job.error_message = ""
|
||||
job.submitted_at = None
|
||||
job.updated_at = None
|
||||
return job
|
||||
|
||||
|
||||
def _build_session(job):
|
||||
"""构造 mock DB session + factory. 返回 (session, factory_patch_ctx_value)."""
|
||||
session = MagicMock()
|
||||
session.query.return_value = _FakeQuery(job)
|
||||
session.commit = MagicMock()
|
||||
session.close = MagicMock()
|
||||
factory = MagicMock(return_value=session)
|
||||
return session, factory
|
||||
|
||||
|
||||
def _apply_all_patches(
|
||||
*,
|
||||
job=None,
|
||||
cosyvoice_service=None,
|
||||
cosyvoice_side_effect=None,
|
||||
cosyvoice_error=None,
|
||||
download_bytes=b"AUDIO",
|
||||
download_error=None,
|
||||
storage=None,
|
||||
mk_client=None,
|
||||
mk_submit_return=None,
|
||||
mk_submit_error=None,
|
||||
):
|
||||
"""统一构造测试需要的 patch 列表.
|
||||
|
||||
lipsync_tts.run() 在函数体内部懒 import 多个模块,通过 sys.modules 注入
|
||||
伪造包路径避免真实导入;对存在的模块用 patch() 替换返回值/side_effect。
|
||||
"""
|
||||
# 构造不存在的 database 模块
|
||||
fake_db_mod = types.ModuleType("packages.adapters.sqlalchemy_impl.database")
|
||||
session, factory = _build_session(job)
|
||||
fake_db_mod.SessionLocal = factory
|
||||
|
||||
patches = [
|
||||
patch.dict(sys.modules, {"packages.adapters.sqlalchemy_impl.database": fake_db_mod}),
|
||||
patch(
|
||||
"app.services.lipsync_service.LipsyncService._sign_media_url",
|
||||
side_effect=lambda url: url + "?signed" if url else url,
|
||||
),
|
||||
]
|
||||
|
||||
# CosyVoice
|
||||
if cosyvoice_service is not None:
|
||||
cosy_instance = cosyvoice_service
|
||||
else:
|
||||
cosy_instance = MagicMock()
|
||||
if cosyvoice_side_effect is not None:
|
||||
cosy_instance.submit_synthesize_task.side_effect = cosyvoice_side_effect
|
||||
elif cosyvoice_error is not None:
|
||||
cosy_instance.submit_synthesize_task.side_effect = cosyvoice_error
|
||||
else:
|
||||
cosy_instance.submit_synthesize_task.return_value = {"audio_url": "https://tts/raw.mp3"}
|
||||
patches.append(patch("packages.application.cosyvoice_service.CosyVoiceService", return_value=cosy_instance))
|
||||
|
||||
# safe_download_bytes
|
||||
if download_error is not None:
|
||||
patches.append(patch("packages.shared.url_security.safe_download_bytes", side_effect=download_error))
|
||||
else:
|
||||
patches.append(patch("packages.shared.url_security.safe_download_bytes", return_value=download_bytes))
|
||||
|
||||
# Storage
|
||||
if storage is None:
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage.upload_file.return_value = "https://oss.example.com/tts.mp3"
|
||||
patches.append(patch("packages.shared.storage.get_shared_storage_service", return_value=storage))
|
||||
|
||||
# MediaKit client
|
||||
if mk_client is not None:
|
||||
patches.append(patch("app.services.mediakit_client.get_mediakit_client", return_value=mk_client))
|
||||
else:
|
||||
client = MagicMock()
|
||||
if mk_submit_error is not None:
|
||||
client.submit_lipsync.side_effect = mk_submit_error
|
||||
else:
|
||||
client.submit_lipsync.return_value = mk_submit_return or {"task_id": "mk-1"}
|
||||
patches.append(patch("app.services.mediakit_client.get_mediakit_client", return_value=client))
|
||||
|
||||
return session, patches
|
||||
|
||||
|
||||
class TestTtsSynthesizeAndSubmit:
|
||||
"""测试 Celery 任务 tts_synthesize_and_submit.run 的所有分支."""
|
||||
|
||||
def test_job_not_found_returns_early(self):
|
||||
"""Job 不存在 → 日志报错直接返回,不抛异常."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
session, patches = _apply_all_patches(job=None)
|
||||
entered = [p.__enter__() for p in patches]
|
||||
try:
|
||||
tts_synthesize_and_submit.run("missing-job", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
session.commit.assert_not_called()
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_cancelled_job_skipped(self):
|
||||
"""Job 已 cancelled → 跳过不处理,不调用 TTS/MediaKit."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="cancelled")
|
||||
session, patches = _apply_all_patches(job=job)
|
||||
entered = [p.__enter__() for p in patches]
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
session.commit.assert_not_called()
|
||||
session.close.assert_called_once()
|
||||
assert job.status == "cancelled"
|
||||
|
||||
def test_happy_path_tts_to_mediakit(self):
|
||||
"""正常流程:TTS 合成 → 下载 → OSS → 签名 → 提交 MediaKit → submitted."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage.upload_file.return_value = "https://oss.example.com/lipsync-tts/u/j.mp3"
|
||||
|
||||
session, patches = _apply_all_patches(
|
||||
job=job,
|
||||
storage=storage,
|
||||
mk_submit_return={"task_id": "mk-999"},
|
||||
)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.audio_url == "https://oss.example.com/lipsync-tts/u/j.mp3"
|
||||
assert job.mediakit_task_id == "mk-999"
|
||||
assert job.status == "submitted"
|
||||
assert job.submitted_at is not None
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_tts_cosyvoice_error_marks_failed(self):
|
||||
"""CosyVoiceError → 标记 failed,error_code=TTSSynthesisFailed."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
from packages.application.cosyvoice_service import CosyVoiceError
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
session, patches = _apply_all_patches(
|
||||
job=job,
|
||||
cosyvoice_error=CosyVoiceError("TTS 服务异常"),
|
||||
)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_code == "TTSSynthesisFailed"
|
||||
assert "TTS 合成失败" in job.error_message
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_tts_value_error_marks_failed(self):
|
||||
"""ValueError → 标记 failed,error_code=TTSInvalidParam."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
session, patches = _apply_all_patches(
|
||||
job=job,
|
||||
cosyvoice_error=ValueError("speed 参数非法"),
|
||||
)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_code == "TTSInvalidParam"
|
||||
assert "TTS 参数错误" in job.error_message
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_tts_no_audio_url_marks_failed(self):
|
||||
"""TTS 返回空 audio_url → 标记 failed,error_code=TTSNoAudio."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
cosy = MagicMock()
|
||||
cosy.submit_synthesize_task.return_value = {"audio_url": ""}
|
||||
session, patches = _apply_all_patches(job=job, cosyvoice_service=cosy)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_code == "TTSNoAudio"
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_oss_upload_failure_falls_back_to_temp_url(self):
|
||||
"""OSS 上传失败 → 回退临时 URL,继续提交 MediaKit."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
storage = MagicMock()
|
||||
storage.public_url = "https://oss.example.com"
|
||||
storage.upload_file.side_effect = Exception("OSS 上传超时")
|
||||
session, patches = _apply_all_patches(
|
||||
job=job,
|
||||
storage=storage,
|
||||
mk_submit_return={"task_id": "mk-77"},
|
||||
)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
# 回退到临时 URL
|
||||
assert job.audio_url == "https://tts/raw.mp3"
|
||||
assert job.status == "submitted"
|
||||
assert job.mediakit_task_id == "mk-77"
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_mediakit_submit_failure_marks_failed(self):
|
||||
"""MediaKit 提交失败(MediaKitError)→ 标记 failed."""
|
||||
from app.services.mediakit_client import MediaKitError
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
err = MediaKitError("GPU 不可用", code="MediaKitUnavailable")
|
||||
session, patches = _apply_all_patches(
|
||||
job=job,
|
||||
mk_submit_error=err,
|
||||
)
|
||||
for p in patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_code == "MediaKitUnavailable"
|
||||
session.close.assert_called_once()
|
||||
|
||||
def test_top_level_exception_marks_async_task_error(self):
|
||||
"""顶层意外异常 → except 分支回写 failed,error_code=AsyncTaskError."""
|
||||
from app.tasks.lipsync_tts import tts_synthesize_and_submit
|
||||
|
||||
job = _make_fake_job(status="tts_processing")
|
||||
# 不调用 _apply_all_patches,手动构造所有 patch,让 CosyVoiceService 抛异常
|
||||
fake_db_mod = types.ModuleType("packages.adapters.sqlalchemy_impl.database")
|
||||
session_mock = MagicMock()
|
||||
session_mock.query.return_value = _FakeQuery(job)
|
||||
session_mock.commit = MagicMock()
|
||||
session_mock.close = MagicMock()
|
||||
fake_db_mod.SessionLocal = MagicMock(return_value=session_mock)
|
||||
|
||||
all_patches = [
|
||||
patch.dict(sys.modules, {"packages.adapters.sqlalchemy_impl.database": fake_db_mod}),
|
||||
patch(
|
||||
"app.services.lipsync_service.LipsyncService._sign_media_url",
|
||||
side_effect=lambda url: url + "?signed" if url else url,
|
||||
),
|
||||
patch(
|
||||
"packages.application.cosyvoice_service.CosyVoiceService",
|
||||
side_effect=RuntimeError("unexpected init failure"),
|
||||
),
|
||||
patch("packages.shared.url_security.safe_download_bytes", return_value=b"AUDIO"),
|
||||
patch("packages.shared.storage.get_shared_storage_service", return_value=MagicMock()),
|
||||
patch("app.services.mediakit_client.get_mediakit_client", return_value=MagicMock()),
|
||||
]
|
||||
for p in all_patches:
|
||||
p.__enter__()
|
||||
try:
|
||||
tts_synthesize_and_submit.run("job-1", "user-1", "v1", "你好", 1.0, "")
|
||||
finally:
|
||||
for p in reversed(all_patches):
|
||||
p.__exit__(None, None, None)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.error_code == "AsyncTaskError"
|
||||
assert "TTS 异步任务执行异常" in job.error_message
|
||||
session_mock.close.assert_called_once()
|
||||
@@ -101,7 +101,6 @@ class TestTTSPreviewEndpoint:
|
||||
text="你好世界",
|
||||
voice_id="longxiaochun",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
)
|
||||
|
||||
def test_preview_with_speed(self):
|
||||
@@ -147,7 +146,6 @@ class TestTTSPreviewEndpoint:
|
||||
text="测试",
|
||||
voice_id="v1",
|
||||
speed=1.5,
|
||||
emotion="",
|
||||
)
|
||||
|
||||
def test_preview_cosyvoice_error_returns_502(self):
|
||||
@@ -332,7 +330,6 @@ class TestTTSPreviewEndpoint:
|
||||
text="克隆音色测试",
|
||||
voice_id="cosyvoice_actual_voice_123",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
)
|
||||
# Verify repo was queried with the UUID
|
||||
mock_clone_repo.get.assert_called_once_with("abc123-uuid-of-profile")
|
||||
@@ -409,7 +406,6 @@ class TestTTSPreviewEndpoint:
|
||||
text="预设音色测试",
|
||||
voice_id="longxiaoxia_v3",
|
||||
speed=1.0,
|
||||
emotion="",
|
||||
)
|
||||
|
||||
def test_preview_clone_voice_wrong_user_returns_403(self):
|
||||
|
||||
Reference in New Issue
Block a user