Compare commits

...

14 Commits

Author SHA1 Message Date
auto-approve-bot 05309b170d ci: harden check-frontend-only with git diff fallback
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Successful in 1s
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 2s
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 33s
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 34s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 58s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m25s
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 1m39s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 1m46s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 1m47s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 1m50s
CI/CD Pipeline / Integration Tests (pull_request) Successful in 1m52s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 2m47s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 4m44s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 2m7s
ACR Cleanup / ACR Image Cleanup (pull_request_target) Successful in 55s
Preview Cleanup / Cleanup Preview Environment (pull_request) Successful in 1m0s
AI Code Review / AI Code Review (pull_request) Successful in 6m18s
CI/CD Pipeline / Unit Tests (pull_request) Failing after 9m29s
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Failing after 4s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
- 加 pull-requests: read 权限,避免 github.token 调 /pulls/files 403
- check-frontend-only 优先用 git diff 判断 PR 改动范围,API 失败时自动 fallback
- 修复 #48555 Check if frontend-only change 失败导致 unit-tests 跑全量 diff-cover 被误拦

Closes: CI 纯前端 PR 误跑 Python 测试被覆盖率门槛拦截问题
2026-09-09 13:17:30 +08:00
auto-approve-bot 474918ec66 fix: add heading to Step 5 single video for E2E test
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 1m57s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 3m5s
AI Code Review / AI Code Review (pull_request) Successful in 6m46s
CI/CD Pipeline / Check if frontend-only change (pull_request) Failing after 11m30s
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Failing after 11m42s
CI/CD Pipeline / PR Build API Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Web Image (pull_request) Has been skipped
CI/CD Pipeline / Frontend Lint (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 1m26s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 1m40s
CI/CD Pipeline / Integration Tests (pull_request) Successful in 1m41s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 2m18s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 11m29s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 5m9s
CI/CD Pipeline / Unit Tests (pull_request) Failing after 10m4s
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Failing after 5s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
Step 5 单视频场景缺少 🎬 确认生成 heading,导致 Playwright E2E 测试
core-generation.spec.ts 超时失败(getByRole('heading', { name: '🎬 确认生成' }))。

修改 GeneratePage.tsx:
- 在单视频 Step 5 容器顶部加 <h2>🎬 确认生成</h2>
- 外层 div flex 布局改为 column + center,保证垂直居中

Closes: E2E 连续 6 次 develop push 失败问题
2026-09-09 12:49:07 +08:00
xiaoxia 5b778fbb3e debug: AI数字人克隆音色试听加 Network/Console 调试日志 (#1819)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 17s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 11s
CI/CD Pipeline / Build Staging API Image (push) Successful in 16s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 18s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 1m24s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m43s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m22s
CI/CD Pipeline / Validate - Style (push) Successful in 2m5s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m52s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m16s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 2m35s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m9s
CI/CD Pipeline / Validate - Security (push) Successful in 5m18s
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 12:40:17 +08:00
xiaoxia 5eb8d6b31c debug: AI数字人克隆音色试听加 Network/Console 调试日志
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / Check push changed paths (push) Successful in 3s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Build Staging Web Image (push) Successful in 16s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 23s
CI/CD Pipeline / Build Staging API Image (push) Successful in 56s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 1m25s
CI/CD Pipeline / Validate - Style (push) Successful in 1m29s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m35s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m28s
CI/CD Pipeline / Validate - Security (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
CI/CD Pipeline / CI Gate (push) Has been cancelled
- 请求前打印 voice_id/voice_name/voice_clone_profile_id
- 响应后打印 audio_url 前80字符 + duration
- catch 打印 HTTP status + response data + message
- 帮助定位 /tts/preview 400/422/500/502 具体原因
2026-09-09 12:37:34 +08:00
xiaoxia 9121341f1b fix: AI数字人克隆音色试听传 profile UUID 而非 voice_id
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 0s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 6s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 24s
CI/CD Pipeline / Build Staging API Image (push) Successful in 38s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m18s
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 1m59s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 2m1s
CI/CD Pipeline / Validate - Style (push) Successful in 2m34s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m32s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m38s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 2m15s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 5m27s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m24s
CI/CD Pipeline / Validate - Security (push) Successful in 7m46s
CI/CD Pipeline / Unit Tests (push) Successful in 8m16s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
根因:后端 /tts/preview 用传入的 voice_id 去查 VoiceCloneProfile,
期望前端传 profile UUID(voice_clone_profile_id 或 clone.id)。
此前 clone 分支传了 voice_id(CosyVoice 模型 ID),
后端查不到 profile 静默返回,用户点播放无反应。

修复:clone 分支 targetId 改用 voice.voice_clone_profile_id || voice.id。
2026-09-09 11:34:36 +08:00
xiaoxia c3023cc11b fix: #1809 补充 对口型接口参数校验返回400而非500 (#1818)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging Web Image (push) Successful in 16s
CI/CD Pipeline / Build Staging API Image (push) Successful in 18s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 22s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m25s
CI/CD Pipeline / Integration Tests (push) Successful in 1m36s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m14s
CI/CD Pipeline / Validate - Style (push) Successful in 2m22s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m29s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m48s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m31s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m15s
CI/CD Pipeline / Validate - Security (push) Successful in 6m42s
CI/CD Pipeline / Unit Tests (push) Successful in 7m31s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 11:12:08 +08:00
xiaoxia 547561f473 fix: AI数字人对口型接口对齐后端新参数 video_url (#1809 补充) (#1816)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / Check push changed paths (push) Successful in 2s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging Web Image (push) Successful in 23s
CI/CD Pipeline / Build Staging API Image (push) Successful in 24s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 25s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m41s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m25s
CI/CD Pipeline / Integration Tests (push) Successful in 1m55s
CI/CD Pipeline / Validate - Style (push) Successful in 2m37s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m48s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 2m37s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m52s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m8s
CI/CD Pipeline / Validate - Security (push) Successful in 5m59s
CI/CD Pipeline / Unit Tests (push) Successful in 7m49s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 10:35:50 +08:00
xiaoxia a10e05654c fix: AI数字人「我的音色」克隆音色试听改用 TTS 合成 (#1815)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 2s
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Successful in 21s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 25s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 24s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Style (push) Successful in 1m8s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m39s
CI/CD Pipeline / Integration Tests (push) Successful in 1m34s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m10s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m37s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 2m42s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m33s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m16s
CI/CD Pipeline / Validate - Security (push) Successful in 5m51s
CI/CD Pipeline / Unit Tests (push) Successful in 7m53s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 10:22:28 +08:00
xiaoxia c954e334e6 fix: #1809 对口型接口参数调整,后端内部调TTS合成音频 (#1814)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 5s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Successful in 16s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 1m12s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 2m7s
CI/CD Pipeline / Integration Tests (push) Successful in 2m14s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 2m48s
CI/CD Pipeline / Validate - Style (push) Successful in 2m49s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m43s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m29s
CI/CD Pipeline / Validate - Security (push) Successful in 6m50s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 2m15s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 8m18s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 4m30s
CI/CD Pipeline / Unit Tests (push) Successful in 10m41s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 10:11:27 +08:00
xiaoxia 7c738ee64d fix: AI数字人「我的音色」试听无音频时弹提示而非静默返回 (#1813)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 2s
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging Web Image (push) Successful in 22s
CI/CD Pipeline / Build Staging API Image (push) Successful in 23s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 26s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m30s
CI/CD Pipeline / Integration Tests (push) Successful in 1m40s
CI/CD Pipeline / Validate - Style (push) Successful in 1m49s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m15s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m51s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m56s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m19s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m22s
CI/CD Pipeline / Unit Tests (push) Successful in 8m56s
CI/CD Pipeline / Validate - Security (push) Successful in 9m9s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 09:55:10 +08:00
xiaoxia 7209b7d481 feat: #1811 新增文案库独立页面 (#1812)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Build Staging API Image (push) Successful in 31s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 36s
CI/CD Pipeline / Validate - Style (push) Successful in 1m21s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 1m46s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 1m48s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 3m15s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m29s
CI/CD Pipeline / Validate - Security (push) Successful in 4m30s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m46s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 5m34s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 2m14s
CI/CD Pipeline / Unit Tests (push) Successful in 7m47s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 22m59s
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 08:59:27 +08:00
xiaoxia 165574f826 fix: #1809 AI数字人页面 7 项实测问题修复 (#1810)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 1s
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Successful in 25s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 27s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 1m2s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Validate - Style (push) Successful in 1m49s
CI/CD Pipeline / Integration Tests (push) Successful in 2m14s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 2m21s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m15s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m26s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m7s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m59s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m8s
CI/CD Pipeline / Validate - Security (push) Successful in 6m2s
CI/CD Pipeline / Unit Tests (push) Successful in 8m35s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 01:00:17 +08:00
xiaoxia a7e6145bb1 fix: #1807 侧边栏缩窄 240px→128px + 页面内容区拓宽 (#1808)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 2s
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Check push changed paths (push) Successful in 5s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Build Staging API Image (push) Successful in 25s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 25s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 50s
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 1m45s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 2m0s
CI/CD Pipeline / Validate - Style (push) Successful in 2m28s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m33s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m46s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 4m48s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 2m35s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m9s
CI/CD Pipeline / Unit Tests (push) Successful in 7m41s
CI/CD Pipeline / Validate - Security (push) Successful in 8m31s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-09 00:18:00 +08:00
xiaoxia 6ee99a652c fix: 部署脚本 worker health-cmd 未转义导致 staging 部署失败回滚 (#1806)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 0s
CI/CD Pipeline / Check push changed paths (push) Successful in 4s
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 27s
CI/CD Pipeline / Build Staging API Image (push) Successful in 28s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 59s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 1m31s
CI/CD Pipeline / Validate - Style (push) Successful in 2m4s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 2m3s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 3m34s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 1m12s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m30s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 5m0s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 2m56s
CI/CD Pipeline / Unit Tests (push) Successful in 6m47s
CI/CD Pipeline / Validate - Security (push) Successful in 20m59s
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Production (push) Has been skipped
CI/CD Pipeline / Canary Release to Production (push) Has been skipped
CI/CD Pipeline / Production Browser E2E (push) Has been skipped
2026-09-08 22:41:28 +08:00
32 changed files with 1675 additions and 306 deletions
+16 -2
View File
@@ -20,6 +20,7 @@ on:
default: "手动触发 - CI漏触发补跑"
permissions:
contents: read
pull-requests: read
concurrency:
group: ci-pipeline-${{ gitea.ref }}
cancel-in-progress: true
@@ -88,9 +89,22 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
run: |
set -eu
# 优先用 git diff 判断 PR 改动范围(比 API 稳定)
PR_NUMBER=$(echo "$GITHUB_REF" | sed 's|refs/pull/||; s|/.*||')
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)]")
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
FRONTEND_COUNT=$(echo "$FILES" | grep -c '^apps/web/' || true)
BACKEND_COUNT=$(echo "$FILES" | grep -cv '^apps/web/' || true)
TOTAL=$(echo "$FILES" | grep -cv '^$' || true)
+59 -7
View File
@@ -1,4 +1,4 @@
"""对口型 API 路由 — #1796 MediaKit 对口型.
"""对口型 API 路由 — #1796 MediaKit 对口型, #1809 参数调整.
接口:
POST /api/v1/lipsync/jobs 提交对口型任务
@@ -13,20 +13,51 @@ from __future__ import annotations
import logging
from app.auth import AuthenticatedUser, get_current_user
from app.dependencies import get_db_session
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, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from packages.application.cosyvoice_service import CosyVoiceError, CosyVoiceService
logger = logging.getLogger(__name__)
router = APIRouter()
def _get_service(db: Session = Depends(get_db_session)) -> LipsyncService:
return LipsyncService(db)
def _get_service(
db: Session = Depends(get_db_session),
cosyvoice_service: CosyVoiceService = Depends(get_cosyvoice_service),
) -> LipsyncService:
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 — 提交对口型任务 ───────────────────────────────────────────
@@ -37,21 +68,35 @@ 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: 前端传 {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.id,
video_url=body.video_url,
audio_url=body.audio_url,
voice_id=actual_voice_id,
script_text=body.script_text,
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 CosyVoiceError as exc:
# TTS 合成基础设施失败(API/网络/认证)
raise HTTPException(
status_code=502,
detail={"code": "TTSSynthesisFailed", "message": str(exc)},
) from exc
except MediaKitError as exc:
# 创建失败(job 已记录 error),返回 502
raise HTTPException(
status_code=502,
detail={
@@ -60,6 +105,13 @@ def create_lipsync_job(
"request_id": exc.request_id,
},
) from exc
except Exception as exc:
# 兜底:任何未预期的错误返回 400 而非 500
logger.error("创建对口型任务异常: %s", exc, exc_info=True)
raise HTTPException(
status_code=400,
detail=f"创建对口型任务失败: {exc}",
) from exc
return job
+21 -14
View File
@@ -1,4 +1,4 @@
"""对口型 API Schema 定义 — #1796."""
"""对口型 API Schema 定义 — #1796, #1809 参数调整."""
from __future__ import annotations
@@ -33,10 +33,15 @@ class LipsyncJobResponse(BaseModel):
class CreateLipsyncJobRequest(BaseModel):
"""创建对口型任务请求."""
"""创建对口型任务请求 — #1809.
前端传 {voice_id, script_text, video_url}
后端内部调 TTS 生成 audio_url 再提交 MediaKit。
"""
video_url: str = Field(..., description="人物视频 URL(MP4,≤30min,单人真人)")
audio_url: str = Field(..., description="驱动音频 URLmp3/aac/wav/m4a/flac")
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(可选)")
@@ -48,23 +53,25 @@ class CreateLipsyncJobRequest(BaseModel):
raise ValueError("video_url 不能为空")
if not v.startswith(("http://", "https://")):
raise ValueError("video_url 必须是 HTTP/HTTPS URL")
# 仅支持 MP4
lower = v.lower().split("?")[0]
if not lower.endswith(".mp4"):
raise ValueError("video_url 仅支持 MP4 格式")
return v
@field_validator("audio_url")
@field_validator("voice_id")
@classmethod
def validate_audio_url(cls, v: str) -> str:
def validate_voice_id(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("audio_url 不能为空")
if not v.startswith(("http://", "https://")):
raise ValueError("audio_url 必须是 HTTP/HTTPS URL")
# 支持的音频格式
lower = v.lower().split("?")[0]
allowed_exts = (".mp3", ".aac", ".wav", ".m4a", ".flac")
if not any(lower.endswith(ext) for ext in allowed_exts):
raise ValueError(f"audio_url 格式不支持,仅支持: {', '.join(allowed_exts)}")
raise ValueError("voice_id 不能为空")
return v
@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 字符")
return v
+52 -5
View File
@@ -1,7 +1,8 @@
"""对口型 Service — #1796 MediaKit 对口型业务逻辑.
"""对口型 Service — #1796 MediaKit 对口型业务逻辑, #1809 参数调整.
职责:
- 创建/查询/取消对口型任务
- 调用 TTS 合成音频(#1809:前端不再传 audio_url
- 调用 MediaKit 客户端提交异步任务
- 轮询更新任务状态
- 用户隔离(每个用户只能操作自己的任务)
@@ -25,6 +26,7 @@ from app.services.mediakit_client import (
from sqlalchemy.orm import Session
from packages.adapters.sqlalchemy_impl.models import LipsyncJobModel
from packages.application.cosyvoice_service import CosyVoiceError, CosyVoiceService
logger = logging.getLogger(__name__)
@@ -32,9 +34,23 @@ logger = logging.getLogger(__name__)
class LipsyncService:
"""对口型任务 Service."""
def __init__(self, db: Session, client: Optional[MediaKitClient] = None):
def __init__(
self,
db: Session,
client: Optional[MediaKitClient] = None,
cosyvoice_service: Optional[CosyVoiceService] = None,
):
self.db = db
self.client = client or get_mediakit_client()
self._cosyvoice_service = cosyvoice_service
@property
def cosyvoice_service(self) -> CosyVoiceService:
if self._cosyvoice_service is None:
from app.dependencies import get_cosyvoice_service
self._cosyvoice_service = get_cosyvoice_service()
return self._cosyvoice_service
# ── 创建任务 ──────────────────────────────────────────────────────────
@@ -43,16 +59,47 @@ class LipsyncService:
*,
user_id: str,
video_url: str,
audio_url: str,
voice_id: str,
script_text: str,
enable_video_loop: bool = False,
project_id: str = "",
) -> LipsyncJobModel:
"""创建对口型任务并提交到 MediaKit.
#1809: 内部调 TTS 合成音频,不再由前端传 audio_url。
Raises:
CosyVoiceError: TTS 合成失败
MediaKitError: API 调用失败
"""
# 1. 创建数据库记录
# 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
# 2. 创建数据库记录
job_id = str(uuid.uuid4())
job = LipsyncJobModel(
id=job_id,
@@ -66,7 +113,7 @@ class LipsyncService:
self.db.add(job)
self.db.flush()
# 2. 提交到 MediaKit
# 3. 提交到 MediaKit
try:
result = self.client.submit_lipsync(
video_url=video_url,
+2
View File
@@ -0,0 +1,2 @@
export * from "./scripts"
export * from "./types"
+37
View File
@@ -0,0 +1,37 @@
/**
* 文案库 API
* 对接后端 /api/v1/scriptsCRUD + 列表解包)
*/
import apiClient from "../client"
import type {
ScriptItem,
ScriptListResponse,
CreateScriptRequest,
UpdateScriptRequest,
} from "./types"
/** 获取文案列表 — 必须解包 items(后端返回 {items,total}*/
export const getScripts = async (): Promise<ScriptItem[]> => {
const response = await apiClient.get<ScriptListResponse | ScriptItem[]>("/scripts")
const data = response.data as unknown
if (Array.isArray(data)) return data
const items = (data as { items?: ScriptItem[] })?.items
return Array.isArray(items) ? items : []
}
/** 新建文案 */
export const createScript = async (data: CreateScriptRequest): Promise<ScriptItem> => {
const response = await apiClient.post<ScriptItem>("/scripts", data)
return response.data
}
/** 更新文案 */
export const updateScript = async (id: string, data: UpdateScriptRequest): Promise<ScriptItem> => {
const response = await apiClient.put<ScriptItem>(`/scripts/${id}`, data)
return response.data
}
/** 删除文案 */
export const deleteScript = async (id: string): Promise<void> => {
await apiClient.delete(`/scripts/${id}`)
}
+24
View File
@@ -0,0 +1,24 @@
/**
* 文案库 API — 类型定义
* 对接后端 /api/v1/scripts
*/
export interface ScriptItem {
id: string
title: string
content: string
char_count: number
created_at: string
updated_at?: string
}
export interface ScriptListResponse {
items: ScriptItem[]
total: number
}
export interface CreateScriptRequest {
title: string
content: string
}
export type UpdateScriptRequest = Partial<CreateScriptRequest>
+10 -4
View File
@@ -5,7 +5,7 @@
.xx-app-shell 全屏 flex 容器
├── header (xx-top-nav) 顶部导航(Header.tsx 管理)
└── .xx-app-body 水平 flex 行
├── .xx-app-sidebar 左侧侧边栏(240px / 64px 折叠)
├── .xx-app-sidebar 左侧侧边栏(128px / 64px 折叠)
└── .xx-app-content 主内容区(自适应)
所有尺寸/颜色均使用 global.css 设计系统变量
@@ -31,7 +31,7 @@
/* ── 侧边栏 ───────────────────────────────────────────────── */
.xx-app-sidebar {
width: 240px;
width: 128px;
flex-shrink: 0;
position: sticky;
top: 0;
@@ -103,6 +103,12 @@
padding: var(--space-sm);
}
/* 展开态(侧边栏 128px)水平 padding 收窄,为菜单文字留出完整一行空间 */
.xx-app-sidebar:not(.xx-collapsed) .xx-sidebar-content {
padding-left: var(--space-xs);
padding-right: var(--space-xs);
}
/* ── 主内容区 ─────────────────────────────────────────────── */
.xx-app-content {
flex: 1;
@@ -136,7 +142,7 @@
/* 展开态恢复完整宽度 */
.xx-app-sidebar:not(.xx-collapsed) {
width: 240px;
width: 128px;
}
.xx-app-sidebar:not(.xx-collapsed) .xx-sidebar-toggle {
@@ -159,7 +165,7 @@
top: 56px; /* 移动端 Header 高度 */
left: 0;
bottom: 0;
width: 240px;
width: 128px;
transform: translateX(-100%);
transition: transform var(--transition-slow);
box-shadow: none;
@@ -2,7 +2,7 @@
* MainLayout - 主布局组件(Task 1.2
*
* 三栏布局:左侧侧边栏 + 顶部导航栏 + 主内容区
* - 侧边栏:240px 固定宽度,可折叠至 64px 图标栏
* - 侧边栏:128px 固定宽度,可折叠至 64px 图标栏
* - 顶部导航:复用 Header 组件(68px 固定高度)
* - 主内容区:自适应填充剩余空间
* - 响应式:移动端(<768px)隐藏侧边栏
+20 -10
View File
@@ -30,7 +30,7 @@
/* 分组标题 */
.xx-sidebar-group-title {
padding: var(--space-sm) var(--space-md) var(--space-xs);
padding: var(--space-sm) var(--space-sm) var(--space-xs);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-semibold);
color: var(--text-tertiary);
@@ -56,9 +56,9 @@
.xx-sidebar-menu-item {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-sm) var(--space-md);
margin: 0 var(--space-xs);
gap: var(--space-xs);
padding: var(--space-sm) var(--space-xs);
margin: 0 var(--space-xxs);
border-radius: var(--radius-sm);
cursor: pointer;
color: var(--text-secondary);
@@ -97,12 +97,12 @@
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 10px;
width: 28px;
height: 28px;
border-radius: 8px;
background: #f1f5f9;
color: var(--text-secondary);
font-size: 18px;
font-size: 16px;
line-height: 1;
transition: 0.15s ease;
}
@@ -119,7 +119,9 @@
/* ── 菜单项文字 ───────────────────────────────────────────── */
.xx-sidebar-menu-label {
flex: 1;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
@@ -133,8 +135,16 @@
/* 折叠时菜单项居中,仅图标 */
.xx-sidebar-nav--collapsed .xx-sidebar-menu-item {
justify-content: center;
padding: var(--space-sm);
margin: 0 var(--space-xxs);
padding: var(--space-xs);
margin: 0;
}
/* 折叠态图标恢复更大尺寸居中 */
.xx-sidebar-nav--collapsed .xx-sidebar-menu-icon {
width: 32px;
height: 32px;
border-radius: 8px;
font-size: 16px;
}
/* 折叠时隐藏分组标题 */
+12
View File
@@ -58,6 +58,12 @@ export const NAV_ITEMS: NavItem[] = [
path: "/app/titles",
icon: React.createElement(FileTextOutlined),
},
{
key: "scripts",
label: "文案库",
path: "/app/scripts",
icon: React.createElement(EditOutlined),
},
{
key: "voices",
label: "配音库",
@@ -173,6 +179,12 @@ export const NAV_GROUPS: NavGroup[] = [
path: "/app/titles",
icon: React.createElement(FileTextOutlined),
},
{
key: "scripts",
label: "文案库",
path: "/app/scripts",
icon: React.createElement(EditOutlined),
},
{
key: "products",
label: "成品库",
+1 -1
View File
@@ -11,7 +11,7 @@
.admin-coming-soon-page {
padding: 32px;
max-width: 1400px;
max-width: 1680px;
margin: 0 auto;
}
+129
View File
@@ -1021,3 +1021,132 @@
font-size: 36px;
margin-bottom: 8px;
}
/* ============================================================
#1809 ④⑤⑥ B-roll 弹窗:选库行 + 文案句子列表 + 自动估算提示
============================================================ */
/* 宽弹窗:左右两栏 + 句子列表需要更大空间 */
.aa-modal--wide {
max-width: 960px;
width: 94%;
}
.aa-broll-modal-body .aa-broll-right {
width: 300px;
}
/* 左侧素材库选择行 */
.aa-broll-lib-row {
margin-bottom: 10px;
}
.aa-broll-lib-row .aa-select {
width: 100%;
height: 36px;
border: 1px solid var(--border-color, #e2e2ea);
border-radius: 8px;
padding: 0 10px;
font-size: 13px;
background: #fff;
color: #1a1a2e;
outline: none;
}
/* 无缩略图时的素材占位 */
.aa-broll-asset-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
}
/* 文案句子列表 */
.aa-sentence-list {
max-height: 240px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 6px;
padding-right: 4px;
}
.aa-sentence-item {
display: flex;
align-items: flex-start;
gap: 8px;
width: 100%;
text-align: left;
border: 1px solid var(--border-color, #e2e2ea);
border-radius: 8px;
background: #fff;
padding: 8px 10px;
cursor: pointer;
transition: all 0.15s;
}
.aa-sentence-item:hover {
border-color: #c0c0d0;
background: #f8f8fc;
}
.aa-sentence-item.active {
border-color: #7c3aed;
background: #f3edff;
}
.aa-sentence-item__idx {
flex-shrink: 0;
width: 20px;
height: 20px;
border-radius: 50%;
background: #f0f0f5;
color: #6b6b80;
font-size: 11px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
}
.aa-sentence-item.active .aa-sentence-item__idx {
background: #7c3aed;
color: #fff;
}
.aa-sentence-item__text {
flex: 1;
font-size: 12px;
line-height: 1.5;
color: #1a1a2e;
word-break: break-all;
}
.aa-sentence-item__time {
flex-shrink: 0;
font-size: 10px;
color: #8c8ca1;
margin-top: 2px;
}
.aa-sentence-empty {
font-size: 12px;
color: #8c8ca1;
background: #f8f8fc;
border-radius: 8px;
padding: 10px;
}
/* 选择/估算提示 */
.aa-broll-hint {
font-size: 12px;
color: #059669;
background: #f8f8fc;
border-radius: 6px;
padding: 8px 10px;
display: flex;
flex-direction: column;
gap: 4px;
}
+50 -20
View File
@@ -3,6 +3,7 @@
* 5列水平面板布局
*/
import React, { useState, useCallback, useEffect, useRef } from "react"
import { message } from "antd"
import "./AiAvatar.css"
import { useAiAvatar } from "./hooks/useAiAvatar"
import { PanelVideoSelector } from "./components/PanelVideoSelector"
@@ -12,8 +13,13 @@ import PanelTitleConfig from "./components/PanelTitleConfig"
import PanelCoverAndGenerate from "./components/PanelCoverAndGenerate"
import { ModalAssetPicker } from "./components/ModalAssetPicker"
import ModalBRollEditor from "./components/ModalBRollEditor"
import { getScripts, createLipsyncJob, getLipsyncJob, submitRender } from "./api/aiAvatar"
import { getAssetsByKind } from "@/api/assets"
import {
getScripts,
getAssetById,
createLipsyncJob,
getLipsyncJob,
submitRender,
} from "./api/aiAvatar"
/** 面板折叠状态 */
type PanelKey = "video" | "voice" | "script" | "title" | "cover"
@@ -28,9 +34,6 @@ const AiAvatarPage: React.FC = () => {
cover: false,
})
/* ── 素材库弹窗 ── */
const [bRollAssets, setBRollAssets] = useState<import("@/api/assets").AssetItem[]>([])
/* ── 对口型轮询 ── */
const lipsyncTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
@@ -40,14 +43,34 @@ const AiAvatarPage: React.FC = () => {
/* ── 对口型 ── */
const handleGenerateLipsync = useCallback(async () => {
if (!state.selectedVideo || !state.selectedVoice || !state.scriptText) return
// ② 缺项明确提示(#1809):不再静默 return
const video = state.selectedVideo
const voice = state.selectedVoice
const text = state.scriptText.trim()
const missing: string[] = []
if (!video) missing.push("出镜视频")
if (!voice) missing.push("音色")
if (!text) missing.push("文案")
if (missing.length > 0 || !video || !voice) {
message.warning(`请先选择${missing.join("、")}`)
return
}
try {
// ① 先按素材 id 拿 file_url(#1809 补充:对齐后端新参数 video_url)
const asset = await getAssetById(video.id)
const videoUrl = asset?.file_url
if (!videoUrl) {
message.error("获取出镜视频播放地址失败,请重新选择素材")
return
}
// ② voice_id(预设/克隆 UUID 均由后端内部调 TTS+ script_text + video_url
const job = await createLipsyncJob({
voice_id: state.selectedVoice.voice_id,
voice_id: voice.voice_id,
script_text: state.scriptText,
video_asset_id: state.selectedVideo.id,
video_url: videoUrl,
})
state.setLipsyncJob(job)
message.success("对口型任务已提交,生成中…")
// 开始轮询
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
lipsyncTimerRef.current = setInterval(async () => {
@@ -56,13 +79,20 @@ const AiAvatarPage: React.FC = () => {
state.setLipsyncJob(updated)
if (updated.status === "completed" || updated.status === "failed") {
if (lipsyncTimerRef.current) clearInterval(lipsyncTimerRef.current)
if (updated.status === "completed") {
message.success("对口型视频生成完成")
} else {
message.error(updated.error_message || "对口型生成失败")
}
}
} catch {
// 忽略轮询错误
// 忽略轮询错误(轮询期间不打扰用户)
}
}, 3000)
} catch (err) {
// ② 接口失败弹错误提示,不只 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])
@@ -74,16 +104,13 @@ const AiAvatarPage: React.FC = () => {
}
}, [])
/* ── 加载 B-roll 素材 ── */
useEffect(() => {
getAssetsByKind("video", { limit: 50 })
.then(setBRollAssets)
.catch(() => {})
}, [])
/* ── 生成视频 ── */
const handleGenerate = useCallback(async () => {
if (!state.lipsyncJob || state.lipsyncJob.status !== "completed") return
// ② 前置条件提示(#1809
if (!state.lipsyncJob || state.lipsyncJob.status !== "completed") {
message.warning("请先生成对口型视频,待对口型完成后再提交渲染")
return
}
state.setIsGenerating(true)
try {
await submitRender({
@@ -94,8 +121,10 @@ const AiAvatarPage: React.FC = () => {
cover_config: state.coverConfig as unknown as Record<string, unknown>,
resolution: state.resolution,
})
message.success("渲染任务已提交,可在视频管理中查看进度")
} catch (err) {
console.error("渲染任务提交失败:", err)
message.error(err instanceof Error ? err.message : "渲染任务提交失败,请重试")
} finally {
state.setIsGenerating(false)
}
@@ -241,7 +270,8 @@ const AiAvatarPage: React.FC = () => {
open={state.showBRollModal}
onClose={() => state.setShowBRollModal(false)}
existingSegments={state.bRollSegments}
availableAssets={bRollAssets}
scriptText={state.scriptText}
outputDuration={state.lipsyncJob?.output_duration ?? 0}
onConfirm={state.addBRollSegment}
onRemove={state.removeBRollSegment}
/>
@@ -264,8 +294,8 @@ const ScriptSelectModalLazy: React.FC<{
if (!open) return
setLoading(true)
getScripts()
.then(setScripts)
.catch(() => {})
.then((items) => setScripts(Array.isArray(items) ? items : []))
.catch(() => setScripts([]))
.finally(() => setLoading(false))
}, [open])
+13 -3
View File
@@ -6,8 +6,12 @@ import type { Script, LipsyncJob, RenderJob, BRollSegment } from "../types"
/* ── 文案库 ── */
export const getScripts = async (): Promise<Script[]> => {
const response = await apiClient.get<Script[]>("/scripts")
return response.data
const response = await apiClient.get<{ items?: Script[] } | Script[]>("/scripts")
// 后端列表返回 { items, total } 分页对象,做兼容解包 + 数组防御(#1809 白屏修复)
const data = response.data as unknown
if (Array.isArray(data)) return data
const items = (data as { items?: Script[] })?.items
return Array.isArray(items) ? items : []
}
export const getScriptById = async (id: string): Promise<Script> => {
@@ -24,11 +28,17 @@ export const deleteScript = async (id: string): Promise<void> => {
await apiClient.delete(`/scripts/${id}`)
}
/* ── 素材单查(用于拿到 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
}
/* ── 对口型 ── */
export const createLipsyncJob = async (data: {
voice_id: string
script_text: string
video_asset_id: string
video_url: string
}): Promise<LipsyncJob> => {
const response = await apiClient.post<LipsyncJob>("/lipsync/jobs", data)
return response.data
@@ -1,13 +1,10 @@
/**
* AI数字人 — 素材库弹窗
* 搜索框 + 类型筛选(全部/视频/图片)+ 4 列竖屏 9:16 缩略图网格 + 底部确认选择
* AI数字人 — 出镜视频选择弹窗(#1809 ③)
* 交互对齐智能剪辑 Step2:先选素材库(video 库)→ 再选该库内视频。
* 搜索框 + 素材库下拉 + 竖屏 9:16 视频缩略图网格 + 底部确认选择。
*/
import { useEffect, useState } from "react"
import { ensureDefaultLibrary, getAssetsByKind, type AssetItem } from "@/api/assets"
import { getOrCreateDefaultProject } from "@/api/projects"
/** 素材类型筛选 */
type AssetKindFilter = "all" | "video" | "image"
import { getAssets, getAssetLibraries, type AssetItem, type AssetLibraryItem } from "@/api/assets"
export interface ModalAssetPickerProps {
open: boolean
@@ -17,86 +14,76 @@ export interface ModalAssetPickerProps {
selectedId?: string
}
const KIND_OPTIONS: { value: AssetKindFilter; label: string }[] = [
{ value: "all", label: "全部" },
{ value: "video", label: "视频" },
{ value: "image", label: "图片" },
]
export function ModalAssetPicker({ open, onClose, onSelect, selectedId }: ModalAssetPickerProps) {
const [keyword, setKeyword] = useState("")
const [kindFilter, setKindFilter] = useState<AssetKindFilter>("video")
const [libraries, setLibraries] = useState<AssetLibraryItem[]>([])
const [libraryId, setLibraryId] = useState<string>("")
const [assets, setAssets] = useState<AssetItem[]>([])
const [pickedId, setPickedId] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const [loadingLibs, setLoadingLibs] = useState(false)
const [loadingAssets, setLoadingAssets] = useState(false)
const [error, setError] = useState("")
const [ready, setReady] = useState(false)
/* 弹窗打开:重置筛选 / 关键字,并定位高亮到已选素材 */
/* 弹窗打开:重置状态 */
useEffect(() => {
if (!open) return
setKeyword("")
setKindFilter("video")
setLibraries([])
setLibraryId("")
setAssets([])
setError("")
setPickedId(selectedId ?? null)
setReady(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open])
/* 确保默认素材库存在(视频 + 图片,供类型筛选),仅在弹窗打开时执行一次 */
/* 第一步:加载视频素材库列表(仅 kind=video,对齐智能剪辑 #1777 */
useEffect(() => {
if (!open) return
let cancelled = false
const ensureLibraries = async () => {
try {
const project = await getOrCreateDefaultProject()
await Promise.all([
ensureDefaultLibrary({ project_id: project.id, kind: "video" }),
ensureDefaultLibrary({ project_id: project.id, kind: "image" }),
])
if (!cancelled) setReady(true)
} catch {
if (!cancelled) setError("素材库初始化失败,请重试")
}
}
ensureLibraries()
setLoadingLibs(true)
getAssetLibraries("video")
.then((libs) => {
if (cancelled) return
const list = Array.isArray(libs) ? libs : []
setLibraries(list)
// 默认选中第一个视频库
if (list.length > 0) setLibraryId((prev) => prev || list[0].id)
})
.catch(() => {
if (!cancelled) setError("素材库加载失败,请重试")
})
.finally(() => {
if (!cancelled) setLoadingLibs(false)
})
return () => {
cancelled = true
}
}, [open])
/* 拉取素材:类型 / 关键字变化时防抖重新请求 */
/* 第二步:选中库后拉取该库视频素材(关键字防抖) */
useEffect(() => {
if (!open || !ready) return
if (!open || !libraryId) return
let cancelled = false
setLoading(true)
setLoadingAssets(true)
const load = async () => {
try {
const kw = keyword.trim() || undefined
let items: AssetItem[] = []
if (kindFilter === "all") {
const [videos, images] = await Promise.all([
getAssetsByKind("video", { keyword: kw }),
getAssetsByKind("image", { keyword: kw }),
])
const seen = new Set<string>()
items = [...videos, ...images].filter((a) => {
if (seen.has(a.id)) return false
seen.add(a.id)
return true
})
} else {
items = await getAssetsByKind(kindFilter, { keyword: kw })
}
if (!cancelled) setAssets(items)
// getAssets 返回 { items, total };拉满一页(数字人口播视频库通常不大)
const { items } = await getAssets(libraryId, { page_size: 100 })
if (cancelled) return
let list = Array.isArray(items) ? items : []
// 仅保留视频素材(出镜视频要求)
list = list.filter((a) => a.mime_type?.includes("video"))
const kw = keyword.trim()
if (kw) list = list.filter((a) => a.name?.includes(kw))
setAssets(list)
setError("")
} catch {
if (!cancelled) {
setError("素材加载失败,请重试")
setAssets([])
}
} finally {
if (!cancelled) setLoading(false)
if (!cancelled) setLoadingAssets(false)
}
}
const timer = window.setTimeout(load, 300)
@@ -104,7 +91,7 @@ export function ModalAssetPicker({ open, onClose, onSelect, selectedId }: ModalA
cancelled = true
window.clearTimeout(timer)
}
}, [open, ready, kindFilter, keyword])
}, [open, libraryId, keyword])
if (!open) return null
@@ -120,15 +107,33 @@ export function ModalAssetPicker({ open, onClose, onSelect, selectedId }: ModalA
<div className="aa-modal" onClick={(e) => e.stopPropagation()}>
{/* 头部 */}
<div className="aa-modal__header">
<span className="aa-modal__title"></span>
<span className="aa-modal__title"></span>
<button type="button" className="aa-modal__close" onClick={onClose} aria-label="关闭">
×
</button>
</div>
{/* 主体:搜索 + 筛选 + 网格 */}
{/* 主体:素材库选择 + 搜索 + 网格 */}
<div className="aa-modal__body">
{/* 第一步:选素材库 */}
<div className="aa-asset-search">
<select
className="aa-select"
style={{ width: 160, flex: "0 0 auto" }}
value={libraryId}
onChange={(e) => setLibraryId(e.target.value)}
disabled={loadingLibs || libraries.length === 0}
>
{libraries.length === 0 ? (
<option value="">{loadingLibs ? "素材库加载中…" : "暂无视频素材库"}</option>
) : (
libraries.map((lib) => (
<option key={lib.id} value={lib.id}>
📁 {lib.name}
</option>
))
)}
</select>
<input
className="aa-input"
type="text"
@@ -136,21 +141,14 @@ export function ModalAssetPicker({ open, onClose, onSelect, selectedId }: ModalA
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
<select
className="aa-select"
style={{ width: 110, flex: "0 0 auto" }}
value={kindFilter}
onChange={(e) => setKindFilter(e.target.value as AssetKindFilter)}
>
{KIND_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
{loading ? (
{libraries.length === 0 && !loadingLibs ? (
<div className="aa-empty">
<div className="aa-empty__icon">📁</div>
</div>
) : loadingAssets ? (
<div className="aa-empty">
<div className="aa-empty__icon"></div>
@@ -162,8 +160,8 @@ export function ModalAssetPicker({ open, onClose, onSelect, selectedId }: ModalA
</div>
) : assets.length === 0 ? (
<div className="aa-empty">
<div className="aa-empty__icon">📁</div>
<div className="aa-empty__icon">🎬</div>
</div>
) : (
<div className="aa-asset-grid">
@@ -1,23 +1,27 @@
/**
* AI数字人 — B-roll 画面插入编辑器弹窗
* AI数字人 — B-roll 画面插入编辑器弹窗#1809 ④⑤⑥)
*
* 布局:
* - 左侧:可用素材网格(已被其他 segment 使用的素材标灰 + "已选择" 遮罩,
* pointer-events: none 防重复选择同一段素材
* - 右侧:插入设置(文案段落索引 / 全屏 or 画中画 / 画中画四角位置 + 大小 / 起止时间)
* - 底部:已配置的画面插入列表(可删除)+ 上传新素材入口
* - 左侧:先选素材库(video 库)→ 再选该库视频素材(已被其他 segment 使用的素材
* 标灰 + "已选择" 遮罩,pointer-events:none 防重复选择)
* - 右侧:文案句子列表(点选对应段落,替代原数字索引框)/ 全屏 or 画中画 / 四角位置+大小
* (开始/结束时间已删除,按句子字数占比 × 口播总时长自动估算)
* - 底部:已配置的画面插入列表(可删除)
*/
import React, { useMemo, useState } from "react"
import type { AssetItem } from "@/api/assets"
import React, { useEffect, useMemo, useState } from "react"
import { getAssets, getAssetLibraries, type AssetItem, type AssetLibraryItem } from "@/api/assets"
import type { BRollSegment, BRollInsertMode, PipPosition } from "../types"
import { splitScriptIntoSentences, type ScriptSentence } from "../utils/sentences"
interface ModalBRollEditorProps {
open: boolean
onClose: () => void
/** 当前已有的 B-roll segments(用于标灰已选素材) */
existingSegments: BRollSegment[]
/** 所有可用素材 */
availableAssets: AssetItem[]
/** 当前文案全文(用于分句) */
scriptText: string
/** 对口型成片总时长(秒),用于时间自动估算 */
outputDuration: number
onConfirm: (segment: BRollSegment) => void
onRemove: (id: string) => void
}
@@ -38,18 +42,31 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
open,
onClose,
existingSegments,
availableAssets,
scriptText,
outputDuration,
onConfirm,
onRemove,
}) => {
/* ── 素材库(④ 先选库再选素材) ── */
const [libraries, setLibraries] = useState<AssetLibraryItem[]>([])
const [libraryId, setLibraryId] = useState<string>("")
const [availableAssets, setAvailableAssets] = useState<AssetItem[]>([])
const [loadingLibs, setLoadingLibs] = useState(false)
const [loadingAssets, setLoadingAssets] = useState(false)
const [assetError, setAssetError] = useState("")
/* ── 右侧设置本地状态 ── */
const [selectedAsset, setSelectedAsset] = useState<AssetItem | null>(null)
const [scriptSegmentIndex, setScriptSegmentIndex] = useState(0)
const [selectedSentence, setSelectedSentence] = useState<ScriptSentence | null>(null)
const [mode, setMode] = useState<BRollInsertMode>("fullscreen")
const [pipPosition, setPipPosition] = useState<PipPosition>("top-right")
const [pipScale, setPipScale] = useState(0.3)
const [startTime, setStartTime] = useState(0)
const [endTime, setEndTime] = useState(3)
/** 文案分句(⑤) */
const sentences = useMemo(
() => splitScriptIntoSentences(scriptText, outputDuration),
[scriptText, outputDuration],
)
/** 已被现有 segments 占用的素材 id 集合(标灰、禁止重复选择) */
const usedAssetIds = useMemo(
@@ -57,25 +74,83 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
[existingSegments],
)
/* 弹窗打开:重置选择 + 加载视频库列表 */
useEffect(() => {
if (!open) return
setSelectedAsset(null)
setSelectedSentence(null)
setMode("fullscreen")
setPipPosition("top-right")
setPipScale(0.3)
setLibraries([])
setLibraryId("")
setAvailableAssets([])
setAssetError("")
setLoadingLibs(true)
let cancelled = false
getAssetLibraries("video")
.then((libs) => {
if (cancelled) return
const list = Array.isArray(libs) ? libs : []
setLibraries(list)
if (list.length > 0) setLibraryId(list[0].id)
})
.catch(() => {
if (!cancelled) setAssetError("素材库加载失败,请重试")
})
.finally(() => {
if (!cancelled) setLoadingLibs(false)
})
return () => {
cancelled = true
}
}, [open])
/* 选中库后拉取该库视频素材 */
useEffect(() => {
if (!open || !libraryId) return
let cancelled = false
setLoadingAssets(true)
getAssets(libraryId, { page_size: 100 })
.then(({ items }) => {
if (cancelled) return
const list = (Array.isArray(items) ? items : []).filter((a) =>
a.mime_type?.includes("video"),
)
setAvailableAssets(list)
setAssetError("")
})
.catch(() => {
if (!cancelled) {
setAssetError("素材加载失败,请重试")
setAvailableAssets([])
}
})
.finally(() => {
if (!cancelled) setLoadingAssets(false)
})
return () => {
cancelled = true
}
}, [open, libraryId])
if (!open) return null
/** 选择素材(已选素材因 pointer-events:none 不会触发) */
const handleSelectAsset = (asset: AssetItem) => {
if (usedAssetIds.has(asset.id)) return
setSelectedAsset(asset)
// 默认起止时间:素材时长的前 3 秒(或整段)
const dur = asset.duration ?? 3
setEndTime(Math.min(3, dur))
}
/** 确认添加一段 B-roll */
/** 确认添加一段 B-roll(⑥ 时间取所选句子的估算起止) */
const handleConfirm = () => {
if (!selectedAsset) return
if (endTime <= startTime) return
if (!selectedAsset || !selectedSentence) return
const startTime = selectedSentence.startTime
const endTime = Math.max(selectedSentence.endTime, startTime + 0.5)
const segment: BRollSegment = {
id: crypto.randomUUID(),
asset: selectedAsset,
script_segment_index: scriptSegmentIndex,
script_segment_index: selectedSentence.index,
start_time: startTime,
end_time: endTime,
mode,
@@ -83,15 +158,16 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
pip_scale: mode === "pip" ? pipScale : 0.3,
}
onConfirm(segment)
// 重置选择,保留设置便于连续添加
// 重置素材/句子选择,保留模式设置便于连续添加
setSelectedAsset(null)
setSelectedSentence(null)
}
const canConfirm = selectedAsset !== null && endTime > startTime
const canConfirm = selectedAsset !== null && selectedSentence !== null
return (
<div className="aa-modal-overlay" onClick={onClose}>
<div className="aa-modal" onClick={(e) => e.stopPropagation()}>
<div className="aa-modal aa-modal--wide" onClick={(e) => e.stopPropagation()}>
{/* 头部 */}
<div className="aa-modal__header">
<span className="aa-modal__title">🎞 B-roll</span>
@@ -103,22 +179,25 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
{/* 主体:左素材 + 右设置 */}
<div className="aa-modal__body">
<div className="aa-broll-modal-body">
{/* 左侧:素材网格 */}
{/* 左侧:选库 + 素材网格 */}
<div className="aa-broll-left">
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginBottom: 10,
}}
>
<span style={{ fontSize: 13, fontWeight: 600, color: "#1a1a2e" }}>
{availableAssets.length}
</span>
<button type="button" className="aa-btn aa-btn--ghost aa-btn-sm">
</button>
<div className="aa-broll-lib-row">
<select
className="aa-select"
value={libraryId}
onChange={(e) => setLibraryId(e.target.value)}
disabled={loadingLibs || libraries.length === 0}
>
{libraries.length === 0 ? (
<option value="">{loadingLibs ? "素材库加载中…" : "暂无视频素材库"}</option>
) : (
libraries.map((lib) => (
<option key={lib.id} value={lib.id}>
📁 {lib.name}
</option>
))
)}
</select>
</div>
<div className="aa-broll-asset-grid">
{availableAssets.map((asset) => {
@@ -141,45 +220,60 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
{asset.thumbnail_url ? (
<img src={asset.thumbnail_url} alt={asset.name} />
) : (
<div
style={{
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: 18,
}}
>
🎬
</div>
<div className="aa-broll-asset-placeholder">🎬</div>
)}
<span className="aa-asset-card__name">{asset.name}</span>
</div>
)
})}
{availableAssets.length === 0 && (
{loadingAssets ? (
<div className="aa-empty" style={{ gridColumn: "1 / -1" }}>
<div className="aa-empty__icon"></div>
</div>
) : availableAssets.length === 0 ? (
<div className="aa-empty" style={{ gridColumn: "1 / -1" }}>
<div className="aa-empty__icon">🎬</div>
{assetError || "该素材库暂无视频素材"}
</div>
)}
) : null}
</div>
</div>
{/* 右侧:插入设置 */}
<div className="aa-broll-right">
<div className="aa-broll-settings">
{/* 文案段落索引 */}
{/* ⑤ 文案句子列表(替代段落索引数字框) */}
<div className="aa-form-field">
<label className="aa-label"></label>
<input
className="aa-input"
type="number"
min={0}
value={scriptSegmentIndex}
onChange={(e) => setScriptSegmentIndex(Math.max(0, Number(e.target.value)))}
/>
<label className="aa-label"></label>
{sentences.length === 0 ? (
<div className="aa-sentence-empty">
&
</div>
) : (
<div className="aa-sentence-list">
{sentences.map((sent) => {
const active = selectedSentence?.index === sent.index
return (
<button
key={sent.index}
type="button"
className={`aa-sentence-item${active ? " active" : ""}`}
onClick={() => setSelectedSentence(sent)}
title={sent.text}
>
<span className="aa-sentence-item__idx">{sent.index + 1}</span>
<span className="aa-sentence-item__text">{sent.text}</span>
{outputDuration > 0 && (
<span className="aa-sentence-item__time">
{sent.startTime.toFixed(1)}-{sent.endTime.toFixed(1)}s
</span>
)}
</button>
)
})}
</div>
)}
</div>
{/* 插入模式 */}
@@ -224,10 +318,7 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
</div>
</div>
<div className="aa-form-field">
<div
className="aa-field-label-row"
style={{ display: "flex", justifyContent: "space-between" }}
>
<div className="aa-field-label-row">
<label className="aa-label"></label>
<span style={{ fontSize: 12, color: "#8c8ca1" }}>
{Math.round(pipScale * 100)}%
@@ -246,41 +337,26 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
</>
)}
{/* 起止时间 */}
<div className="aa-form-field">
<label className="aa-label"></label>
<input
className="aa-input"
type="number"
min={0}
step={0.1}
value={startTime}
onChange={(e) => setStartTime(Math.max(0, Number(e.target.value)))}
/>
</div>
<div className="aa-form-field">
<label className="aa-label"></label>
<input
className="aa-input"
type="number"
min={0}
step={0.1}
value={endTime}
onChange={(e) => setEndTime(Math.max(0, Number(e.target.value)))}
/>
</div>
{/* 当前选中素材提示 */}
<div
style={{
fontSize: 12,
color: selectedAsset ? "#059669" : "#8c8ca1",
background: "#f8f8fc",
borderRadius: 6,
padding: "6px 8px",
}}
>
{selectedAsset ? `已选素材:${selectedAsset.name}` : "请从左侧选择一段素材"}
{/* 当前选择提示(⑥ 自动估算时间在这里展示) */}
<div className="aa-broll-hint">
{selectedAsset && selectedSentence ? (
<>
<div>{selectedAsset.name}</div>
<div>
{selectedSentence.index + 1} · {" "}
{selectedSentence.startTime.toFixed(1)}s -{" "}
{Math.max(
selectedSentence.endTime,
selectedSentence.startTime + 0.5,
).toFixed(1)}
s
</div>
</>
) : (
<div style={{ color: "#8c8ca1" }}>
{!selectedAsset ? "请从左侧选择一段素材" : "请在上方点选对应的文案句子"}
</div>
)}
</div>
</div>
</div>
@@ -304,7 +380,7 @@ const ModalBRollEditor: React.FC<ModalBRollEditorProps> = ({
<div className="aa-broll-item__info">
<div style={{ fontWeight: 500, color: "#1a1a2e" }}>{seg.asset.name}</div>
<div style={{ color: "#8c8ca1", fontSize: 11 }}>
{seg.script_segment_index} · {MODE_LABEL[seg.mode]}
{seg.script_segment_index + 1} · {MODE_LABEL[seg.mode]}
{seg.mode === "pip" ? ` · ${seg.pip_position}` : ""} ·{" "}
{seg.start_time.toFixed(1)}s - {seg.end_time.toFixed(1)}s
</div>
@@ -3,7 +3,9 @@
* 音色来源切换(系统预设 / 我的音色)、音色选择与试听、情绪/语速/语言参数
*/
import { useEffect, useRef, useState } from "react"
import { message } from "antd"
import { fetchVoices } from "@/api/voices/voices"
import { previewTts } from "@/api/tts"
import type { UnifiedVoiceItem } from "@/api/voices/types"
import {
type VoiceSource,
@@ -43,6 +45,9 @@ export function PanelVoiceSelector({
const [error, setError] = useState<string | null>(null)
const [previewingId, setPreviewingId] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
/** 克隆音色试听合成缓存:voiceId -> url,对齐配音库 useAudioPlayer */
const previewCacheRef = useRef<Map<string, string>>(new Map())
const VOICE_PREVIEW_TEXT = "你好呀,欢迎使用小虾智剪,这是我的配音效果,希望你喜欢。"
/* 切换来源时重新获取音色列表 */
useEffect(() => {
@@ -52,7 +57,7 @@ export function PanelVoiceSelector({
setError(null)
try {
const res = await fetchVoices({ type: voiceSource })
if (!cancelled) setVoices(res.items || [])
if (!cancelled) setVoices(Array.isArray(res?.items) ? res.items : [])
} catch (err) {
if (!cancelled) setError(err instanceof Error ? err.message : "音色加载失败")
} finally {
@@ -83,21 +88,17 @@ export function PanelVoiceSelector({
setPreviewingId(null)
}
const handlePreview = (voice: UnifiedVoiceItem) => {
const url = voice.preview_url || voice.audio_url
if (!url) return
/* 再次点击当前试听音色 → 停止 */
if (previewingId === voice.id) {
stopPreview()
return
}
const NO_PREVIEW_TIP = "该音色暂无试听音频,请先用此音色生成一段配音后再试听"
/** 用指定 URL 真实播放(抽取公共) */
const playAudioUrl = (voiceId: string, url: string) => {
if (audioRef.current) {
audioRef.current.pause()
audioRef.current = null
}
const audio = new Audio(url)
audioRef.current = audio
setPreviewingId(voice.id)
setPreviewingId(voiceId)
audio.onended = () => {
if (audioRef.current === audio) {
audioRef.current = null
@@ -108,15 +109,79 @@ export function PanelVoiceSelector({
if (audioRef.current === audio) {
audioRef.current = null
setPreviewingId(null)
setError("试听音频加载失败")
message.error("试听音频加载失败")
}
}
void audio.play().catch(() => {
setPreviewingId(null)
setError("试听播放失败")
message.error("试听播放失败")
})
}
const handlePreview = async (voice: UnifiedVoiceItem) => {
/* 再次点击当前试听音色 → 停止 */
if (previewingId === voice.id) {
stopPreview()
return
}
/* 克隆音色:preview_url/audio_url 通常为空,需走 POST /tts/preview
* 现合成示例文案再播放,对齐配音库 useAudioPlayer 行为 */
if (voice.type === "clone") {
const cached = previewCacheRef.current.get(voice.voice_clone_profile_id || voice.id)
if (cached) {
playAudioUrl(voice.id, cached)
return
}
const targetId = voice.voice_clone_profile_id || voice.id
// DEBUG: 打印请求参数,帮助定位 /tts/preview 失败原因
console.log("[AI数字人-克隆试听] previewTts 请求:", {
voice_id: targetId,
voice_name: voice.name,
voice_type: voice.type,
voice_clone_profile_id: voice.voice_clone_profile_id,
voice_id_field: voice.voice_id,
})
setPreviewingId(voice.id)
try {
const res = await previewTts({
text: VOICE_PREVIEW_TEXT,
voice_id: targetId,
speed: 1.0,
})
console.log("[AI数字人-克隆试听] previewTts 响应:", {
audio_url: res.audio_url?.substring(0, 80),
duration: res.duration,
})
if (!res.audio_url) {
setPreviewingId(null)
message.error("合成试听失败:未返回音频")
return
}
previewCacheRef.current.set(targetId, res.audio_url)
playAudioUrl(voice.id, res.audio_url)
} catch (err) {
setPreviewingId(null)
// DEBUG: 打印详细错误信息
console.error("[AI数字人-克隆试听] previewTts 失败:", {
status: (err as { response?: { status?: number } })?.response?.status,
data: (err as { response?: { data?: unknown } })?.response?.data,
message: err instanceof Error ? err.message : String(err),
})
// apiClient 拦截器已统一 toast
}
return
}
/* 系统预设音色:沿用 preview_url/audio_url 直链播放 */
const url = voice.preview_url || voice.audio_url
if (!url) {
message.warning(NO_PREVIEW_TIP)
return
}
playAudioUrl(voice.id, url)
}
const handleSpeedChange = (value: string) => {
const parsed = parseFloat(value)
if (Number.isNaN(parsed)) return
+2
View File
@@ -44,6 +44,8 @@ export interface LipsyncJob {
status: LipsyncStatus
progress: number
output_video_url: string | null
/** 对口型成片总时长(秒),后端返回;用于 B-roll 时间自动估算(#1809 ⑥) */
output_duration?: number
error_message: string | null
created_at: string
}
@@ -0,0 +1,62 @@
/**
* AI数字人 — 文案分句 & B-roll 时间自动估算(#1809 ⑤⑥)
*/
export interface ScriptSentence {
/** 句子序号(从 0 开始,对应提交给后端的 script_segment_index */
index: number
/** 句子文本(去掉首尾空白) */
text: string
/** 句子字数(按中文/字符计,去除空白) */
charCount: number
/** 累计起始字数(用于时间估算) */
startChar: number
/** 估算的对口型视频内起始时间(秒) */
startTime: number
/** 估算的对口型视频内结束时间(秒) */
endTime: number
}
/**
* 按句号/问号/感叹号/分号/换行分句(兼容中英文标点)。
* 空文案返回空数组。时间按「该句字数 ÷ 全文总字数 × 口播总时长」线性估算。
*/
export function splitScriptIntoSentences(
scriptText: string,
outputDuration: number,
): ScriptSentence[] {
const text = (scriptText || "").trim()
if (!text) return []
const rawParts = text
.split(/[。!?!?;\n\r]+/)
.map((part) => part.trim())
.filter((part) => part.length > 0)
const totalChars = rawParts.reduce((sum, part) => sum + part.replace(/\s/g, "").length, 0)
const duration = outputDuration > 0 ? outputDuration : 0
const sentences: ScriptSentence[] = []
let accChar = 0
rawParts.forEach((part, i) => {
const charCount = part.replace(/\s/g, "").length
const startTime = duration > 0 && totalChars > 0 ? (accChar / totalChars) * duration : 0
const endTime =
duration > 0 && totalChars > 0 ? ((accChar + charCount) / totalChars) * duration : 0
sentences.push({
index: i,
text: part,
charCount,
startChar: accChar,
startTime: round1(startTime),
endTime: round1(endTime),
})
accChar += charCount
})
return sentences
}
function round1(n: number): number {
return Math.round(n * 10) / 10
}
@@ -10,7 +10,7 @@
============================================================ */
.dup-page {
padding: var(--space-2xl) var(--space-lg);
max-width: 1100px;
max-width: 1400px;
margin: 0 auto;
}
+12 -1
View File
@@ -548,10 +548,21 @@ const GeneratePage: React.FC = () => {
<div
style={{
display: "flex",
justifyContent: "center",
flexDirection: "column",
alignItems: "center",
marginTop: 16,
}}
>
<h2
style={{
textAlign: "center",
marginBottom: 12,
fontSize: "1.5rem",
fontWeight: 600,
}}
>
🎬
</h2>
<div
style={{
display: "flex",
@@ -0,0 +1,192 @@
/* ============================================================
TitleStylePanel 标题样式面板 — 独立共用样式(#1809 ⑦)
从 generate.css 抽取的标题样式区块,供「智能剪辑」与「AI数字人」
两个页面共用。AI数字人页面不引入 generate.css,直接由
TitleStylePanel.tsx import 本文件,保证 24 个 T 预设格子的网格布局、
配色描边、选中态与智能剪辑页面完全一致。
注意:本文件规则与 generate.css 中同名规则一一对应、取值相同;
智能剪辑页面两处同时存在时同优先级同值,不改变其原有呈现。
============================================================ */
/* ── 区块容器 ── */
.xx-title-style-section {
margin-top: 22px;
padding-top: 20px;
border-top: 1px solid var(--border-light);
}
.xx-section-subtitle {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
margin: 0 0 16px;
}
.xx-title-style-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
margin-bottom: 14px;
}
.xx-half-field {
margin-bottom: 0;
}
.xx-field-label-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.xx-field-label-row label {
margin-bottom: 0;
}
.xx-field-value {
font-size: 13px;
font-weight: 600;
color: var(--primary-color);
}
/* ── 共用表单字段(位置/字体下拉) ── */
.xx-title-style-section .xx-form-field {
margin-bottom: 14px;
}
.xx-title-style-section .xx-form-field:last-child {
margin-bottom: 0;
}
.xx-title-style-section .xx-form-field label {
display: block;
font-weight: 600;
margin-bottom: 8px;
font-size: 13px;
color: var(--text-primary);
}
.xx-title-style-section .xx-form-field select,
.xx-title-style-section .xx-form-field input {
width: 100%;
height: 44px;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
background: var(--bg-primary);
padding: 0 14px;
font-size: 14px;
outline: 0;
transition: 0.15s ease;
color: var(--text-primary);
}
.xx-title-style-section .xx-form-field select:focus,
.xx-title-style-section .xx-form-field input:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}
/* ── 字号滑块 ── */
.xx-slider {
width: 100%;
height: 6px;
-webkit-appearance: none;
appearance: none;
background: var(--border-color);
border-radius: 3px;
outline: none;
cursor: pointer;
}
.xx-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
background: var(--primary-color);
border-radius: 50%;
cursor: pointer;
box-shadow: 0 2px 6px rgba(79, 70, 229, 0.3);
}
.xx-slider::-moz-range-thumb {
width: 18px;
height: 18px;
background: var(--primary-color);
border-radius: 50%;
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(79, 70, 229, 0.3);
}
/* ── 标题预设卡片网格(24 个 T 格子) ── */
.xx-title-presets-grid {
display: grid;
grid-template-columns: repeat(6, 52px);
gap: 1px;
}
.xx-title-preset-card {
display: flex;
align-items: center;
justify-content: center;
width: 52px;
height: 52px;
padding: 0;
background: #404040;
border: 2px solid transparent;
border-radius: 8px;
cursor: pointer;
transition: all 0.15s;
}
.xx-title-preset-card:hover {
border-color: #666;
background: #4d4d4d;
}
.xx-title-preset-card.active {
border-color: #409eff;
background: #4d4d4d;
}
.xx-title-preset-preview-text {
font-size: 32px;
line-height: 1;
user-select: none;
}
/* ── 样式按钮组(加粗/斜体/描边/阴影) ── */
.xx-style-btns {
display: flex;
gap: 8px;
}
.xx-style-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
background: var(--bg-primary);
cursor: pointer;
font-size: 15px;
color: var(--text-secondary);
transition: all 0.15s;
}
.xx-style-btn:hover {
border-color: var(--primary-300);
color: var(--primary-color);
}
.xx-style-btn.active {
background: var(--primary-color);
border-color: var(--primary-color);
color: #fff;
}
@@ -5,6 +5,9 @@
import React from "react"
import type { TitleSettings } from "../../types"
import TitlePresetsGrid from "./TitlePresetsGrid"
// 标题样式面板共用样式(#1809 ⑦):智能剪辑与 AI数字人复用同一组件,
// 由组件自带样式,避免 AI数字人页面重复引入整个 generate.css
import "./TitleStylePanel.css"
interface PositionOption {
value: string
+1 -1
View File
@@ -10,7 +10,7 @@
.xx-generate-page {
min-height: 100%;
padding: var(--space-xl);
max-width: 1400px;
max-width: 1680px;
margin: 0 auto;
}
@@ -5,7 +5,7 @@
.mt-page {
padding: var(--space-xl);
max-width: 1400px;
max-width: 1680px;
margin: 0 auto;
}
@@ -0,0 +1,273 @@
/**
* 文案库页面 — Issue #1811
* 风格对齐标题库(同类资源管理页面统一风格),单列卡片列表
* 功能:列表 / 新建 / 编辑 / 删除 / 按标题搜索 / 空状态
* 对接后端 /api/v1/scripts CRUD
*/
import React, { useEffect, useMemo, useState } from "react"
import { Modal, message, Empty, Button, Input, Popconfirm } from "antd"
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from "@ant-design/icons"
import {
getScripts,
createScript,
updateScript,
deleteScript,
type ScriptItem,
} from "@/api/scripts"
import "./scripts.css"
const { TextArea } = Input
const ScriptLibrary: React.FC = () => {
const [scripts, setScripts] = useState<ScriptItem[]>([])
const [loading, setLoading] = useState(false)
const [searchText, setSearchText] = useState("")
// 弹窗状态
const [createOpen, setCreateOpen] = useState(false)
const [editing, setEditing] = useState<ScriptItem | null>(null)
const [formTitle, setFormTitle] = useState("")
const [formContent, setFormContent] = useState("")
const [submitting, setSubmitting] = useState(false)
const load = async () => {
setLoading(true)
try {
const items = await getScripts()
setScripts(items)
} catch (err) {
message.error(err instanceof Error ? err.message : "加载文案列表失败")
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
}, [])
const filtered = useMemo(() => {
const kw = searchText.trim().toLowerCase()
if (!kw) return scripts
return scripts.filter((s) => s.title.toLowerCase().includes(kw))
}, [scripts, searchText])
const openCreate = () => {
setFormTitle("")
setFormContent("")
setCreateOpen(true)
}
const openEdit = (item: ScriptItem) => {
setEditing(item)
setFormTitle(item.title)
setFormContent(item.content)
}
const handleCloseCreate = () => {
setCreateOpen(false)
setFormTitle("")
setFormContent("")
}
const handleCloseEdit = () => {
setEditing(null)
setFormTitle("")
setFormContent("")
}
const handleCreate = async () => {
const title = formTitle.trim()
const content = formContent.trim()
if (!title || !content) {
message.warning("请填写标题和正文")
return
}
setSubmitting(true)
try {
await createScript({ title, content })
message.success("文案已创建")
handleCloseCreate()
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : "创建文案失败")
} finally {
setSubmitting(false)
}
}
const handleUpdate = async () => {
if (!editing) return
const title = formTitle.trim()
const content = formContent.trim()
if (!title || !content) {
message.warning("请填写标题和正文")
return
}
setSubmitting(true)
try {
await updateScript(editing.id, { title, content })
message.success("文案已更新")
handleCloseEdit()
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : "更新文案失败")
} finally {
setSubmitting(false)
}
}
const handleDelete = async (id: string) => {
try {
await deleteScript(id)
message.success("文案已删除")
await load()
} catch (err) {
message.error(err instanceof Error ? err.message : "删除文案失败")
}
}
const preview = (content: string) => {
const text = content.replace(/\s+/g, " ").trim()
return text.length > 120 ? `${text.slice(0, 120)}` : text || "(空)"
}
const formatTime = (iso: string) => {
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return iso
const pad = (n: number) => String(n).padStart(2, "0")
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(
d.getHours(),
)}:${pad(d.getMinutes())}`
}
return (
<div className="xx-scripts-page">
<div className="xx-scripts-layout">
{/* 顶部操作栏 */}
<div className="xx-scripts-filters">
<div className="xx-scripts-filters-left">
<Input
prefix={<SearchOutlined />}
placeholder="按标题搜索"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
allowClear
style={{ width: 260 }}
/>
</div>
<div className="xx-scripts-filters-right">
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
</Button>
</div>
</div>
{/* 列表 / 空状态 */}
{loading ? (
<div className="xx-scripts-loading"></div>
) : filtered.length === 0 ? (
<Empty
description={searchText ? "没有匹配的文案" : "暂无文案,点击右上角「新建文案」开始创作"}
/>
) : (
<div className="xx-scripts-list">
{filtered.map((s) => (
<div key={s.id} className="xx-script-card">
<div className="xx-script-card-header">
<div className="xx-script-title">{s.title}</div>
<div className="xx-script-actions">
<Button
size="small"
type="text"
icon={<EditOutlined />}
onClick={() => openEdit(s)}
>
</Button>
<Popconfirm
title="确认删除此文案?"
description="删除后不可恢复"
okText="删除"
cancelText="取消"
okButtonProps={{ danger: true }}
onConfirm={() => handleDelete(s.id)}
>
<Button size="small" type="text" danger icon={<DeleteOutlined />}>
</Button>
</Popconfirm>
</div>
</div>
<div className="xx-script-preview">{preview(s.content)}</div>
<div className="xx-script-meta">
<span>{s.char_count ?? s.content.length} </span>
<span>·</span>
<span>{formatTime(s.created_at)}</span>
</div>
</div>
))}
</div>
)}
</div>
{/* 新建弹窗 */}
<Modal
title="新建文案"
open={createOpen}
onCancel={handleCloseCreate}
onOk={handleCreate}
confirmLoading={submitting}
destroyOnClose
okText="创建"
cancelText="取消"
>
<div className="xx-script-form">
<Input
placeholder="标题"
value={formTitle}
onChange={(e) => setFormTitle(e.target.value)}
maxLength={200}
/>
<TextArea
placeholder="正文"
value={formContent}
onChange={(e) => setFormContent(e.target.value)}
rows={8}
maxLength={5000}
/>
</div>
</Modal>
{/* 编辑弹窗 */}
<Modal
title="编辑文案"
open={!!editing}
onCancel={handleCloseEdit}
onOk={handleUpdate}
confirmLoading={submitting}
destroyOnClose
okText="保存"
cancelText="取消"
>
<div className="xx-script-form">
<Input
placeholder="标题"
value={formTitle}
onChange={(e) => setFormTitle(e.target.value)}
maxLength={200}
/>
<TextArea
placeholder="正文"
value={formContent}
onChange={(e) => setFormContent(e.target.value)}
rows={8}
maxLength={5000}
/>
</div>
</Modal>
</div>
)
}
export default ScriptLibrary
+137
View File
@@ -0,0 +1,137 @@
/**
* 文案库页面 - V21 设计系统样式
* 单列卡片列表,风格对齐标题库(xx-titles-page
*/
@import "../../styles/global.css";
/* ============================================================
页面容器
============================================================ */
.xx-scripts-page {
min-height: 100%;
padding: var(--space-xl);
}
.xx-scripts-layout {
display: flex;
flex-direction: column;
gap: var(--space-lg);
max-width: 960px;
margin: 0 auto;
}
/* ============================================================
顶部筛选栏
============================================================ */
.xx-scripts-filters {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-md);
flex-wrap: wrap;
}
.xx-scripts-filters-left {
display: flex;
align-items: center;
gap: var(--space-sm);
}
.xx-scripts-filters-right {
display: flex;
align-items: center;
gap: var(--space-sm);
}
/* ============================================================
列表
============================================================ */
.xx-scripts-list {
display: flex;
flex-direction: column;
gap: var(--space-sm);
}
.xx-scripts-loading {
text-align: center;
color: var(--text-secondary);
padding: var(--space-xl);
font-size: var(--font-size-sm);
}
/* ============================================================
文案卡片(对齐标题卡片风格,单列)
============================================================ */
.xx-script-card {
border: 1px solid var(--border-color);
background: var(--bg-primary);
border-radius: var(--radius-md);
padding: var(--space-md);
transition: var(--transition-all);
display: flex;
flex-direction: column;
gap: 10px;
}
.xx-script-card:hover {
border-color: var(--primary-color);
background: var(--bg-secondary);
box-shadow: var(--shadow-sm);
}
.xx-script-card-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-md);
}
.xx-script-title {
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
color: var(--text-primary);
line-height: 1.5;
word-break: break-word;
flex: 1;
}
.xx-script-actions {
display: flex;
align-items: center;
gap: var(--space-xxs);
flex-shrink: 0;
opacity: 0;
transition: var(--transition-opacity, opacity 0.2s);
}
.xx-script-card:hover .xx-script-actions {
opacity: 1;
}
.xx-script-preview {
font-size: var(--font-size-sm);
color: var(--text-secondary);
line-height: 1.6;
word-break: break-word;
}
.xx-script-meta {
display: flex;
align-items: center;
gap: var(--space-xs);
font-size: var(--font-size-xs, 12px);
color: var(--text-tertiary);
}
/* ============================================================
弹窗表单
============================================================ */
.xx-script-form {
display: flex;
flex-direction: column;
gap: var(--space-md);
}
.xx-script-form textarea.ant-input {
resize: vertical;
}
+1 -1
View File
@@ -2,7 +2,7 @@
.task-center {
padding: var(--space-lg);
max-width: 1400px;
max-width: 1680px;
margin: 0 auto;
}
+4
View File
@@ -24,6 +24,10 @@ const appChildren: RouteObject[] = [
path: "titles",
lazy: lazyRoute(() => import("@/pages/titles/TitleLibrary")),
},
{
path: "scripts",
lazy: lazyRoute(() => import("@/pages/scripts/ScriptLibrary")),
},
{
path: "voices",
lazy: lazyRoute(() => import("@/pages/voices/VoiceLibrary")),
+2 -2
View File
@@ -192,7 +192,7 @@ rollback() {
-e PUBLIC_API_BASE_URL=https://staging-api.xiaoxiajianji.com \
-v "$GENERATED_DIR:/app/generated" \
--restart unless-stopped \
--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-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 \
@@ -501,7 +501,7 @@ docker run -d \
-e PUBLIC_API_BASE_URL=https://staging-api.xiaoxiajianji.com \
-v "$GENERATED_DIR:/app/generated" \
--restart unless-stopped \
--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-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 \
+212 -46
View File
@@ -1,4 +1,4 @@
"""对口型 API 路由 + Service 单元测试 — #1796.
"""对口型 API 路由 + Service 单元测试 — #1796, #1809 参数调整.
CI 增量映射: lipsync.py (route) + lipsync_service.py → test_lipsync_routes.py
"""
@@ -33,6 +33,19 @@ def mock_mediakit():
return client
@pytest.fixture
def mock_cosyvoice():
"""Mock CosyVoice 服务."""
service = MagicMock()
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
def _make_mock_job(
job_id="job-1",
user_id="user-1",
@@ -48,7 +61,7 @@ def _make_mock_job(
m.user_id = user_id
m.project_id = ""
m.video_url = "https://example.com/video.mp4"
m.audio_url = "https://example.com/audio.mp3"
m.audio_url = "https://oss.example.com/tts-output.mp3"
m.enable_video_loop = False
m.mediakit_task_id = mediakit_task_id
m.status = status
@@ -64,16 +77,19 @@ def _make_mock_job(
class TestSchemaValidation:
"""Schema 验证测试."""
"""Schema 验证测试 — #1809 新参数结构."""
def test_valid_video_url(self):
def test_valid_request(self):
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.video_url == "https://example.com/video.mp4"
assert req.voice_id == "longxiaochun_v3"
assert req.script_text == "大家好,欢迎来到直播间"
def test_invalid_video_url_not_mp4(self):
from app.schemas.lipsync import CreateLipsyncJobRequest
@@ -81,7 +97,8 @@ class TestSchemaValidation:
with pytest.raises(ValueError, match="MP4"):
CreateLipsyncJobRequest(
video_url="https://example.com/video.mov",
audio_url="https://example.com/audio.mp3",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
def test_invalid_video_url_empty(self):
@@ -90,7 +107,8 @@ class TestSchemaValidation:
with pytest.raises(ValueError, match="不能为空"):
CreateLipsyncJobRequest(
video_url=" ",
audio_url="https://example.com/audio.mp3",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
def test_invalid_video_url_not_http(self):
@@ -99,26 +117,38 @@ class TestSchemaValidation:
with pytest.raises(ValueError, match="HTTP"):
CreateLipsyncJobRequest(
video_url="ftp://example.com/video.mp4",
audio_url="https://example.com/audio.mp3",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
def test_valid_audio_formats(self):
def test_empty_voice_id_rejected(self):
from app.schemas.lipsync import CreateLipsyncJobRequest
for ext in [".mp3", ".aac", ".wav", ".m4a", ".flac"]:
req = CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4",
audio_url=f"https://example.com/audio{ext}",
)
assert req.audio_url.endswith(ext)
def test_invalid_audio_format(self):
from app.schemas.lipsync import CreateLipsyncJobRequest
with pytest.raises(ValueError, match="格式不支持"):
with pytest.raises(ValueError, match="voice_id"):
CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4",
audio_url="https://example.com/audio.ogg",
voice_id=" ",
script_text="测试文本",
)
def test_empty_script_text_rejected(self):
from app.schemas.lipsync import CreateLipsyncJobRequest
with pytest.raises(ValueError, match="script_text"):
CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4",
voice_id="longxiaochun_v3",
script_text="",
)
def test_script_text_too_long(self):
from app.schemas.lipsync import CreateLipsyncJobRequest
with pytest.raises(ValueError, match="5000"):
CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4",
voice_id="longxiaochun_v3",
script_text="x" * 5001,
)
def test_enable_video_loop_default(self):
@@ -126,7 +156,8 @@ class TestSchemaValidation:
req = CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4",
audio_url="https://example.com/audio.mp3",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
assert req.enable_video_loop is False
@@ -136,53 +167,111 @@ class TestSchemaValidation:
req = CreateLipsyncJobRequest(
video_url="https://example.com/video.mp4?token=abc",
audio_url="https://example.com/audio.mp3?sign=xyz",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
assert "?token=" in req.video_url
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",
voice_id="longxiaochun_v3",
script_text="测试文本",
)
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,不依赖数据库)."""
"""Service 层单元测试(纯 mock,不依赖数据库)— #1809 更新."""
def test_create_job_success(self, mock_mediakit):
def test_create_job_success(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_db = MagicMock()
svc = LipsyncService(mock_db, client=mock_mediakit)
# 模拟 db.add + db.flush 不报错
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)
job = 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="大家好,欢迎来到直播间",
)
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"
def test_create_job_api_failure(self, mock_mediakit):
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="测试文本",
)
# 不应提交到 MediaKit
mock_mediakit.submit_lipsync.assert_not_called()
# 应该记录了失败状态
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, 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):
def test_get_job_delegates_to_db(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_job = _make_mock_job()
@@ -193,13 +282,13 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.get_job("job-1", "user-1")
assert result is mock_job
mock_db.query.assert_called_once()
def test_get_job_not_found(self, mock_mediakit):
def test_get_job_not_found(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_db = MagicMock()
@@ -209,11 +298,11 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.get_job("nonexistent", "user-1")
assert result is None
def test_refresh_job_completed(self, mock_mediakit):
def test_refresh_job_completed(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_job = _make_mock_job(status="submitted")
@@ -224,14 +313,14 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.refresh_job_status("job-1", "user-1")
assert result.status == "completed"
assert result.output_video_url == "https://output.mp4"
assert result.output_duration == 30.0
def test_refresh_job_failed(self, mock_mediakit):
def test_refresh_job_failed(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_mediakit.get_task_status.return_value = {
@@ -251,13 +340,13 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.refresh_job_status("job-1", "user-1")
assert result.status == "failed"
assert result.error_code == "DownloadFailed"
def test_refresh_job_already_completed(self, mock_mediakit):
def test_refresh_job_already_completed(self, mock_mediakit, mock_cosyvoice):
"""已完成的任务不轮询."""
from app.services.lipsync_service import LipsyncService
@@ -269,14 +358,14 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.refresh_job_status("job-1", "user-1")
# 不应调用 MediaKit
mock_mediakit.get_task_status.assert_not_called()
assert result.status == "completed"
def test_cancel_job_pending(self, mock_mediakit):
def test_cancel_job_pending(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_job = _make_mock_job(status="pending")
@@ -287,12 +376,12 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.cancel_job("job-1", "user-1")
assert result.status == "cancelled"
def test_cancel_job_completed_not_allowed(self, mock_mediakit):
def test_cancel_job_completed_not_allowed(self, mock_mediakit, mock_cosyvoice):
from app.services.lipsync_service import LipsyncService
mock_job = _make_mock_job(status="completed")
@@ -303,8 +392,85 @@ class TestLipsyncServiceUnit:
mock_query.filter.return_value = mock_filter
mock_db.query.return_value = mock_query
svc = LipsyncService(mock_db, client=mock_mediakit)
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
result = svc.cancel_job("job-1", "user-1")
# 已完成不可取消
assert result.status == "completed"
def test_create_job_stores_tts_audio_url(self, mock_mediakit, mock_cosyvoice):
"""#1809: 验证 job 的 audio_url 来自 TTS 合成结果."""
from app.services.lipsync_service import LipsyncService
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)
job = svc.create_job(
user_id="user-1",
video_url="https://example.com/video.mp4",
voice_id="my-clone-voice",
script_text="这是一段测试文本",
)
# job.audio_url 应该是 TTS 返回的 URL
assert job.audio_url == "https://oss.example.com/tts-output.mp3"
class TestErrorHandling:
"""#1809 补充:错误返回 400 而非 500."""
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_repo = MagicMock()
mock_repo.get.side_effect = Exception("DB connection error")
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)
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.synthesize_speech.side_effect = ValueError("voice_id 为空")
mock_db = MagicMock()
svc = LipsyncService(mock_db, client=mock_mediakit, cosyvoice_service=mock_cosyvoice)
# 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="",
script_text="test",
)
def test_create_job_unexpected_exception_returns_400(self, mock_mediakit):
"""未预期的异常应被路由层捕获返回 400 而非 500."""
from app.services.lipsync_service import LipsyncService
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)
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",
)