Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ae78918ae4 | |||
| ee2cc0e7a1 | |||
| be0b4f4dac | |||
| 1e16e81344 | |||
| 7a72cfd709 | |||
| b82b303d6a | |||
| baa3bf6300 | |||
| d7788013de | |||
| ff3038a291 | |||
| 10f9e67c8e | |||
| c192398db6 | |||
| 17cf970ae6 | |||
| 5b21763aea | |||
| c90b4819c0 | |||
| 464f6ea155 | |||
| d2bdb462c6 | |||
| 745c851758 | |||
| 18bd0de3fa | |||
| 04bcd2e6f9 | |||
| f7151ea2be | |||
| cea83329c8 | |||
| 2df7bc9dc8 | |||
| f6a1798124 | |||
| 3ca32f3532 | |||
| 03b42e1561 | |||
| 972ff89990 | |||
| 37d111dcd5 | |||
| 0e86062f17 | |||
| 6e70a7ad29 | |||
| c9c7da0c74 | |||
| cf544881fd | |||
| 42f92017de | |||
| 58fe71c483 | |||
| 3ae15eb4fc | |||
| 68e55df83b | |||
| 78afa40458 | |||
| e38f13eb96 | |||
| 42335eff42 | |||
| 9a51cad137 |
@@ -26,7 +26,7 @@ concurrency:
|
||||
cancel-in-progress: ${{ gitea.event_name == 'pull_request' }}
|
||||
env:
|
||||
CI_PG_HOST: host.docker.internal
|
||||
CI_PG_PORT: "5432"
|
||||
CI_LOCAL_PG_PORT: "5432"
|
||||
CI_PG_USER: postgres
|
||||
CI_PG_PASSWORD: postgres
|
||||
CI_PG_DB: xiaoxia_saas
|
||||
@@ -262,7 +262,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
DATABASE_URL: postgresql+psycopg://${{ env.CI_PG_USER }}:${{ env.CI_PG_PASSWORD }}@${{ env.CI_PG_HOST }}:${{ env.CI_PG_PORT }}/${{ env.CI_PG_DB }}
|
||||
DATABASE_URL: postgresql+psycopg://${{ env.CI_PG_USER }}:${{ env.CI_PG_PASSWORD }}@${{ env.CI_PG_HOST }}:${{ env.CI_LOCAL_PG_PORT }}/${{ env.CI_PG_DB }}
|
||||
USE_IN_MEMORY_DB: 'false'
|
||||
CI_USE_SHARED_PG: 'true'
|
||||
steps:
|
||||
@@ -346,6 +346,7 @@ jobs:
|
||||
OSS_ACCESS_KEY_SECRET: placeholder
|
||||
OSS_BUCKET_NAME: xiaoxia-autocut
|
||||
OSS_ENDPOINT: oss-cn-hangzhou.aliyuncs.com
|
||||
JWT_SECRET_KEY: test-jwt-secret-for-ci-only-2026
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
@@ -410,13 +411,14 @@ jobs:
|
||||
- validate-type-check
|
||||
- validate-migration
|
||||
env:
|
||||
DATABASE_URL: postgresql+psycopg://${{ env.CI_PG_USER }}:${{ env.CI_PG_PASSWORD }}@${{ env.CI_PG_HOST }}:${{ env.CI_PG_PORT }}/${{ env.CI_PG_DB }}
|
||||
DATABASE_URL: postgresql+psycopg://${{ env.CI_PG_USER }}:${{ env.CI_PG_PASSWORD }}@${{ env.CI_PG_HOST }}:${{ env.CI_LOCAL_PG_PORT }}/${{ env.CI_PG_DB }}
|
||||
USE_IN_MEMORY_DB: 'false'
|
||||
CI_USE_SHARED_PG: 'true'
|
||||
OSS_ACCESS_KEY_ID: placeholder
|
||||
OSS_ACCESS_KEY_SECRET: placeholder
|
||||
OSS_BUCKET_NAME: xiaoxia-autocut
|
||||
OSS_ENDPOINT: oss-cn-hangzhou.aliyuncs.com
|
||||
JWT_SECRET_KEY: test-jwt-secret-for-ci-only-2026
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
@@ -638,65 +640,83 @@ jobs:
|
||||
echo "Docker login failed ($i/3), retrying in 5s..."
|
||||
sleep 5
|
||||
done
|
||||
- name: Pre-build worker base images (fallback if not exist)
|
||||
- name: Pre-build worker base images (3-level cache)
|
||||
if: matrix.service == 'worker'
|
||||
id: prebuild
|
||||
shell: sh
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
REGISTRY="git.xiaoxiajianji.com/xiaoxia-saas"
|
||||
BASE_BUILDER="${REGISTRY}/worker-base-builder:latest"
|
||||
BASE_RUNTIME="${REGISTRY}/worker-base-runtime:latest"
|
||||
|
||||
# 尝试拉取基础镜像
|
||||
echo "检查基础镜像..."
|
||||
if docker pull "$BASE_BUILDER" 2>/dev/null && docker pull "$BASE_RUNTIME" 2>/dev/null; then
|
||||
echo "基础镜像已存在,使用远程镜像"
|
||||
echo "fallback=false" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "基础镜像不存在,本地构建(fallback模式)..."
|
||||
|
||||
# 构建builder基础镜像
|
||||
echo "构建 worker-base-builder..."
|
||||
# 用buildx docker-container驱动构建(兼容DooD模式:普通docker build看不到容器内文件)
|
||||
BUILDER_NAME="ci-pr-builder-${GITHUB_RUN_ID:-local}"
|
||||
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
else
|
||||
docker buildx use "$BUILDER_NAME"
|
||||
fi
|
||||
docker buildx inspect --bootstrap > /dev/null 2>&1
|
||||
|
||||
# 构建builder基础镜像(带重试,buildx容器偶发不稳定)
|
||||
echo "构建 worker-base-builder..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-builder.Dockerfile -t "$BASE_BUILDER" .; then
|
||||
echo "worker-base-builder 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-builder 构建失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
# 构建runtime基础镜像
|
||||
echo "构建 worker-base-runtime..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-runtime.Dockerfile -t "$BASE_RUNTIME" .; then
|
||||
echo "worker-base-runtime 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-runtime 构建失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
echo "fallback=true" >> $GITHUB_OUTPUT
|
||||
echo "基础镜像本地构建完成"
|
||||
fi
|
||||
GITEA_REGISTRY="git.xiaoxiajianji.com/xiaoxia-saas"
|
||||
ACR_REGISTRY="xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com/xiaoxiakeji"
|
||||
GITEA_BUILDER="${GITEA_REGISTRY}/worker-base-builder:latest"
|
||||
GITEA_RUNTIME="${GITEA_REGISTRY}/worker-base-runtime:latest"
|
||||
ACR_BUILDER="${ACR_REGISTRY}/worker-base-builder:latest"
|
||||
ACR_RUNTIME="${ACR_REGISTRY}/worker-base-runtime:latest"
|
||||
|
||||
# L1: 本地daemon缓存(DooD模式8runner共享宿主机daemon)
|
||||
echo "=== L1 本地缓存 ==="
|
||||
if docker image inspect "$ACR_BUILDER" > /dev/null 2>&1 \
|
||||
&& docker image inspect "$ACR_RUNTIME" > /dev/null 2>&1; then
|
||||
echo "本地缓存命中"
|
||||
echo "has_local_base=true" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
echo "本地无缓存"
|
||||
|
||||
# L2: Gitea registry缓存(内网快)
|
||||
echo "=== L2 Registry拉取 ==="
|
||||
if docker pull "$GITEA_BUILDER" 2>/dev/null && docker pull "$GITEA_RUNTIME" 2>/dev/null; then
|
||||
echo "Registry拉取成功,重tag供Dockerfile使用"
|
||||
docker tag "$GITEA_BUILDER" "$ACR_BUILDER"
|
||||
docker tag "$GITEA_RUNTIME" "$ACR_RUNTIME"
|
||||
echo "has_local_base=true" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
echo "Registry无缓存,需本地构建"
|
||||
|
||||
# L3: 本地构建
|
||||
echo "=== L3 本地构建 ==="
|
||||
BUILDER_NAME="ci-pr-builder-${GITHUB_RUN_ID:-local}"
|
||||
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
else
|
||||
docker buildx use "$BUILDER_NAME"
|
||||
fi
|
||||
docker buildx inspect --bootstrap > /dev/null 2>&1
|
||||
|
||||
echo "构建 worker-base-builder..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-builder.Dockerfile -t "$ACR_BUILDER" .; then
|
||||
echo "worker-base-builder 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-builder 失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
echo "构建 worker-base-runtime..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-runtime.Dockerfile -t "$ACR_RUNTIME" .; then
|
||||
echo "worker-base-runtime 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-runtime 失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
# 推送到Gitea registry供后续复用
|
||||
echo "=== 推送缓存到Registry ==="
|
||||
docker tag "$ACR_BUILDER" "$GITEA_BUILDER"
|
||||
docker tag "$ACR_RUNTIME" "$GITEA_RUNTIME"
|
||||
docker push "$GITEA_BUILDER" 2>/dev/null || echo "push builder失败(不影响)"
|
||||
docker push "$GITEA_RUNTIME" 2>/dev/null || echo "push runtime失败(不影响)"
|
||||
|
||||
echo "has_local_base=true" >> $GITHUB_OUTPUT
|
||||
echo "基础镜像构建完成"
|
||||
- name: Build PR image (verify only, no push)
|
||||
shell: sh
|
||||
run: |
|
||||
@@ -710,15 +730,15 @@ jobs:
|
||||
EXTRA_BUILD_ARGS="$EXTRA_BUILD_ARGS NGINX_CONF=infra/docker/nginx-staging.conf"
|
||||
fi
|
||||
|
||||
# Worker fallback模式:基础镜像本地已构建,用普通docker build绕过buildx
|
||||
if [ "${{ matrix.service }}" = "worker" ] && [ "${{ steps.prebuild.outputs.fallback }}" = "true" ]; then
|
||||
echo "Fallback模式:用普通docker build(基础镜像本地已构建)"
|
||||
# Worker有本地base镜像时:用BuildKit直接构建(快,无需起buildx容器)
|
||||
if [ "${{ matrix.service }}" = "worker" ] && [ "${{ steps.prebuild.outputs.has_local_base }}" = "true" ]; then
|
||||
echo "本地base镜像已就绪,BuildKit快速构建"
|
||||
BUILD_ARG_STR=""
|
||||
for arg in $EXTRA_BUILD_ARGS; do
|
||||
BUILD_ARG_STR="$BUILD_ARG_STR --build-arg $arg"
|
||||
done
|
||||
docker build -f ${{ matrix.dockerfile }} -t "${IMAGE_TAG}" $BUILD_ARG_STR .
|
||||
echo "Fallback PR Build successful"
|
||||
DOCKER_BUILDKIT=1 docker build -f ${{ matrix.dockerfile }} -t "${IMAGE_TAG}" $BUILD_ARG_STR .
|
||||
echo "快速构建成功"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
@@ -115,11 +115,11 @@ jobs:
|
||||
fi
|
||||
if [ "$CACHE_VALID" = "false" ]; then
|
||||
echo "Cache miss or invalid: running npm ci..."
|
||||
if ! npm ci --include=dev; then
|
||||
if ! npm ci; then
|
||||
echo "npm ci failed, cleaning node_modules and retrying..."
|
||||
rm -rf node_modules
|
||||
mkdir -p node_modules
|
||||
npm ci --include=dev
|
||||
npm ci
|
||||
fi
|
||||
echo "$PACKAGE_LOCK_HASH" > "$CACHE_HASH_FILE"
|
||||
echo "Dependencies installed, cache updated"
|
||||
|
||||
Generated
+4653
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Step 1 模板选择组件
|
||||
*/
|
||||
import React from "react"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
import { MODE_GRADIENTS } from "../constants"
|
||||
import { useStep1Template } from "../hooks/useStep1Template"
|
||||
|
||||
interface Step1TemplateSelectProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
onSelectTemplate: (id: string) => void
|
||||
}
|
||||
|
||||
const Step1TemplateSelect: React.FC<Step1TemplateSelectProps> = (props) => {
|
||||
const { templates, selectedTemplate, handleSelect, handleKeySelect } = useStep1Template(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>🎨 选择模板</h3>
|
||||
{templates.length === 0 ? (
|
||||
<div className="xx-empty-state">
|
||||
<p>暂无可用模板</p>
|
||||
<p style={{ fontSize: 13, color: "var(--text-tertiary)" }}>
|
||||
请先在「模板编辑器」中创建模板
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="xx-choice-list">
|
||||
{templates.map((tpl) => (
|
||||
<div
|
||||
key={tpl.id}
|
||||
className={`xx-choice-item ${selectedTemplate === tpl.id ? "selected" : ""}`}
|
||||
onClick={() => handleSelect(tpl.id)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-pressed={selectedTemplate === tpl.id}
|
||||
onKeyDown={(e) => handleKeySelect(e, tpl.id)}
|
||||
>
|
||||
<span className="xx-choice-check">✓</span>
|
||||
<div
|
||||
className="xx-choice-thumb"
|
||||
style={{
|
||||
background: MODE_GRADIENTS[tpl.mode] || MODE_GRADIENTS.pip,
|
||||
}}
|
||||
>
|
||||
🎬
|
||||
</div>
|
||||
<h4>{tpl.name}</h4>
|
||||
<p>
|
||||
{tpl.estimated_duration}s · {tpl.segments.length}片段
|
||||
</p>
|
||||
{tpl.tags.length > 0 && (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: 4,
|
||||
flexWrap: "wrap",
|
||||
marginTop: 4,
|
||||
}}
|
||||
>
|
||||
{tpl.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
style={{
|
||||
fontSize: 11,
|
||||
padding: "1px 6px",
|
||||
borderRadius: 6,
|
||||
background: "var(--bg-secondary)",
|
||||
color: "var(--text-secondary)",
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step1TemplateSelect
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Step 2 素材选择组件
|
||||
*/
|
||||
import React from "react"
|
||||
import { useStep2Materials } from "../hooks/useStep2Materials"
|
||||
import MaterialModeTabs from "./material/MaterialModeTabs"
|
||||
import ManualMaterialList from "./material/ManualMaterialList"
|
||||
import SmartMatchInput from "./material/SmartMatchInput"
|
||||
import SmartMatchResults from "./material/SmartMatchResults"
|
||||
|
||||
interface Step2MaterialSelectProps {
|
||||
materialMode: "manual" | "auto"
|
||||
onMaterialModeChange: (mode: "manual" | "auto") => void
|
||||
selectedMaterials: string[]
|
||||
onSelectedMaterialsChange: (ids: string[]) => void
|
||||
smartSelectedIds: string[]
|
||||
onSmartSelectedIdsChange: (ids: string[]) => void
|
||||
}
|
||||
|
||||
const Step2MaterialSelect: React.FC<Step2MaterialSelectProps> = (props) => {
|
||||
const m = useStep2Materials(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>📦 选择素材</h3>
|
||||
|
||||
<MaterialModeTabs mode={m.materialMode} onModeChange={m.onMaterialModeChange} />
|
||||
|
||||
<div className="xx-form-field" style={{ marginTop: 12 }}>
|
||||
<label>选择视频库</label>
|
||||
<select
|
||||
value={m.selectedLibraryId}
|
||||
onChange={(e) => m.setSelectedLibraryId(e.target.value)}
|
||||
>
|
||||
{m.libraries.map((lib) => (
|
||||
<option key={lib.id} value={lib.id}>
|
||||
{lib.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{m.materialMode === "manual" && (
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 14,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 10,
|
||||
}}
|
||||
>
|
||||
<span className="xx-pill xx-pill-ok">已选 {m.selectedMaterials.length} 个素材</span>
|
||||
</div>
|
||||
|
||||
<ManualMaterialList
|
||||
materials={m.materials}
|
||||
materialsLoading={m.materialsLoading}
|
||||
selectedMaterials={m.selectedMaterials}
|
||||
onToggle={m.handleToggleMaterial}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{m.materialMode === "auto" && (
|
||||
<div className="xx-smart-match-section">
|
||||
<SmartMatchInput
|
||||
inputValue={m.smartMatchInput}
|
||||
onInputChange={m.setSmartMatchInput}
|
||||
matching={m.smartMatching}
|
||||
onMatch={m.handleSmartMatch}
|
||||
hasMatched={m.hasMatched}
|
||||
onRefresh={m.handleRefreshMatch}
|
||||
materialsCount={m.materials.items.length}
|
||||
loading={m.materialsLoading}
|
||||
/>
|
||||
|
||||
<SmartMatchResults
|
||||
results={m.smartMatchedResults}
|
||||
selectedIds={m.smartSelectedIds}
|
||||
matching={m.smartMatching}
|
||||
hasMatched={m.hasMatched}
|
||||
onToggle={m.handleToggleSmartSelect}
|
||||
onSelectAll={m.handleSelectAllMatched}
|
||||
onClear={m.handleClearSmartSelect}
|
||||
formatDuration={m.formatDuration}
|
||||
selectedTotalDuration={m.smartSelectedTotalDuration}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step2MaterialSelect
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Step 3 生成预览组件
|
||||
*/
|
||||
import React from "react"
|
||||
import { CheckCircleFilled } from "@ant-design/icons"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
import { useStep3Preview } from "../hooks/useStep3Preview"
|
||||
|
||||
interface Step3GeneratePreviewProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
materialMode: "manual" | "auto"
|
||||
selectedMaterials: string[]
|
||||
smartSelectedIds: string[]
|
||||
duration: number
|
||||
videoRatio: string
|
||||
}
|
||||
|
||||
const Step3GeneratePreview: React.FC<Step3GeneratePreviewProps> = (props) => {
|
||||
const { templateName, materialCount, duration, videoRatio } = useStep3Preview(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>🎬 生成预览</h3>
|
||||
<div className="xx-preview-tip">
|
||||
<CheckCircleFilled style={{ color: "#52c41a", marginRight: 8 }} />
|
||||
<span>素材已选好,AI 将为您智能匹配剪辑方案</span>
|
||||
</div>
|
||||
<div className="xx-preview-plan-card">
|
||||
<div className="xx-preview-plan-title">模板草稿预览</div>
|
||||
<div className="xx-preview-plan-info">
|
||||
<div className="xx-preview-plan-row">
|
||||
<span className="xx-preview-plan-label">模板</span>
|
||||
<span className="xx-preview-plan-value">{templateName}</span>
|
||||
</div>
|
||||
<div className="xx-preview-plan-row">
|
||||
<span className="xx-preview-plan-label">素材数量</span>
|
||||
<span className="xx-preview-plan-value">{materialCount}</span>
|
||||
</div>
|
||||
<div className="xx-preview-plan-row">
|
||||
<span className="xx-preview-plan-label">预计时长</span>
|
||||
<span className="xx-preview-plan-value">{duration} 秒</span>
|
||||
</div>
|
||||
<div className="xx-preview-plan-row">
|
||||
<span className="xx-preview-plan-label">视频比例</span>
|
||||
<span className="xx-preview-plan-value">{videoRatio}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="xx-preview-plan-hint">
|
||||
💡 点击「下一步」进入标题设置,AI 将根据素材内容为您推荐标题
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step3GeneratePreview
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Step 4 标题设置组件
|
||||
*/
|
||||
import React from "react"
|
||||
import { Select } from "antd"
|
||||
import { POSITION_OPTIONS, FONT_OPTIONS } from "../constants"
|
||||
import type { TitleSettings } from "../types"
|
||||
import { useStep4Title } from "../hooks/useStep4Title"
|
||||
import AiTitleGenerator from "./title/AiTitleGenerator"
|
||||
import TitleStylePanel from "./title/TitleStylePanel"
|
||||
|
||||
interface Step4TitleSettingsProps {
|
||||
titleSettings: TitleSettings
|
||||
onTitleSettingsChange: (settings: TitleSettings) => void
|
||||
}
|
||||
|
||||
const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
|
||||
const t = useStep4Title(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>📝 选择标题</h3>
|
||||
|
||||
<AiTitleGenerator
|
||||
inputValue={t.aiTitleInput}
|
||||
onInputChange={t.setAiTitleInput}
|
||||
generating={t.aiTitleGenerating}
|
||||
onGenerate={t.handleGenerateAiTitles}
|
||||
results={t.aiTitleResults}
|
||||
hasGenerated={t.hasGeneratedTitles}
|
||||
onSelect={t.handleSelectAiTitle}
|
||||
selectedTitle={t.titleSettings.title}
|
||||
onRefresh={t.handleRefreshAiTitles}
|
||||
/>
|
||||
|
||||
<div className="xx-divider">
|
||||
<span>或手动选择</span>
|
||||
</div>
|
||||
|
||||
<div className="xx-title-ai-toggle">
|
||||
<span className="xx-toggle-label">AI 自动选择标题</span>
|
||||
<div
|
||||
className={`xx-switch ${t.titleSettings.aiAutoSelect ? "active" : ""}`}
|
||||
onClick={t.toggleAiAutoSelect}
|
||||
>
|
||||
<div className="xx-switch-knob" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!t.titleSettings.aiAutoSelect && (
|
||||
<>
|
||||
<div className="xx-form-field">
|
||||
<label>从标题库选择</label>
|
||||
<Select
|
||||
placeholder="请选择标题…"
|
||||
allowClear
|
||||
showSearch
|
||||
style={{ width: "100%" }}
|
||||
value={t.titleSettings.title || undefined}
|
||||
onChange={(val) => t.updateTitle(val || "")}
|
||||
options={t.userTitles.map((ut) => ({
|
||||
label: ut.content,
|
||||
value: ut.content,
|
||||
}))}
|
||||
filterOption={(input, option) =>
|
||||
((option?.label as string) || "").toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
notFoundContent={
|
||||
t.userTitles.length === 0 ? (
|
||||
<span style={{ color: "var(--text-tertiary)", fontSize: 13 }}>
|
||||
标题库为空,请前往「标题管理」添加
|
||||
</span>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="xx-form-field" style={{ marginTop: 14 }}>
|
||||
<label>或手动输入</label>
|
||||
<input
|
||||
placeholder="输入自定义标题…"
|
||||
value={t.titleSettings.title}
|
||||
onChange={(e) => t.updateTitle(e.target.value)}
|
||||
maxLength={50}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TitleStylePanel
|
||||
settings={t.titleSettings}
|
||||
onUpdatePosition={t.updatePosition}
|
||||
onUpdateFont={t.updateFont}
|
||||
onUpdateSize={t.updateSize}
|
||||
onToggleBold={t.toggleBold}
|
||||
onToggleItalic={t.toggleItalic}
|
||||
onToggleStroke={t.toggleStroke}
|
||||
onToggleShadow={t.toggleShadow}
|
||||
onApplyPreset={t.applyPreset}
|
||||
activePreset={t.activePreset}
|
||||
titlePresets={t.titlePresets}
|
||||
POSITION_OPTIONS={POSITION_OPTIONS}
|
||||
FONT_OPTIONS={FONT_OPTIONS}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step4TitleSettings
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Step 5 配音选择组件
|
||||
*/
|
||||
import React from "react"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
import { useStep5Voice } from "../hooks/useStep5Voice"
|
||||
import VoiceRecommendSection from "./voice/VoiceRecommendSection"
|
||||
import VoiceChoiceCard from "./voice/VoiceChoiceCard"
|
||||
import PresetVoiceDetail from "./voice/PresetVoiceDetail"
|
||||
import CustomVoicePanel from "./voice/CustomVoicePanel"
|
||||
import SaveVoiceModal from "./voice/SaveVoiceModal"
|
||||
import CloneVoiceSection from "./voice/CloneVoiceSection"
|
||||
|
||||
interface Step5VoiceSelectProps {
|
||||
selectedVoice: string
|
||||
onSelectedVoiceChange: (voiceId: string) => void
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
onVoiceModeChange: (mode: "preset" | "custom" | "clone") => void
|
||||
selectedClonedVoice: string
|
||||
onSelectedClonedVoiceChange: (voiceId: string) => void
|
||||
clonedVoices: VoiceClone[]
|
||||
addClone: (voice: VoiceClone) => void
|
||||
hasProcessing: boolean
|
||||
cloneModalOpen: boolean
|
||||
onCloneModalOpenChange: (open: boolean) => void
|
||||
titleText: string
|
||||
}
|
||||
|
||||
const Step5VoiceSelect: React.FC<Step5VoiceSelectProps> = (props) => {
|
||||
const v = useStep5Voice(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>🎙️ 选择配音</h3>
|
||||
|
||||
<VoiceRecommendSection
|
||||
presetVoices={v.presetVoices}
|
||||
voiceRecommendLoading={v.voiceRecommendLoading}
|
||||
voiceRecommendations={v.voiceRecommendations}
|
||||
hasVoiceRecommend={v.hasVoiceRecommend}
|
||||
onRecommend={v.handleVoiceRecommend}
|
||||
onSelectVoice={v.handleSelectRecommendedVoice}
|
||||
selectedVoiceId={v.selectedVoice}
|
||||
voiceMode={v.voiceMode}
|
||||
VOICE_GENDER_ICON={v.VOICE_GENDER_ICON}
|
||||
/>
|
||||
|
||||
<div className="xx-divider">
|
||||
<span>全部音色</span>
|
||||
</div>
|
||||
|
||||
<div className="xx-voice-choice-list" style={{ marginBottom: 16 }}>
|
||||
{v.presetVoices.slice(0, 3).map((pv) => (
|
||||
<VoiceChoiceCard
|
||||
key={pv.voice_id}
|
||||
selected={v.voiceMode === "preset" && v.selectedVoice === pv.voice_id}
|
||||
onClick={() => v.handleSelectPresetVoice(pv.voice_id)}
|
||||
avatar={v.VOICE_GENDER_ICON[pv.gender] ?? "✨"}
|
||||
title={pv.name}
|
||||
description={pv.description}
|
||||
/>
|
||||
))}
|
||||
{v.presetVoicesLoading && (
|
||||
<VoiceChoiceCard
|
||||
selected={false}
|
||||
onClick={() => {}}
|
||||
avatar="⏳"
|
||||
title="加载中…"
|
||||
loading
|
||||
/>
|
||||
)}
|
||||
<VoiceChoiceCard
|
||||
selected={v.voiceMode === "clone"}
|
||||
onClick={v.handleSelectCloneVoice}
|
||||
avatar="🎤"
|
||||
title="克隆我的声音"
|
||||
description="上传语音样本克隆"
|
||||
avatarStyle={{ background: "linear-gradient(135deg, #10b981, #059669)" }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{v.voiceMode === "preset" && (
|
||||
<PresetVoiceDetail
|
||||
presetVoices={v.presetVoices}
|
||||
selectedVoice={v.selectedVoice}
|
||||
onSelect={v.handleSelectPresetVoice}
|
||||
playingVoice={v.playingVoice}
|
||||
onTogglePlay={v.toggleVoicePlay}
|
||||
presetVoicesLoading={v.presetVoicesLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
{v.voiceMode === "custom" && (
|
||||
<>
|
||||
<CustomVoicePanel
|
||||
customVoiceText={v.customVoiceText}
|
||||
onTextChange={v.setCustomVoiceText}
|
||||
synthesizePending={v.synthesizeMutation.isPending}
|
||||
onSynthesize={v.handleSynthesizeVoice}
|
||||
ttsError={v.ttsError}
|
||||
customAudioUrl={v.customAudioUrl}
|
||||
completedTtsJobId={v.completedTtsJobId}
|
||||
onOpenSaveModal={v.handleOpenSaveModal}
|
||||
/>
|
||||
<SaveVoiceModal
|
||||
open={v.saveModalOpen}
|
||||
onClose={() => v.setSaveModalOpen(false)}
|
||||
saveName={v.saveName}
|
||||
onNameChange={v.setSaveName}
|
||||
saveTagIds={v.saveTagIds}
|
||||
onTagIdsChange={v.setSaveTagIds}
|
||||
saveNewTag={v.saveNewTag}
|
||||
onNewTagChange={v.setSaveNewTag}
|
||||
onAddTag={v.handleAddTagInModal}
|
||||
allTags={v.allTags}
|
||||
savePending={v.saveToLibraryMutation.isPending}
|
||||
onConfirm={v.handleConfirmSave}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{v.voiceMode === "clone" && (
|
||||
<CloneVoiceSection
|
||||
clonedVoices={v.clonedVoices}
|
||||
hasProcessing={v.hasProcessing}
|
||||
selectedClonedVoice={v.selectedClonedVoice}
|
||||
onSelect={v.handleSelectClonedVoice}
|
||||
onOpenCloneModal={v.handleOpenCloneModal}
|
||||
CLONE_STATUS_CONFIG={v.CLONE_STATUS_CONFIG}
|
||||
formatDuration={v.formatDuration}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step5VoiceSelect
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Step 6 封面设置组件
|
||||
*/
|
||||
import React from "react"
|
||||
import type { CoverConfig } from "../../editing-planner/types"
|
||||
import { useStep6Cover } from "../hooks/useStep6Cover"
|
||||
|
||||
interface Step6CoverSettingsProps {
|
||||
coverSettings: CoverConfig
|
||||
onCoverSettingsChange: (settings: CoverConfig) => void
|
||||
duration: number
|
||||
}
|
||||
|
||||
const Step6CoverSettings: React.FC<Step6CoverSettingsProps> = (props) => {
|
||||
const {
|
||||
coverSettings,
|
||||
formatTime,
|
||||
toggleEnabled,
|
||||
setMode,
|
||||
setFrameTime,
|
||||
handleUpload,
|
||||
totalDuration,
|
||||
COVER_MODE_LABELS,
|
||||
COVER_MODE_ICONS,
|
||||
} = useStep6Cover(props)
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>🖼️ 选择封面</h3>
|
||||
|
||||
{/* 启用开关 */}
|
||||
<div className="xx-cover-header">
|
||||
<span className="xx-cover-header-label">启用自定义封面</span>
|
||||
<label className="xx-switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={coverSettings.enabled}
|
||||
onChange={(e) => toggleEnabled(e.target.checked)}
|
||||
/>
|
||||
<span className="xx-switch-slider" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{coverSettings.enabled && (
|
||||
<>
|
||||
{/* 模式选择 */}
|
||||
<div className="xx-section-title">封面来源</div>
|
||||
<div className="xx-cover-mode-tabs">
|
||||
{(["auto", "frame", "upload"] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
className={`xx-cover-mode-tab${coverSettings.mode === m ? " active" : ""}`}
|
||||
onClick={() => setMode(m)}
|
||||
>
|
||||
<span className="xx-cover-mode-icon">{COVER_MODE_ICONS[m]}</span>
|
||||
<span className="xx-cover-mode-label">{COVER_MODE_LABELS[m]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 智能封面 */}
|
||||
{coverSettings.mode === "auto" && (
|
||||
<div className="xx-cover-auto">
|
||||
<div className="xx-cover-auto-desc">
|
||||
AI 将分析视频内容,自动选择最具吸引力的画面作为封面。
|
||||
</div>
|
||||
<div className="xx-cover-auto-badge">
|
||||
<span style={{ fontSize: 24 }}>🤖</span>
|
||||
<span>AI 智能选帧</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 抽帧选封面 */}
|
||||
{coverSettings.mode === "frame" && (
|
||||
<div className="xx-cover-frame">
|
||||
<div className="xx-cover-frame-preview">
|
||||
<div className="xx-cover-frame-placeholder">
|
||||
<span className="xx-cover-frame-icon">🎞️</span>
|
||||
<span className="xx-cover-frame-time">
|
||||
{formatTime(coverSettings.frame_time)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="xx-cover-frame-slider">
|
||||
<div className="xx-cover-frame-slider-header">
|
||||
<span>拖动选择封面帧</span>
|
||||
<span className="xx-cover-frame-value">
|
||||
{formatTime(coverSettings.frame_time)}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={Math.max(totalDuration, 1)}
|
||||
step={0.1}
|
||||
value={coverSettings.frame_time}
|
||||
onChange={(e) => setFrameTime(Number(e.target.value))}
|
||||
className="xx-cover-range"
|
||||
/>
|
||||
<div className="xx-cover-frame-range">
|
||||
<span>00:00</span>
|
||||
<span>{formatTime(totalDuration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="xx-cover-frame-quick">
|
||||
<span className="xx-cover-quick-label">快捷选帧:</span>
|
||||
{[0, 0.25, 0.5, 0.75].map((ratio) => {
|
||||
const t = totalDuration * ratio
|
||||
return (
|
||||
<button
|
||||
key={ratio}
|
||||
className="xx-cover-quick-btn"
|
||||
onClick={() => setFrameTime(t)}
|
||||
>
|
||||
{formatTime(t)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 上传封面 */}
|
||||
{coverSettings.mode === "upload" && (
|
||||
<div className="xx-cover-upload">
|
||||
<div
|
||||
className="xx-cover-upload-area"
|
||||
onClick={() => {
|
||||
const input = document.getElementById("cover-upload-input")
|
||||
input?.click()
|
||||
}}
|
||||
>
|
||||
{coverSettings.upload_url ? (
|
||||
<div className="xx-cover-upload-preview">
|
||||
<img src={coverSettings.upload_url} alt="封面预览" />
|
||||
<div className="xx-cover-upload-overlay">点击更换</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="xx-cover-upload-placeholder">
|
||||
<span style={{ fontSize: 32 }}>📤</span>
|
||||
<span className="xx-cover-upload-text">点击上传封面图片</span>
|
||||
<span className="xx-cover-upload-hint">支持 JPG / PNG,建议 16:9 比例</span>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
id="cover-upload-input"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
handleUpload(file)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 封面预览 */}
|
||||
<div className="xx-section-title">封面预览</div>
|
||||
<div className="xx-cover-preview-box">
|
||||
{coverSettings.upload_url ? (
|
||||
<img src={coverSettings.upload_url} alt="封面预览" className="xx-cover-preview-img" />
|
||||
) : (
|
||||
<div className="xx-cover-preview-placeholder">
|
||||
<span style={{ fontSize: 28 }}>🖼️</span>
|
||||
<span>
|
||||
{coverSettings.mode === "auto"
|
||||
? "AI 智能选择"
|
||||
: coverSettings.mode === "frame"
|
||||
? `帧 ${formatTime(coverSettings.frame_time)}`
|
||||
: "未上传封面"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="xx-cover-preview-ratio">16:9</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step6CoverSettings
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Step 7 确认生成组件
|
||||
*/
|
||||
import React from "react"
|
||||
import {
|
||||
LoadingOutlined,
|
||||
CheckCircleFilled,
|
||||
CloseCircleOutlined,
|
||||
MinusOutlined,
|
||||
PlusOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
import type { GeneratedVideo } from "@/api/template-editor"
|
||||
import type { CoverConfig } from "../../editing-planner/types"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
import { useStep7Generate } from "../hooks/useStep7Generate"
|
||||
|
||||
interface Step7ConfirmGenerateProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
materialMode: "manual" | "auto"
|
||||
selectedMaterials: string[]
|
||||
smartSelectedIds: string[]
|
||||
title: string
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
selectedVoice: string
|
||||
selectedClonedVoice: string
|
||||
presetVoices: PresetVoiceItem[]
|
||||
clonedVoices: VoiceClone[]
|
||||
coverSettings: CoverConfig
|
||||
generateCount: number
|
||||
onGenerateCountChange: (count: number) => void
|
||||
generating: boolean
|
||||
generated: boolean
|
||||
generateError: string | null
|
||||
progress: number
|
||||
generatedVideos: GeneratedVideo[]
|
||||
onRetry: () => void
|
||||
onDismissError: () => void
|
||||
}
|
||||
|
||||
const Step7ConfirmGenerate: React.FC<Step7ConfirmGenerateProps> = (props) => {
|
||||
const {
|
||||
templateName,
|
||||
materialSummary,
|
||||
title,
|
||||
voiceName,
|
||||
coverSummary,
|
||||
generateCount,
|
||||
handleDecrement,
|
||||
handleIncrement,
|
||||
generating,
|
||||
generated,
|
||||
generateError,
|
||||
progress,
|
||||
generatedVideos,
|
||||
getGenerationPhase,
|
||||
handleScrollToPreview,
|
||||
} = useStep7Generate(props)
|
||||
|
||||
const { onRetry, onDismissError } = props
|
||||
|
||||
return (
|
||||
<div className="xx-form-section">
|
||||
<h3>✨ 确认生成</h3>
|
||||
<div className="xx-summary-card">
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">模板</span>
|
||||
<span className="xx-summary-value">{templateName}</span>
|
||||
</div>
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">素材</span>
|
||||
<span className="xx-summary-value">{materialSummary}</span>
|
||||
</div>
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">标题</span>
|
||||
<span className="xx-summary-value">{title || "未选择"}</span>
|
||||
</div>
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">配音</span>
|
||||
<span className="xx-summary-value">{voiceName}</span>
|
||||
</div>
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">封面</span>
|
||||
<span className="xx-summary-value">{coverSummary}</span>
|
||||
</div>
|
||||
<div className="xx-summary-row">
|
||||
<span className="xx-summary-label">生成数量</span>
|
||||
<span className="xx-summary-value">
|
||||
<div className="xx-count-stepper">
|
||||
<button
|
||||
className="xx-count-stepper-btn"
|
||||
disabled={generateCount <= 1 || generating}
|
||||
onClick={handleDecrement}
|
||||
>
|
||||
<MinusOutlined />
|
||||
</button>
|
||||
<span className="xx-count-stepper-value">{generateCount}</span>
|
||||
<button
|
||||
className="xx-count-stepper-btn"
|
||||
disabled={generateCount >= 10 || generating}
|
||||
onClick={handleIncrement}
|
||||
>
|
||||
<PlusOutlined />
|
||||
</button>
|
||||
<span className="xx-count-stepper-hint">条视频</span>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 生成进度 / 结果反馈 */}
|
||||
{(generating || generated || generateError) && (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
{generating && (
|
||||
<div className="xx-gen-progress-card">
|
||||
<div className="xx-gen-progress-header">
|
||||
<div className="xx-gen-progress-icon">
|
||||
<LoadingOutlined />
|
||||
</div>
|
||||
<div className="xx-gen-progress-info">
|
||||
<div className="xx-gen-progress-phase">
|
||||
{getGenerationPhase(progress).icon} {getGenerationPhase(progress).label}
|
||||
</div>
|
||||
<div className="xx-gen-progress-sub">预计还需 1-2 分钟,请稍候…</div>
|
||||
</div>
|
||||
<div className="xx-gen-progress-percent">{Math.round(progress)}%</div>
|
||||
</div>
|
||||
<div className="xx-gen-progress-bar">
|
||||
<div
|
||||
className="xx-gen-progress-bar-fill"
|
||||
style={{ width: `${Math.min(Math.round(progress), 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="xx-gen-progress-tip">
|
||||
💡 生成过程中可以切换到其他页面操作,完成后会自动通知
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{generated && !generating && (
|
||||
<div className="xx-gen-success-card">
|
||||
<div className="xx-gen-success-icon">
|
||||
<CheckCircleFilled style={{ fontSize: 32, color: "#52c41a" }} />
|
||||
</div>
|
||||
<div className="xx-gen-success-info">
|
||||
<div className="xx-gen-success-title">视频生成完成!</div>
|
||||
<div className="xx-gen-success-sub">
|
||||
共生成 {generatedVideos.length} 条视频,可在右侧预览或前往成片库查看
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-primary xx-btn-sm"
|
||||
onClick={handleScrollToPreview}
|
||||
>
|
||||
查看结果
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{generateError && !generating && (
|
||||
<div className="xx-gen-error-card">
|
||||
<div className="xx-gen-error-icon">
|
||||
<CloseCircleOutlined style={{ fontSize: 28, color: "#ef4444" }} />
|
||||
</div>
|
||||
<div className="xx-gen-error-info">
|
||||
<div className="xx-gen-error-title">生成失败</div>
|
||||
<div className="xx-gen-error-msg">
|
||||
{typeof generateError === "string"
|
||||
? generateError
|
||||
: JSON.stringify(generateError)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
<button type="button" className="xx-btn xx-btn-primary xx-btn-sm" onClick={onRetry}>
|
||||
🔄 重试
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-ghost xx-btn-sm"
|
||||
onClick={onDismissError}
|
||||
>
|
||||
知道了
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Step7ConfirmGenerate
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 手动选择素材列表
|
||||
*/
|
||||
import React from "react"
|
||||
import { Typography } from "antd"
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
interface ManualMaterialListProps {
|
||||
materials: { items: AssetItem[]; total: number }
|
||||
materialsLoading: boolean
|
||||
selectedMaterials: string[]
|
||||
onToggle: (materialId: string) => void
|
||||
}
|
||||
|
||||
const ManualMaterialList: React.FC<ManualMaterialListProps> = ({
|
||||
materials,
|
||||
materialsLoading,
|
||||
selectedMaterials,
|
||||
onToggle,
|
||||
}) => {
|
||||
return (
|
||||
<div style={{ marginTop: 14 }}>
|
||||
{materialsLoading ? (
|
||||
<Text style={{ color: "var(--text-secondary)", padding: "16px 0" }}>加载素材中…</Text>
|
||||
) : materials.items.length === 0 ? (
|
||||
<Text style={{ color: "var(--text-secondary)", padding: "16px 0" }}>
|
||||
暂无素材,请先在视频库中上传
|
||||
</Text>
|
||||
) : (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
{materials.items.map((m) => {
|
||||
const checked = selectedMaterials.includes(m.id)
|
||||
return (
|
||||
<label
|
||||
key={m.id}
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 10,
|
||||
padding: "8px 12px",
|
||||
background: checked ? "var(--primary-soft, #eef2ff)" : "#f8fafc",
|
||||
borderRadius: 10,
|
||||
cursor: "pointer",
|
||||
border: checked
|
||||
? "1px solid var(--primary-color, #4f46e5)"
|
||||
: "1px solid transparent",
|
||||
transition: "all 0.15s ease",
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => onToggle(m.id)}
|
||||
style={{ accentColor: "var(--primary-color, #4f46e5)" }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
fontSize: 13,
|
||||
color: "var(--text-primary)",
|
||||
flex: 1,
|
||||
}}
|
||||
>
|
||||
{m.name}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: 11,
|
||||
color: "var(--text-tertiary, #94a3b8)",
|
||||
}}
|
||||
>
|
||||
{m.mime_type.split("/")[1].toUpperCase()}
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ManualMaterialList
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* 素材模式切换 Tab
|
||||
*/
|
||||
import React from "react"
|
||||
|
||||
interface MaterialModeTabsProps {
|
||||
mode: "manual" | "auto"
|
||||
onModeChange: (mode: "manual" | "auto") => void
|
||||
}
|
||||
|
||||
const MaterialModeTabs: React.FC<MaterialModeTabsProps> = ({ mode, onModeChange }) => {
|
||||
return (
|
||||
<div className="xx-material-mode-tabs">
|
||||
<button
|
||||
className={`xx-material-mode-tab ${mode === "manual" ? "active" : ""}`}
|
||||
onClick={() => onModeChange("manual")}
|
||||
type="button"
|
||||
>
|
||||
手动选择素材
|
||||
</button>
|
||||
<button
|
||||
className={`xx-material-mode-tab ${mode === "auto" ? "active" : ""}`}
|
||||
onClick={() => onModeChange("auto")}
|
||||
type="button"
|
||||
>
|
||||
选择视频库自动匹配
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MaterialModeTabs
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 单个智能匹配卡片
|
||||
*/
|
||||
import React from "react"
|
||||
import { PlayCircleOutlined, CheckCircleFilled } from "@ant-design/icons"
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
|
||||
interface SmartMatchResultItem {
|
||||
asset: AssetItem
|
||||
matchScore: number
|
||||
matchReason: string
|
||||
}
|
||||
|
||||
interface SmartMatchCardProps {
|
||||
result: SmartMatchResultItem
|
||||
selected: boolean
|
||||
onClick: () => void
|
||||
formatDuration: (seconds: number) => string
|
||||
}
|
||||
|
||||
const SmartMatchCard: React.FC<SmartMatchCardProps> = ({
|
||||
result,
|
||||
selected,
|
||||
onClick,
|
||||
formatDuration,
|
||||
}) => {
|
||||
const { asset, matchScore, matchReason } = result
|
||||
return (
|
||||
<div className={`xx-smart-match-card ${selected ? "selected" : ""}`} onClick={onClick}>
|
||||
{/* 缩略图 */}
|
||||
<div className="xx-smart-match-thumb">
|
||||
{asset.thumbnail_url ? (
|
||||
<img src={asset.thumbnail_url} alt={asset.name} />
|
||||
) : (
|
||||
<div className="xx-smart-match-thumb-placeholder">
|
||||
<PlayCircleOutlined style={{ fontSize: 32, opacity: 0.5 }} />
|
||||
</div>
|
||||
)}
|
||||
<div className="xx-smart-match-score">{matchScore}%</div>
|
||||
{selected && (
|
||||
<div className="xx-smart-match-check">
|
||||
<CheckCircleFilled style={{ fontSize: 20, color: "#fff" }} />
|
||||
</div>
|
||||
)}
|
||||
{asset.duration && (
|
||||
<div className="xx-smart-match-duration">{formatDuration(asset.duration)}</div>
|
||||
)}
|
||||
</div>
|
||||
{/* 信息区 */}
|
||||
<div className="xx-smart-match-info">
|
||||
<div className="xx-smart-match-name" title={asset.name}>
|
||||
{asset.name}
|
||||
</div>
|
||||
<div className="xx-smart-match-reason">🎯 {matchReason}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SmartMatchCard
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* 智能匹配输入区
|
||||
* textarea + 提示 + 按钮组
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined } from "@ant-design/icons"
|
||||
|
||||
interface SmartMatchInputProps {
|
||||
inputValue: string
|
||||
onInputChange: (value: string) => void
|
||||
matching: boolean
|
||||
onMatch: () => void
|
||||
hasMatched: boolean
|
||||
onRefresh: () => void
|
||||
materialsCount: number
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
const SmartMatchInput: React.FC<SmartMatchInputProps> = ({
|
||||
inputValue,
|
||||
onInputChange,
|
||||
matching,
|
||||
onMatch,
|
||||
hasMatched,
|
||||
onRefresh,
|
||||
materialsCount,
|
||||
loading,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-smart-match-input-area">
|
||||
<label className="xx-smart-match-label">🤖 描述你想要的视频内容</label>
|
||||
<textarea
|
||||
className="xx-smart-match-input"
|
||||
placeholder="例如:一个科技感十足的产品宣传视频,画面要有现代办公场景、团队协作、数据分析图表…"
|
||||
value={inputValue}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
rows={3}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
||||
onMatch()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="xx-smart-match-input-footer">
|
||||
<span className="xx-smart-match-tip">
|
||||
{loading ? "扫描视频库中…" : `当前视频库共 ${materialsCount} 个素材可供匹配`}
|
||||
</span>
|
||||
<div style={{ display: "flex", gap: 8 }}>
|
||||
{hasMatched && (
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-ghost xx-btn-sm"
|
||||
onClick={onRefresh}
|
||||
disabled={matching || loading}
|
||||
>
|
||||
🔄 换一批
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-primary xx-btn-sm"
|
||||
onClick={onMatch}
|
||||
disabled={matching || loading || !inputValue.trim()}
|
||||
>
|
||||
{matching ? (
|
||||
<>
|
||||
<LoadingOutlined style={{ marginRight: 6 }} />
|
||||
匹配中…
|
||||
</>
|
||||
) : (
|
||||
"✨ 智能匹配"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SmartMatchInput
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 智能匹配结果区(含加载/空状态/已选汇总)
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined } from "@ant-design/icons"
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
import SmartMatchCard from "./SmartMatchCard"
|
||||
|
||||
interface SmartMatchResultItem {
|
||||
asset: AssetItem
|
||||
matchScore: number
|
||||
matchReason: string
|
||||
}
|
||||
|
||||
interface SmartMatchResultsProps {
|
||||
results: SmartMatchResultItem[]
|
||||
selectedIds: string[]
|
||||
matching: boolean
|
||||
hasMatched: boolean
|
||||
onToggle: (assetId: string) => void
|
||||
onSelectAll: () => void
|
||||
onClear: () => void
|
||||
formatDuration: (seconds: number) => string
|
||||
selectedTotalDuration: number
|
||||
}
|
||||
|
||||
const SmartMatchResults: React.FC<SmartMatchResultsProps> = ({
|
||||
results,
|
||||
selectedIds,
|
||||
matching,
|
||||
hasMatched,
|
||||
onToggle,
|
||||
onSelectAll,
|
||||
onClear,
|
||||
formatDuration,
|
||||
selectedTotalDuration,
|
||||
}) => {
|
||||
// 匹配中状态
|
||||
if (matching) {
|
||||
return (
|
||||
<div className="xx-smart-match-loading">
|
||||
<LoadingOutlined
|
||||
style={{ fontSize: 32, color: "var(--primary-color)", marginBottom: 12 }}
|
||||
/>
|
||||
<div style={{ color: "var(--text-primary)", fontSize: 14 }}>AI 正在分析素材…</div>
|
||||
<div style={{ color: "var(--text-tertiary)", fontSize: 12, marginTop: 4 }}>
|
||||
正在根据描述从视频库中匹配最合适的素材
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 未匹配状态提示
|
||||
if (!hasMatched) {
|
||||
return (
|
||||
<div className="xx-smart-match-empty">
|
||||
<div style={{ fontSize: 36, marginBottom: 8 }}>💡</div>
|
||||
<div style={{ color: "var(--text-secondary)", fontSize: 13 }}>
|
||||
输入视频内容描述,点击「智能匹配」让 AI 帮你选素材
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 无结果
|
||||
if (results.length === 0) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="xx-smart-match-results">
|
||||
<div className="xx-smart-match-results-header">
|
||||
<span className="xx-smart-match-results-title">推荐素材 ({results.length}个)</span>
|
||||
<div className="xx-smart-match-results-actions">
|
||||
<button type="button" className="xx-link-btn" onClick={onSelectAll}>
|
||||
全选
|
||||
</button>
|
||||
<span style={{ color: "var(--border-color)" }}>|</span>
|
||||
<button type="button" className="xx-link-btn" onClick={onClear}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="xx-smart-match-grid">
|
||||
{results.map((result) => {
|
||||
const isSelected = selectedIds.includes(result.asset.id)
|
||||
return (
|
||||
<SmartMatchCard
|
||||
key={result.asset.id}
|
||||
result={result}
|
||||
selected={isSelected}
|
||||
onClick={() => onToggle(result.asset.id)}
|
||||
formatDuration={formatDuration}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 已选素材汇总 */}
|
||||
{selectedIds.length > 0 && (
|
||||
<div className="xx-smart-match-summary">
|
||||
<div className="xx-smart-match-summary-header">
|
||||
<span className="xx-pill xx-pill-ok">已选 {selectedIds.length} 个素材</span>
|
||||
<span style={{ color: "var(--text-tertiary)", fontSize: 12 }}>
|
||||
预计总时长约 {selectedTotalDuration.toFixed(0)} 秒
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default SmartMatchResults
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 单个 AI 标题卡片
|
||||
*/
|
||||
import React from "react"
|
||||
import { CheckCircleFilled } from "@ant-design/icons"
|
||||
|
||||
interface AiTitleCardProps {
|
||||
title: string
|
||||
highlight: string
|
||||
style: "catchy" | "emotional" | "informative"
|
||||
selected: boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const AiTitleCard: React.FC<AiTitleCardProps> = ({
|
||||
title,
|
||||
highlight,
|
||||
style,
|
||||
selected,
|
||||
onClick,
|
||||
}) => {
|
||||
return (
|
||||
<div className={`xx-ai-title-card ${selected ? "selected" : ""} ${style}`} onClick={onClick}>
|
||||
<div className="xx-ai-title-card-text">{title}</div>
|
||||
<div className="xx-ai-title-card-tag">{highlight}</div>
|
||||
{selected && (
|
||||
<div className="xx-ai-title-card-check">
|
||||
<CheckCircleFilled style={{ color: "#fff", fontSize: 14 }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AiTitleCard
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* AI 智能生成标题
|
||||
* 输入框 + 生成按钮 + 结果列表 + 加载状态
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined } from "@ant-design/icons"
|
||||
import AiTitleCard from "./AiTitleCard"
|
||||
|
||||
interface AiTitleItem {
|
||||
title: string
|
||||
highlight: string
|
||||
style: "catchy" | "emotional" | "informative"
|
||||
}
|
||||
|
||||
interface AiTitleGeneratorProps {
|
||||
inputValue: string
|
||||
onInputChange: (value: string) => void
|
||||
generating: boolean
|
||||
onGenerate: () => void
|
||||
results: AiTitleItem[]
|
||||
hasGenerated: boolean
|
||||
onSelect: (title: string) => void
|
||||
selectedTitle: string
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
const AiTitleGenerator: React.FC<AiTitleGeneratorProps> = ({
|
||||
inputValue,
|
||||
onInputChange,
|
||||
generating,
|
||||
onGenerate,
|
||||
results,
|
||||
hasGenerated,
|
||||
onSelect,
|
||||
selectedTitle,
|
||||
onRefresh,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-ai-title-section">
|
||||
<div className="xx-ai-title-header">
|
||||
<span className="xx-ai-title-label">✨ AI 智能生成标题</span>
|
||||
</div>
|
||||
<div className="xx-ai-title-input-row">
|
||||
<input
|
||||
className="xx-ai-title-input"
|
||||
placeholder="输入视频内容描述或关键词,如:职场成长、副业赚钱…"
|
||||
value={inputValue}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onGenerate()
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-primary"
|
||||
onClick={onGenerate}
|
||||
disabled={generating || !inputValue.trim()}
|
||||
>
|
||||
{generating ? (
|
||||
<>
|
||||
<LoadingOutlined style={{ marginRight: 6 }} />
|
||||
生成中
|
||||
</>
|
||||
) : (
|
||||
"生成标题"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 生成结果 */}
|
||||
{hasGenerated && !generating && results.length > 0 && (
|
||||
<div className="xx-ai-title-results">
|
||||
<div className="xx-ai-title-results-header">
|
||||
<span className="xx-ai-title-results-count">为你生成 {results.length} 个标题</span>
|
||||
<button type="button" className="xx-link-btn" onClick={onRefresh} disabled={generating}>
|
||||
🔄 换一批
|
||||
</button>
|
||||
</div>
|
||||
<div className="xx-ai-title-list">
|
||||
{results.map((item, idx) => (
|
||||
<AiTitleCard
|
||||
key={idx}
|
||||
title={item.title}
|
||||
highlight={item.highlight}
|
||||
style={item.style}
|
||||
selected={selectedTitle === item.title}
|
||||
onClick={() => onSelect(item.title)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 生成中 */}
|
||||
{generating && (
|
||||
<div className="xx-ai-title-loading">
|
||||
<LoadingOutlined style={{ color: "var(--primary-color)", marginRight: 8 }} />
|
||||
AI 正在为你创作标题…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AiTitleGenerator
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 标题预设样式网格
|
||||
*/
|
||||
import React from "react"
|
||||
|
||||
interface TitlePresetItem {
|
||||
key: string
|
||||
label: string
|
||||
previewStyle: React.CSSProperties
|
||||
}
|
||||
|
||||
interface TitlePresetsGridProps {
|
||||
presets: TitlePresetItem[]
|
||||
activePreset: string | null
|
||||
onApply: (presetKey: string) => void
|
||||
}
|
||||
|
||||
const TitlePresetsGrid: React.FC<TitlePresetsGridProps> = ({ presets, activePreset, onApply }) => {
|
||||
return (
|
||||
<div className="xx-title-presets-grid">
|
||||
{presets.map((p) => {
|
||||
const isActive = activePreset === p.key
|
||||
return (
|
||||
<button
|
||||
key={p.key}
|
||||
className={`xx-title-preset-card${isActive ? " active" : ""}`}
|
||||
onClick={() => onApply(p.key)}
|
||||
title={p.label}
|
||||
>
|
||||
<span className="xx-title-preset-preview-text" style={p.previewStyle}>
|
||||
标题
|
||||
</span>
|
||||
<span className="xx-title-preset-card-label">{p.label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TitlePresetsGrid
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 标题样式设置区
|
||||
* 位置/字体/字号/样式按钮/预设
|
||||
*/
|
||||
import React from "react"
|
||||
import type { TitleSettings } from "../../types"
|
||||
import TitlePresetsGrid from "./TitlePresetsGrid"
|
||||
|
||||
interface PositionOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
interface TitlePresetItem {
|
||||
key: string
|
||||
label: string
|
||||
previewStyle: React.CSSProperties
|
||||
}
|
||||
|
||||
interface TitleStylePanelProps {
|
||||
settings: TitleSettings
|
||||
onUpdatePosition: (position: string) => void
|
||||
onUpdateFont: (font: string) => void
|
||||
onUpdateSize: (size: number) => void
|
||||
onToggleBold: () => void
|
||||
onToggleItalic: () => void
|
||||
onToggleStroke: () => void
|
||||
onToggleShadow: () => void
|
||||
onApplyPreset: (presetKey: string) => void
|
||||
activePreset: string | null
|
||||
titlePresets: TitlePresetItem[]
|
||||
POSITION_OPTIONS: PositionOption[]
|
||||
FONT_OPTIONS: string[]
|
||||
}
|
||||
|
||||
const TitleStylePanel: React.FC<TitleStylePanelProps> = ({
|
||||
settings,
|
||||
onUpdatePosition,
|
||||
onUpdateFont,
|
||||
onUpdateSize,
|
||||
onToggleBold,
|
||||
onToggleItalic,
|
||||
onToggleStroke,
|
||||
onToggleShadow,
|
||||
onApplyPreset,
|
||||
activePreset,
|
||||
titlePresets,
|
||||
POSITION_OPTIONS,
|
||||
FONT_OPTIONS,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-title-style-section">
|
||||
<h4 className="xx-section-subtitle">标题样式</h4>
|
||||
|
||||
{/* 位置 + 字体 一行 */}
|
||||
<div className="xx-title-style-row">
|
||||
<div className="xx-form-field xx-half-field">
|
||||
<label>位置</label>
|
||||
<select
|
||||
className="xx-form-select"
|
||||
value={settings.position}
|
||||
onChange={(e) => onUpdatePosition(e.target.value)}
|
||||
>
|
||||
{POSITION_OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="xx-form-field xx-half-field">
|
||||
<label>字体</label>
|
||||
<select
|
||||
className="xx-form-select"
|
||||
value={settings.font}
|
||||
onChange={(e) => onUpdateFont(e.target.value)}
|
||||
>
|
||||
{FONT_OPTIONS.map((f) => (
|
||||
<option key={f} value={f}>
|
||||
{f}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 字号滑块 */}
|
||||
<div className="xx-form-field">
|
||||
<div className="xx-field-label-row">
|
||||
<label>字号</label>
|
||||
<span className="xx-field-value">{settings.size}px</span>
|
||||
</div>
|
||||
<input
|
||||
className="xx-slider"
|
||||
type="range"
|
||||
min={12}
|
||||
max={48}
|
||||
value={settings.size}
|
||||
onChange={(e) => onUpdateSize(Number(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 预设样式 */}
|
||||
<div className="xx-form-field">
|
||||
<label>预设样式</label>
|
||||
<TitlePresetsGrid
|
||||
presets={titlePresets}
|
||||
activePreset={activePreset}
|
||||
onApply={onApplyPreset}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 样式按钮:粗体/斜体/描边/阴影 */}
|
||||
<div className="xx-form-field">
|
||||
<label>样式</label>
|
||||
<div className="xx-style-btns">
|
||||
<button
|
||||
className={`xx-style-btn ${settings.bold ? "active" : ""}`}
|
||||
onClick={onToggleBold}
|
||||
title="粗体"
|
||||
>
|
||||
<b>B</b>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-style-btn ${settings.italic ? "active" : ""}`}
|
||||
onClick={onToggleItalic}
|
||||
title="斜体"
|
||||
>
|
||||
<i>I</i>
|
||||
</button>
|
||||
<button
|
||||
className={`xx-style-btn ${settings.stroke ? "active" : ""}`}
|
||||
onClick={onToggleStroke}
|
||||
title="描边"
|
||||
>
|
||||
S
|
||||
</button>
|
||||
<button
|
||||
className={`xx-style-btn ${settings.shadow ? "active" : ""}`}
|
||||
onClick={onToggleShadow}
|
||||
title="阴影"
|
||||
>
|
||||
☁
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TitleStylePanel
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* 克隆声音展开区域
|
||||
* 克隆按钮、轮询提示、已克隆列表、空状态
|
||||
*/
|
||||
import React from "react"
|
||||
import { Typography } from "antd"
|
||||
import { ThunderboltOutlined, AudioOutlined, CheckCircleFilled } from "@ant-design/icons"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
interface CloneVoiceSectionProps {
|
||||
clonedVoices: VoiceClone[]
|
||||
hasProcessing: boolean
|
||||
selectedClonedVoice: string
|
||||
onSelect: (voiceId: string) => void
|
||||
onOpenCloneModal: () => void
|
||||
CLONE_STATUS_CONFIG: Record<string, { label: string; color: string }>
|
||||
formatDuration: (seconds: number) => string
|
||||
}
|
||||
|
||||
const CloneVoiceSection: React.FC<CloneVoiceSectionProps> = ({
|
||||
clonedVoices,
|
||||
hasProcessing,
|
||||
selectedClonedVoice,
|
||||
onSelect,
|
||||
onOpenCloneModal,
|
||||
CLONE_STATUS_CONFIG,
|
||||
formatDuration,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-clone-section">
|
||||
<p className="xx-clone-section-title">克隆我的声音</p>
|
||||
<Text style={{ fontSize: 12, color: "var(--text-tertiary, #94a3b8)" }}>
|
||||
上传一段您的语音样本,AI 将克隆您的声音用于视频配音
|
||||
</Text>
|
||||
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<button
|
||||
className="xx-btn xx-btn-primary"
|
||||
style={{ height: 36, fontSize: 13 }}
|
||||
onClick={onOpenCloneModal}
|
||||
>
|
||||
<ThunderboltOutlined /> 克隆新声音
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 轮询提示 */}
|
||||
{hasProcessing && (
|
||||
<div className="xx-clone-polling-hint" style={{ marginTop: 10 }}>
|
||||
<span className="xx-clone-polling-dot" />
|
||||
正在同步克隆进度...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 已克隆声音列表 */}
|
||||
{clonedVoices.length > 0 && (
|
||||
<div className="xx-clone-voices-list">
|
||||
{clonedVoices.map((cv) => {
|
||||
const statusCfg = CLONE_STATUS_CONFIG[cv.status]
|
||||
const isReady = cv.status === "ready"
|
||||
const selected = selectedClonedVoice === cv.id
|
||||
return (
|
||||
<div
|
||||
key={cv.id}
|
||||
className={`xx-clone-voice-row ${selected ? "selected" : ""} ${
|
||||
!isReady ? "disabled" : ""
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (isReady) onSelect(cv.id)
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={isReady ? 0 : -1}
|
||||
aria-pressed={selected}
|
||||
>
|
||||
<div className={`xx-clone-avatar ${cv.status}`}>
|
||||
<AudioOutlined />
|
||||
</div>
|
||||
<div className="xx-clone-info">
|
||||
<div className="xx-clone-name">{cv.name}</div>
|
||||
<div className="xx-clone-status">
|
||||
<span className="xx-clone-status-dot" style={{ background: statusCfg.color }} />
|
||||
<span style={{ color: statusCfg.color }}>{statusCfg.label}</span>
|
||||
{isReady && (
|
||||
<span
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
marginLeft: 8,
|
||||
}}
|
||||
>
|
||||
{formatDuration(cv.duration_seconds)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{selected && isReady && (
|
||||
<CheckCircleFilled style={{ color: "var(--primary-color, #4f46e5)" }} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{clonedVoices.length === 0 && (
|
||||
<Text
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
display: "block",
|
||||
textAlign: "center",
|
||||
padding: "16px 0",
|
||||
}}
|
||||
>
|
||||
暂无克隆音色,点击「克隆新声音」开始
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Text
|
||||
style={{
|
||||
fontSize: 12,
|
||||
color: "var(--text-tertiary, #94a3b8)",
|
||||
marginTop: 10,
|
||||
display: "block",
|
||||
}}
|
||||
>
|
||||
💡 提示:录音环境越安静,克隆效果越好。
|
||||
</Text>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CloneVoiceSection
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 自定义录制面板
|
||||
* textarea + 合成按钮 + 结果区 + 存为素材按钮
|
||||
*/
|
||||
import React from "react"
|
||||
import { Typography } from "antd"
|
||||
import { AudioOutlined, SaveOutlined } from "@ant-design/icons"
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
interface CustomVoicePanelProps {
|
||||
customVoiceText: string
|
||||
onTextChange: (text: string) => void
|
||||
synthesizePending: boolean
|
||||
onSynthesize: () => void
|
||||
ttsError: string | null
|
||||
customAudioUrl: string | null
|
||||
completedTtsJobId: string | null
|
||||
onOpenSaveModal: () => void
|
||||
}
|
||||
|
||||
const CustomVoicePanel: React.FC<CustomVoicePanelProps> = ({
|
||||
customVoiceText,
|
||||
onTextChange,
|
||||
synthesizePending,
|
||||
onSynthesize,
|
||||
ttsError,
|
||||
customAudioUrl,
|
||||
completedTtsJobId,
|
||||
onOpenSaveModal,
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
placeholder="输入配音文案,点击合成按钮生成语音…"
|
||||
value={customVoiceText}
|
||||
onChange={(e) => onTextChange(e.target.value)}
|
||||
maxLength={500}
|
||||
style={{
|
||||
width: "100%",
|
||||
minHeight: 100,
|
||||
border: "1px solid var(--border-color, #e2e8f0)",
|
||||
borderRadius: "var(--radius-sm, 10px)",
|
||||
padding: 12,
|
||||
fontSize: 14,
|
||||
resize: "vertical",
|
||||
outline: "none",
|
||||
}}
|
||||
/>
|
||||
<div style={{ marginTop: 12, display: "flex", gap: 8 }}>
|
||||
<button
|
||||
className="xx-btn xx-btn-ghost"
|
||||
disabled={!customVoiceText.trim() || synthesizePending}
|
||||
onClick={onSynthesize}
|
||||
>
|
||||
<AudioOutlined /> {synthesizePending ? "合成中…" : "合成语音"}
|
||||
</button>
|
||||
</div>
|
||||
{ttsError && (
|
||||
<Text
|
||||
style={{
|
||||
color: "var(--error, #ef4444)",
|
||||
marginTop: 8,
|
||||
display: "block",
|
||||
}}
|
||||
>
|
||||
{ttsError}
|
||||
</Text>
|
||||
)}
|
||||
{customAudioUrl && completedTtsJobId && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 8,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 12,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: "var(--success, #10b981)" }}>✓ 语音合成完成</Text>
|
||||
<button
|
||||
className="xx-btn xx-btn-primary"
|
||||
style={{ height: 30, padding: "0 14px", fontSize: 12 }}
|
||||
onClick={onOpenSaveModal}
|
||||
>
|
||||
<SaveOutlined /> 存为素材
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CustomVoicePanel
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 预设音色下拉选择 + 试听按钮
|
||||
* voiceMode === "preset" 时显示的详情区
|
||||
*/
|
||||
import React from "react"
|
||||
import { PlayCircleOutlined, PauseCircleOutlined } from "@ant-design/icons"
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
|
||||
interface PresetVoiceDetailProps {
|
||||
presetVoices: PresetVoiceItem[]
|
||||
selectedVoice: string
|
||||
onSelect: (voiceId: string) => void
|
||||
playingVoice: string | null
|
||||
onTogglePlay: (voiceId: string, previewUrl: string | null) => void
|
||||
presetVoicesLoading: boolean
|
||||
}
|
||||
|
||||
const PresetVoiceDetail: React.FC<PresetVoiceDetailProps> = ({
|
||||
presetVoices,
|
||||
selectedVoice,
|
||||
onSelect,
|
||||
playingVoice,
|
||||
onTogglePlay,
|
||||
presetVoicesLoading,
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
<div className="xx-form-field">
|
||||
<label>从配音库选择</label>
|
||||
<select value={selectedVoice} onChange={(e) => onSelect(e.target.value)}>
|
||||
<option value="">请选择配音…</option>
|
||||
{presetVoicesLoading ? (
|
||||
<option disabled>加载中…</option>
|
||||
) : (
|
||||
presetVoices.map((v) => (
|
||||
<option key={v.voice_id} value={v.voice_id}>
|
||||
{v.name} — {v.description}
|
||||
</option>
|
||||
))
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
{/* 试听按钮 */}
|
||||
{presetVoices.length > 0 && (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: 8,
|
||||
flexWrap: "wrap",
|
||||
marginTop: 8,
|
||||
}}
|
||||
>
|
||||
{presetVoices.slice(0, 4).map((v) => (
|
||||
<button
|
||||
key={v.voice_id}
|
||||
className="xx-btn xx-btn-ghost"
|
||||
style={{ height: 32, padding: "0 12px", fontSize: 12 }}
|
||||
onClick={() => onTogglePlay(v.voice_id, v.preview_url)}
|
||||
>
|
||||
{playingVoice === v.voice_id ? (
|
||||
<>
|
||||
<PauseCircleOutlined /> 停止
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlayCircleOutlined /> {v.name}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PresetVoiceDetail
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 保存到配音库弹窗
|
||||
*/
|
||||
import React from "react"
|
||||
import { CloseOutlined, PlusOutlined } from "@ant-design/icons"
|
||||
import type { TagItem } from "@/api/tags"
|
||||
|
||||
interface SaveVoiceModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
saveName: string
|
||||
onNameChange: (name: string) => void
|
||||
saveTagIds: string[]
|
||||
onTagIdsChange: (tags: string[] | ((prev: string[]) => string[])) => void
|
||||
saveNewTag: string
|
||||
onNewTagChange: (tag: string) => void
|
||||
onAddTag: (tagName: string) => void
|
||||
allTags: TagItem[]
|
||||
savePending: boolean
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
const SaveVoiceModal: React.FC<SaveVoiceModalProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
saveName,
|
||||
onNameChange,
|
||||
saveTagIds,
|
||||
onTagIdsChange,
|
||||
saveNewTag,
|
||||
onNewTagChange,
|
||||
onAddTag,
|
||||
allTags,
|
||||
savePending,
|
||||
onConfirm,
|
||||
}) => {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="xx-save-modal-overlay" onClick={onClose}>
|
||||
<div className="xx-save-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="xx-save-modal-header">
|
||||
<span>保存到配音库</span>
|
||||
<button className="xx-save-modal-close" onClick={onClose}>
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</div>
|
||||
<div className="xx-save-modal-body">
|
||||
<label className="xx-save-modal-label">素材名称</label>
|
||||
<input
|
||||
className="xx-save-modal-input"
|
||||
placeholder="留空则自动生成名称"
|
||||
value={saveName}
|
||||
onChange={(e) => onNameChange(e.target.value)}
|
||||
maxLength={50}
|
||||
/>
|
||||
<label className="xx-save-modal-label">
|
||||
标签
|
||||
<span
|
||||
style={{
|
||||
fontWeight: 400,
|
||||
color: "var(--text-tertiary, #94a3b8)",
|
||||
}}
|
||||
>
|
||||
(可选)
|
||||
</span>
|
||||
</label>
|
||||
<div className="xx-save-modal-tags">
|
||||
{saveTagIds.map((id) => {
|
||||
const tag = allTags.find((t) => t.id === id)
|
||||
return tag ? (
|
||||
<span key={id} className="xx-save-modal-tag active">
|
||||
{tag.name}
|
||||
<CloseOutlined
|
||||
className="xx-save-modal-tag-remove"
|
||||
onClick={() => onTagIdsChange((prev: string[]) => prev.filter((x) => x !== id))}
|
||||
/>
|
||||
</span>
|
||||
) : null
|
||||
})}
|
||||
<input
|
||||
className="xx-save-modal-tag-input"
|
||||
placeholder="输入标签名回车添加"
|
||||
value={saveNewTag}
|
||||
onChange={(e) => onNewTagChange(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
onAddTag(saveNewTag)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{allTags.length > 0 && (
|
||||
<div className="xx-save-modal-tag-presets">
|
||||
{allTags
|
||||
.filter((t) => !saveTagIds.includes(t.id))
|
||||
.slice(0, 12)
|
||||
.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
className="xx-save-modal-tag-preset"
|
||||
onClick={() => onTagIdsChange((prev: string[]) => [...prev, t.id])}
|
||||
>
|
||||
{t.name}
|
||||
<PlusOutlined style={{ fontSize: 10, marginLeft: 4 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="xx-save-modal-footer">
|
||||
<button className="xx-btn xx-btn-ghost" onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
<button className="xx-btn xx-btn-primary" disabled={savePending} onClick={onConfirm}>
|
||||
{savePending ? "保存中…" : "保存"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SaveVoiceModal
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 音色选择卡片
|
||||
* 用于顶部预设音色卡片和克隆入口卡片
|
||||
*/
|
||||
import React from "react"
|
||||
|
||||
interface VoiceChoiceCardProps {
|
||||
selected: boolean
|
||||
onClick: () => void
|
||||
avatar: React.ReactNode
|
||||
title: string
|
||||
description?: string
|
||||
avatarStyle?: React.CSSProperties
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
const VoiceChoiceCard: React.FC<VoiceChoiceCardProps> = ({
|
||||
selected,
|
||||
onClick,
|
||||
avatar,
|
||||
title,
|
||||
description,
|
||||
avatarStyle,
|
||||
loading = false,
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={`xx-voice-choice-item ${selected ? "selected" : ""}`}
|
||||
onClick={onClick}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-pressed={selected}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault()
|
||||
onClick()
|
||||
}
|
||||
}}
|
||||
style={loading ? { opacity: 0.5 } : undefined}
|
||||
>
|
||||
<span className="xx-voice-choice-check">✓</span>
|
||||
<div className="xx-voice-choice-avatar" style={avatarStyle}>
|
||||
{avatar}
|
||||
</div>
|
||||
<div className="xx-voice-choice-info">
|
||||
<h4>{title}</h4>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceChoiceCard
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* AI 智能推荐配音区域
|
||||
*/
|
||||
import React from "react"
|
||||
import { LoadingOutlined, CheckCircleFilled } from "@ant-design/icons"
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
|
||||
interface VoiceRecommendSectionProps {
|
||||
presetVoices: PresetVoiceItem[]
|
||||
voiceRecommendLoading: boolean
|
||||
voiceRecommendations: string[]
|
||||
hasVoiceRecommend: boolean
|
||||
onRecommend: () => void
|
||||
onSelectVoice: (voiceId: string) => void
|
||||
selectedVoiceId: string
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
VOICE_GENDER_ICON: Record<string, string>
|
||||
}
|
||||
|
||||
const VoiceRecommendSection: React.FC<VoiceRecommendSectionProps> = ({
|
||||
presetVoices,
|
||||
voiceRecommendLoading,
|
||||
voiceRecommendations,
|
||||
hasVoiceRecommend,
|
||||
onRecommend,
|
||||
onSelectVoice,
|
||||
selectedVoiceId,
|
||||
voiceMode,
|
||||
VOICE_GENDER_ICON,
|
||||
}) => {
|
||||
return (
|
||||
<div className="xx-voice-recommend-section">
|
||||
<div className="xx-voice-recommend-header">
|
||||
<span className="xx-voice-recommend-label">✨ AI 智能推荐</span>
|
||||
<button
|
||||
type="button"
|
||||
className="xx-btn xx-btn-primary xx-btn-sm"
|
||||
onClick={onRecommend}
|
||||
disabled={voiceRecommendLoading}
|
||||
>
|
||||
{voiceRecommendLoading ? (
|
||||
<>
|
||||
<LoadingOutlined style={{ marginRight: 6 }} />
|
||||
推荐中
|
||||
</>
|
||||
) : hasVoiceRecommend ? (
|
||||
"换一批"
|
||||
) : (
|
||||
"智能推荐"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{voiceRecommendLoading && (
|
||||
<div className="xx-voice-recommend-loading">
|
||||
<LoadingOutlined style={{ color: "var(--primary-color)", marginRight: 8 }} />
|
||||
根据视频内容为你匹配最合适的音色…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!voiceRecommendLoading && hasVoiceRecommend && voiceRecommendations.length > 0 && (
|
||||
<div className="xx-voice-recommend-list">
|
||||
{voiceRecommendations.map((voiceId) => {
|
||||
const v = presetVoices.find((pv) => pv.voice_id === voiceId)
|
||||
if (!v) return null
|
||||
const isSelected = voiceMode === "preset" && selectedVoiceId === v.voice_id
|
||||
return (
|
||||
<div
|
||||
key={v.voice_id}
|
||||
className={`xx-voice-recommend-card ${isSelected ? "selected" : ""}`}
|
||||
onClick={() => onSelectVoice(v.voice_id)}
|
||||
>
|
||||
<div className="xx-voice-recommend-avatar">
|
||||
{VOICE_GENDER_ICON[v.gender] ?? "✨"}
|
||||
</div>
|
||||
<div className="xx-voice-recommend-info">
|
||||
<div className="xx-voice-recommend-name">{v.name}</div>
|
||||
<div className="xx-voice-recommend-desc">{v.description}</div>
|
||||
</div>
|
||||
{isSelected && (
|
||||
<div className="xx-voice-recommend-check">
|
||||
<CheckCircleFilled style={{ color: "#fff", fontSize: 16 }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!voiceRecommendLoading && !hasVoiceRecommend && (
|
||||
<div className="xx-voice-recommend-empty">
|
||||
<span>点击「智能推荐」,AI 根据视频内容匹配音色</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceRecommendSection
|
||||
@@ -0,0 +1,370 @@
|
||||
/**
|
||||
* 视频生成 Hook
|
||||
* 封装视频生成的核心逻辑、状态管理、轮询等
|
||||
*/
|
||||
import { useState, useRef, useCallback } from "react"
|
||||
import { message } from "antd"
|
||||
import type { GeneratedVideo, EditPlanConfig } from "@/api/template-editor"
|
||||
import {
|
||||
generateEditPlan,
|
||||
updateEditPlan,
|
||||
getGenerationTaskResults,
|
||||
getGenerationStatus,
|
||||
getEditPlan,
|
||||
} from "@/api/template-editor"
|
||||
import type { CoverConfig } from "../../editing-planner/types"
|
||||
import type { TitleSettings } from "../types"
|
||||
|
||||
interface UseGenerateVideoProps {
|
||||
titleSettings: TitleSettings
|
||||
selectedTemplate: string
|
||||
selectedMaterials: string[]
|
||||
materialMode: "manual" | "auto"
|
||||
smartSelectedIds: string[]
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
selectedVoice: string
|
||||
selectedClonedVoice: string
|
||||
coverSettings: CoverConfig
|
||||
videoRatio: string
|
||||
style: string
|
||||
duration: number
|
||||
autoSubtitles: boolean
|
||||
bgm: boolean
|
||||
generateCount: number
|
||||
}
|
||||
|
||||
export function useGenerateVideo({
|
||||
titleSettings,
|
||||
selectedTemplate,
|
||||
selectedMaterials,
|
||||
materialMode,
|
||||
smartSelectedIds,
|
||||
voiceMode,
|
||||
selectedVoice,
|
||||
selectedClonedVoice,
|
||||
coverSettings,
|
||||
videoRatio,
|
||||
style,
|
||||
duration,
|
||||
autoSubtitles,
|
||||
bgm,
|
||||
generateCount,
|
||||
}: UseGenerateVideoProps) {
|
||||
/* ── 生成状态 ── */
|
||||
const [generating, setGenerating] = useState(false)
|
||||
const [progress, setProgress] = useState(0)
|
||||
const [generated, setGenerated] = useState(false)
|
||||
const [generateError, setGenerateError] = useState<string | null>(null)
|
||||
const [generatedVideos, setGeneratedVideos] = useState<GeneratedVideo[]>([])
|
||||
|
||||
const progressTimer = useRef<ReturnType<typeof setInterval>>(undefined)
|
||||
|
||||
/* ── 生成阶段映射 ── */
|
||||
const getGenerationPhase = (p: number) => {
|
||||
if (p < 20) return { label: "分析素材与配置", icon: "🔍" }
|
||||
if (p < 50) return { label: "智能剪辑合成", icon: "🎬" }
|
||||
if (p < 80) return { label: "渲染视频中", icon: "⚡" }
|
||||
return { label: "即将完成", icon: "✨" }
|
||||
}
|
||||
|
||||
/* ── 生成视频 ── */
|
||||
const generate = useCallback(async () => {
|
||||
console.log("[handleGenerate] 开始生成, 参数:", {
|
||||
titleSettings,
|
||||
selectedTemplate,
|
||||
selectedMaterials,
|
||||
voiceMode,
|
||||
})
|
||||
if (!titleSettings.title.trim()) {
|
||||
message.warning("请先选择或输入标题")
|
||||
return
|
||||
}
|
||||
if (materialMode === "manual" && selectedMaterials.length === 0) {
|
||||
message.warning("请至少选择一个素材")
|
||||
return
|
||||
}
|
||||
|
||||
if (voiceMode === "clone" && !selectedClonedVoice) {
|
||||
message.warning("请先选择一个克隆音色")
|
||||
return
|
||||
}
|
||||
|
||||
setGenerating(true)
|
||||
setProgress(0)
|
||||
setGenerated(false)
|
||||
setGenerateError(null)
|
||||
|
||||
try {
|
||||
const voiceConfig: Pick<
|
||||
EditPlanConfig,
|
||||
"voice_id" | "voice_clone_profile_id" | "custom_audio_url" | "custom_text"
|
||||
> = {}
|
||||
if (voiceMode === "preset") {
|
||||
voiceConfig.voice_id = selectedVoice || undefined
|
||||
} else if (voiceMode === "clone") {
|
||||
voiceConfig.voice_clone_profile_id = selectedClonedVoice || undefined
|
||||
} else if (voiceMode === "custom") {
|
||||
voiceConfig.voice_id = selectedVoice || undefined
|
||||
// 注意:customAudioUrl / customVoiceText 在 step5 hook 中,
|
||||
// 自定义配音模式需从 step5 组件传回
|
||||
}
|
||||
|
||||
// 获取或创建草稿
|
||||
await getEditPlan(selectedTemplate)
|
||||
|
||||
// 更新草稿内容 + 切换到 editing 状态
|
||||
await updateEditPlan(selectedTemplate, {
|
||||
name: titleSettings.title.trim(),
|
||||
config: {
|
||||
asset_ids: materialMode === "auto" ? smartSelectedIds : selectedMaterials,
|
||||
title_config: {
|
||||
ai_auto_select: titleSettings.aiAutoSelect,
|
||||
content: titleSettings.title,
|
||||
position: titleSettings.position,
|
||||
font_preset: titleSettings.font,
|
||||
font_color: titleSettings.color,
|
||||
font_size: titleSettings.size,
|
||||
},
|
||||
cover_config: coverSettings,
|
||||
...voiceConfig,
|
||||
ratio: videoRatio,
|
||||
style,
|
||||
duration,
|
||||
auto_subtitles: autoSubtitles,
|
||||
bgm,
|
||||
generate_count: generateCount,
|
||||
material_mode: materialMode,
|
||||
},
|
||||
total_duration: duration,
|
||||
status: "editing",
|
||||
})
|
||||
|
||||
await generateEditPlan(selectedTemplate)
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const data = await getGenerationStatus(selectedTemplate)
|
||||
|
||||
if (data.plan_status === "completed") {
|
||||
setProgress(100)
|
||||
setGenerating(false)
|
||||
setGenerated(true)
|
||||
|
||||
// 获取生成的视频结果
|
||||
if (data.generation_task_id) {
|
||||
try {
|
||||
const videos = await getGenerationTaskResults(data.generation_task_id)
|
||||
setGeneratedVideos(videos)
|
||||
} catch (err) {
|
||||
console.error("[获取生成结果失败]", err)
|
||||
}
|
||||
}
|
||||
|
||||
message.success("视频生成完成!")
|
||||
return
|
||||
}
|
||||
if (data.plan_status === "failed") {
|
||||
setGenerating(false)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 防御性错误提取
|
||||
const dataAny = data as Record<string, any>
|
||||
const rawMsg =
|
||||
dataAny.error_message ||
|
||||
dataAny.error ||
|
||||
dataAny.message ||
|
||||
(data.clips || []).find((c: { status: string }) => c.status === "failed")
|
||||
?.error_message ||
|
||||
"视频生成失败,请联系管理员或重试"
|
||||
const safeExtract = (val: unknown): string => {
|
||||
if (typeof val === "string") return val
|
||||
if (typeof val === "object" && val !== null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 防御性错误提取
|
||||
const obj = val as Record<string, any>
|
||||
if (typeof obj.message === "string") return obj.message
|
||||
if (typeof obj.msg === "string") return obj.msg
|
||||
if (typeof obj.detail === "string") return obj.detail
|
||||
if (obj.message && typeof obj.message === "object") return safeExtract(obj.message)
|
||||
return JSON.stringify(val)
|
||||
}
|
||||
return String(val ?? "")
|
||||
}
|
||||
const errorMsg = safeExtract(rawMsg)
|
||||
console.error("[生成失败] templateId:", selectedTemplate, "响应:", data)
|
||||
setGenerateError(errorMsg)
|
||||
message.error(errorMsg)
|
||||
return
|
||||
}
|
||||
|
||||
const clips = data.clips || []
|
||||
const total = clips.length || 1
|
||||
const done = clips.filter((c: { status: string }) => c.status === "completed").length
|
||||
setProgress(Math.round((done / total) * 100))
|
||||
|
||||
progressTimer.current = setTimeout(poll, 2000) as unknown as ReturnType<
|
||||
typeof setInterval
|
||||
>
|
||||
} catch (pollErr) {
|
||||
console.error("[轮询出错] templateId:", selectedTemplate, pollErr)
|
||||
progressTimer.current = setTimeout(poll, 3000) as unknown as ReturnType<
|
||||
typeof setInterval
|
||||
>
|
||||
}
|
||||
}
|
||||
|
||||
progressTimer.current = setTimeout(poll, 2000) as unknown as ReturnType<typeof setInterval>
|
||||
} catch (err: unknown) {
|
||||
console.error("[handleGenerate] 生成失败:", err)
|
||||
setGenerating(false)
|
||||
const axiosErr = err as {
|
||||
response?: {
|
||||
data?: {
|
||||
message?: string | object
|
||||
error?: string | object
|
||||
detail?: string | object
|
||||
msg?: string | object
|
||||
}
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
const extractString = (val: unknown): string => {
|
||||
if (typeof val === "string") return val
|
||||
if (typeof val === "object" && val !== null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 防御性错误提取
|
||||
const obj = val as Record<string, any>
|
||||
if (typeof obj.message === "string") return obj.message
|
||||
if (typeof obj.msg === "string") return obj.msg
|
||||
if (typeof obj.detail === "string") return obj.detail
|
||||
if (typeof obj.message === "object" && obj.message !== null)
|
||||
return extractString(obj.message)
|
||||
if (typeof obj.msg === "object" && obj.msg !== null) return extractString(obj.msg)
|
||||
return JSON.stringify(val)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
const backendMsg =
|
||||
extractString(axiosErr.response?.data?.message) ||
|
||||
extractString(axiosErr.response?.data?.error) ||
|
||||
extractString(axiosErr.response?.data?.detail) ||
|
||||
extractString(axiosErr.response?.data?.msg) ||
|
||||
axiosErr.message ||
|
||||
""
|
||||
console.error("[handleGenerate] 错误信息:", backendMsg, "完整错误:", axiosErr)
|
||||
const safeExtractErr = (val: unknown): string => {
|
||||
if (typeof val === "string") return val
|
||||
if (typeof val === "object" && val !== null) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- 防御性错误提取
|
||||
const obj = val as Record<string, any>
|
||||
if (typeof obj.message === "string") return obj.message
|
||||
if (typeof obj.msg === "string") return obj.msg
|
||||
if (typeof obj.detail === "string") return obj.detail
|
||||
if (typeof obj.message === "object") return safeExtractErr(obj.message)
|
||||
return JSON.stringify(val)
|
||||
}
|
||||
return String(val ?? "")
|
||||
}
|
||||
const rawError = safeExtractErr(backendMsg)
|
||||
const translateError = (msg: string): string => {
|
||||
if (!msg) return "生成失败,请检查网络后重试或联系管理员"
|
||||
if (msg.includes("editing") || msg.includes("draft") || msg.includes("状态")) {
|
||||
return "正在准备生成,请稍候再试"
|
||||
}
|
||||
if (msg.includes("template_id") || msg.includes("not found") || msg.includes("不存在")) {
|
||||
return "所选模板或素材不可用,请重新选择"
|
||||
}
|
||||
if (msg.includes("asset") && (msg.includes("not found") || msg.includes("missing"))) {
|
||||
return "素材数据异常,请返回视频库重新检查"
|
||||
}
|
||||
if (msg.includes("timeout") || msg.includes("network") || msg.includes("ECONN")) {
|
||||
return "网络连接超时,请检查网络后重试"
|
||||
}
|
||||
if (msg.includes("quota") || msg.includes("limit") || msg.includes("exceed")) {
|
||||
return "已达到生成次数上限,请稍后再试或联系客服"
|
||||
}
|
||||
if (msg.length > 0 && msg.length < 100 && !msg.includes("{")) return msg
|
||||
return "生成失败,请稍后重试或联系管理员"
|
||||
}
|
||||
const finalMsg = translateError(rawError)
|
||||
setGenerateError(finalMsg)
|
||||
message.error(finalMsg)
|
||||
}
|
||||
}, [
|
||||
titleSettings,
|
||||
selectedMaterials,
|
||||
selectedVoice,
|
||||
voiceMode,
|
||||
selectedClonedVoice,
|
||||
videoRatio,
|
||||
style,
|
||||
duration,
|
||||
autoSubtitles,
|
||||
bgm,
|
||||
selectedTemplate,
|
||||
generateCount,
|
||||
materialMode,
|
||||
coverSettings,
|
||||
smartSelectedIds,
|
||||
])
|
||||
|
||||
/* 重新生成(失败后重试) */
|
||||
const retry = useCallback(() => {
|
||||
setGenerateError(null)
|
||||
generate()
|
||||
}, [generate])
|
||||
|
||||
/* 清除错误 */
|
||||
const dismissError = useCallback(() => {
|
||||
setGenerateError(null)
|
||||
}, [])
|
||||
|
||||
/* ── 下载视频 ── */
|
||||
const download = useCallback(async () => {
|
||||
if (!generatedVideos.length) return
|
||||
const video = generatedVideos[0]
|
||||
try {
|
||||
const url = video.download_url || video.file_url
|
||||
if (url) {
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = video.name || "generated-video.mp4"
|
||||
a.target = "_blank"
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[下载失败]", err)
|
||||
message.error("下载失败,请重试")
|
||||
}
|
||||
}, [generatedVideos])
|
||||
|
||||
/* ── 分享视频 ── */
|
||||
const share = useCallback(async () => {
|
||||
if (!generatedVideos.length) return
|
||||
const video = generatedVideos[0]
|
||||
const shareUrl = video.file_url || window.location.href
|
||||
try {
|
||||
await navigator.clipboard.writeText(shareUrl)
|
||||
message.success("视频链接已复制到剪贴板")
|
||||
} catch {
|
||||
message.info(`视频链接: ${shareUrl}`)
|
||||
}
|
||||
}, [generatedVideos])
|
||||
|
||||
return {
|
||||
// 状态
|
||||
generating,
|
||||
progress,
|
||||
generated,
|
||||
generateError,
|
||||
generatedVideos,
|
||||
// 操作
|
||||
generate,
|
||||
retry,
|
||||
dismissError,
|
||||
download,
|
||||
share,
|
||||
// 工具
|
||||
getGenerationPhase,
|
||||
}
|
||||
}
|
||||
|
||||
export default useGenerateVideo
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Step 1 模板选择 Hook
|
||||
* 封装模板选择的交互逻辑
|
||||
*/
|
||||
import { useCallback } from "react"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
|
||||
interface UseStep1TemplateProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
onSelectTemplate: (id: string) => void
|
||||
}
|
||||
|
||||
export function useStep1Template({
|
||||
templates,
|
||||
selectedTemplate,
|
||||
onSelectTemplate,
|
||||
}: UseStep1TemplateProps) {
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => {
|
||||
onSelectTemplate(id)
|
||||
},
|
||||
[onSelectTemplate],
|
||||
)
|
||||
|
||||
const handleKeySelect = useCallback(
|
||||
(e: React.KeyboardEvent, id: string) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault()
|
||||
onSelectTemplate(id)
|
||||
}
|
||||
},
|
||||
[onSelectTemplate],
|
||||
)
|
||||
|
||||
return {
|
||||
templates,
|
||||
selectedTemplate,
|
||||
handleSelect,
|
||||
handleKeySelect,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep1Template
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Step 2 素材选择 Hook
|
||||
* 封装素材库加载、手动选择、智能匹配等逻辑
|
||||
*/
|
||||
import { useState, useCallback, useEffect, useMemo } from "react"
|
||||
import { message } from "antd"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { getAssets, getAssetLibraries } from "@/api/assets"
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
import { formatDuration } from "../utils/formatDuration"
|
||||
import { SMART_MATCH_REASONS } from "../constants"
|
||||
|
||||
interface SmartMatchedResult {
|
||||
asset: AssetItem
|
||||
matchScore: number
|
||||
matchReason: string
|
||||
}
|
||||
|
||||
interface UseStep2MaterialsProps {
|
||||
materialMode: "manual" | "auto"
|
||||
onMaterialModeChange: (mode: "manual" | "auto") => void
|
||||
selectedMaterials: string[]
|
||||
onSelectedMaterialsChange: (ids: string[]) => void
|
||||
smartSelectedIds: string[]
|
||||
onSmartSelectedIdsChange: (ids: string[]) => void
|
||||
}
|
||||
|
||||
export function useStep2Materials({
|
||||
materialMode,
|
||||
onMaterialModeChange,
|
||||
selectedMaterials,
|
||||
onSelectedMaterialsChange,
|
||||
smartSelectedIds,
|
||||
onSmartSelectedIdsChange,
|
||||
}: UseStep2MaterialsProps) {
|
||||
/* ── 素材库数据 API ── */
|
||||
const { data: libraries = [] } = useQuery({
|
||||
queryKey: ["asset-libraries"],
|
||||
queryFn: getAssetLibraries,
|
||||
})
|
||||
const [selectedLibraryId, setSelectedLibraryId] = useState<string>("")
|
||||
|
||||
// 自动选中第一个视频库
|
||||
useEffect(() => {
|
||||
if (libraries.length > 0 && !selectedLibraryId) {
|
||||
setSelectedLibraryId(libraries[0].id)
|
||||
}
|
||||
}, [libraries, selectedLibraryId])
|
||||
|
||||
const { data: materials = { items: [], total: 0 }, isLoading: materialsLoading } = useQuery<{
|
||||
items: AssetItem[]
|
||||
total: number
|
||||
}>({
|
||||
queryKey: ["generate-assets", selectedLibraryId],
|
||||
queryFn: () => getAssets(selectedLibraryId),
|
||||
enabled: !!selectedLibraryId,
|
||||
})
|
||||
|
||||
/* ── 智能素材匹配状态 ── */
|
||||
const [smartMatchInput, setSmartMatchInput] = useState("")
|
||||
const [smartMatching, setSmartMatching] = useState(false)
|
||||
const [smartMatchedResults, setSmartMatchedResults] = useState<SmartMatchedResult[]>([])
|
||||
const [hasMatched, setHasMatched] = useState(false)
|
||||
|
||||
/* ── 手动选择素材 ── */
|
||||
const handleToggleMaterial = useCallback(
|
||||
(materialId: string) => {
|
||||
onSelectedMaterialsChange(
|
||||
selectedMaterials.includes(materialId)
|
||||
? selectedMaterials.filter((id) => id !== materialId)
|
||||
: [...selectedMaterials, materialId],
|
||||
)
|
||||
},
|
||||
[selectedMaterials, onSelectedMaterialsChange],
|
||||
)
|
||||
|
||||
/* ── 智能素材匹配 ── */
|
||||
const handleSmartMatch = useCallback(async () => {
|
||||
if (!smartMatchInput.trim()) {
|
||||
message.warning("请先输入视频内容描述")
|
||||
return
|
||||
}
|
||||
if (materials.items.length === 0) {
|
||||
message.warning("当前视频库暂无素材")
|
||||
return
|
||||
}
|
||||
|
||||
setSmartMatching(true)
|
||||
setHasMatched(true)
|
||||
|
||||
// 模拟 AI 匹配延迟
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500))
|
||||
|
||||
// 从素材库中随机选取 5-8 个作为推荐结果
|
||||
const shuffled = [...materials.items].sort(() => Math.random() - 0.5)
|
||||
const count = Math.min(shuffled.length, 5 + Math.floor(Math.random() * 4))
|
||||
const picked = shuffled.slice(0, count)
|
||||
|
||||
const results = picked.map((asset, idx) => ({
|
||||
asset,
|
||||
matchScore: Math.round(85 + Math.random() * 14), // 85-99 分
|
||||
matchReason:
|
||||
SMART_MATCH_REASONS[idx % SMART_MATCH_REASONS.length] +
|
||||
(Math.random() > 0.5 ? ",画面质感优秀" : ""),
|
||||
}))
|
||||
|
||||
// 按匹配度从高到低排序
|
||||
results.sort((a, b) => b.matchScore - a.matchScore)
|
||||
|
||||
setSmartMatchedResults(results)
|
||||
// 默认选中匹配度 >= 90 的素材
|
||||
const defaultSelected = results.filter((r) => r.matchScore >= 90).map((r) => r.asset.id)
|
||||
onSmartSelectedIdsChange(
|
||||
defaultSelected.length > 0 ? defaultSelected : results.slice(0, 3).map((r) => r.asset.id),
|
||||
)
|
||||
setSmartMatching(false)
|
||||
}, [smartMatchInput, materials.items, onSmartSelectedIdsChange])
|
||||
|
||||
const handleToggleSmartSelect = useCallback(
|
||||
(assetId: string) => {
|
||||
onSmartSelectedIdsChange(
|
||||
smartSelectedIds.includes(assetId)
|
||||
? smartSelectedIds.filter((id) => id !== assetId)
|
||||
: [...smartSelectedIds, assetId],
|
||||
)
|
||||
},
|
||||
[smartSelectedIds, onSmartSelectedIdsChange],
|
||||
)
|
||||
|
||||
const handleRefreshMatch = useCallback(async () => {
|
||||
if (materials.items.length <= 5) {
|
||||
message.info("视频库素材较少,无法换一批")
|
||||
return
|
||||
}
|
||||
setSmartMatching(true)
|
||||
await new Promise((resolve) => setTimeout(resolve, 800))
|
||||
|
||||
const remaining = materials.items.filter(
|
||||
(m) => !smartMatchedResults.some((r) => r.asset.id === m.id),
|
||||
)
|
||||
const shuffled = [...remaining].sort(() => Math.random() - 0.5)
|
||||
const count = Math.min(shuffled.length, 5 + Math.floor(Math.random() * 3))
|
||||
const picked = shuffled.slice(0, count)
|
||||
|
||||
const results = picked.map((asset, idx) => ({
|
||||
asset,
|
||||
matchScore: Math.round(80 + Math.random() * 19),
|
||||
matchReason:
|
||||
SMART_MATCH_REASONS[(idx + 2) % SMART_MATCH_REASONS.length] +
|
||||
(Math.random() > 0.5 ? ",节奏明快" : ""),
|
||||
}))
|
||||
results.sort((a, b) => b.matchScore - a.matchScore)
|
||||
|
||||
setSmartMatchedResults(results)
|
||||
onSmartSelectedIdsChange([])
|
||||
setSmartMatching(false)
|
||||
}, [materials.items, smartMatchedResults, onSmartSelectedIdsChange])
|
||||
|
||||
const handleSelectAllMatched = useCallback(() => {
|
||||
onSmartSelectedIdsChange(smartMatchedResults.map((r) => r.asset.id))
|
||||
}, [smartMatchedResults, onSmartSelectedIdsChange])
|
||||
|
||||
const handleClearSmartSelect = useCallback(() => {
|
||||
onSmartSelectedIdsChange([])
|
||||
}, [onSmartSelectedIdsChange])
|
||||
|
||||
/* ── 计算已选智能匹配素材的总时长 ── */
|
||||
const smartSelectedTotalDuration = useMemo(() => {
|
||||
return smartMatchedResults
|
||||
.filter((r) => smartSelectedIds.includes(r.asset.id))
|
||||
.reduce((sum, r) => sum + (r.asset.duration || 0), 0)
|
||||
}, [smartMatchedResults, smartSelectedIds])
|
||||
|
||||
return {
|
||||
// 素材库
|
||||
libraries,
|
||||
selectedLibraryId,
|
||||
setSelectedLibraryId,
|
||||
materials,
|
||||
materialsLoading,
|
||||
// 模式
|
||||
materialMode,
|
||||
onMaterialModeChange,
|
||||
// 手动选择
|
||||
selectedMaterials,
|
||||
handleToggleMaterial,
|
||||
// 智能匹配
|
||||
smartMatchInput,
|
||||
setSmartMatchInput,
|
||||
smartMatching,
|
||||
smartMatchedResults,
|
||||
hasMatched,
|
||||
smartSelectedIds,
|
||||
handleSmartMatch,
|
||||
handleToggleSmartSelect,
|
||||
handleRefreshMatch,
|
||||
handleSelectAllMatched,
|
||||
handleClearSmartSelect,
|
||||
smartSelectedTotalDuration,
|
||||
// utils
|
||||
formatDuration,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep2Materials
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Step 3 生成预览 Hook
|
||||
* 封装预览信息的计算逻辑
|
||||
*/
|
||||
import { useMemo } from "react"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
|
||||
interface UseStep3PreviewProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
materialMode: "manual" | "auto"
|
||||
selectedMaterials: string[]
|
||||
smartSelectedIds: string[]
|
||||
duration: number
|
||||
videoRatio: string
|
||||
}
|
||||
|
||||
export function useStep3Preview({
|
||||
templates,
|
||||
selectedTemplate,
|
||||
materialMode,
|
||||
selectedMaterials,
|
||||
smartSelectedIds,
|
||||
duration,
|
||||
videoRatio,
|
||||
}: UseStep3PreviewProps) {
|
||||
const templateName = useMemo(
|
||||
() => templates.find((t) => t.id === selectedTemplate)?.name ?? "未选择",
|
||||
[templates, selectedTemplate],
|
||||
)
|
||||
|
||||
const materialCount = useMemo(() => {
|
||||
if (materialMode === "auto") {
|
||||
return `${smartSelectedIds.length} 个素材(智能匹配)`
|
||||
}
|
||||
return `${selectedMaterials.length} 个素材`
|
||||
}, [materialMode, selectedMaterials.length, smartSelectedIds.length])
|
||||
|
||||
return {
|
||||
templateName,
|
||||
materialCount,
|
||||
duration,
|
||||
videoRatio,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep3Preview
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Step 4 标题设置 Hook
|
||||
* 封装 AI 标题生成、标题样式设置等逻辑
|
||||
*/
|
||||
import { useState, useCallback, useMemo } from "react"
|
||||
import { message } from "antd"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { getTitles } from "@/api/titles"
|
||||
import { TITLE_PRESETS, AI_TITLE_TEMPLATES } from "../constants"
|
||||
import type { TitleSettings } from "../types"
|
||||
|
||||
interface UseStep4TitleProps {
|
||||
titleSettings: TitleSettings
|
||||
onTitleSettingsChange: (settings: TitleSettings) => void
|
||||
}
|
||||
|
||||
interface AiTitleItem {
|
||||
title: string
|
||||
highlight: string
|
||||
style: "catchy" | "emotional" | "informative"
|
||||
}
|
||||
|
||||
export function useStep4Title({ titleSettings, onTitleSettingsChange }: UseStep4TitleProps) {
|
||||
/* ── 标题库 API ── */
|
||||
const { data: userTitles = [] } = useQuery({
|
||||
queryKey: ["titles"],
|
||||
queryFn: () => getTitles(),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
/* ── AI 标题生成状态 ── */
|
||||
const [aiTitleInput, setAiTitleInput] = useState("")
|
||||
const [aiTitleGenerating, setAiTitleGenerating] = useState(false)
|
||||
const [aiTitleResults, setAiTitleResults] = useState<AiTitleItem[]>([])
|
||||
const [hasGeneratedTitles, setHasGeneratedTitles] = useState(false)
|
||||
|
||||
/* ── 辅助函数 ── */
|
||||
const extractTopic = (text: string): string => {
|
||||
const keywords = text
|
||||
.replace(/[,。!?、,.!?]/g, " ")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
if (keywords.length === 0) return "这个话题"
|
||||
// 取前3个关键词组合
|
||||
return keywords.slice(0, 3).join("")
|
||||
}
|
||||
|
||||
const getActivePreset = (settings: TitleSettings): string | null => {
|
||||
for (const p of TITLE_PRESETS) {
|
||||
if (
|
||||
settings.size === p.style.size &&
|
||||
settings.color === p.style.color &&
|
||||
settings.bold === p.style.bold &&
|
||||
settings.italic === p.style.italic &&
|
||||
settings.stroke === p.style.stroke &&
|
||||
settings.shadow === p.style.shadow
|
||||
) {
|
||||
return p.key
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const activePreset = useMemo(() => getActivePreset(titleSettings), [titleSettings])
|
||||
|
||||
/* ── AI 标题生成 ── */
|
||||
const handleGenerateAiTitles = useCallback(async () => {
|
||||
if (!aiTitleInput.trim()) {
|
||||
message.warning("请先输入视频描述或关键词")
|
||||
return
|
||||
}
|
||||
setAiTitleGenerating(true)
|
||||
setHasGeneratedTitles(true)
|
||||
|
||||
// 模拟 AI 生成延迟
|
||||
await new Promise((resolve) => setTimeout(resolve, 1200))
|
||||
|
||||
const topic = extractTopic(aiTitleInput)
|
||||
const results: AiTitleItem[] = []
|
||||
|
||||
const styles: Array<"catchy" | "emotional" | "informative"> = [
|
||||
"catchy",
|
||||
"emotional",
|
||||
"informative",
|
||||
]
|
||||
styles.forEach((style) => {
|
||||
const templates = AI_TITLE_TEMPLATES[style]
|
||||
// 每种风格随机选2个
|
||||
const shuffled = [...templates].sort(() => Math.random() - 0.5).slice(0, 2)
|
||||
shuffled.forEach((tpl) => {
|
||||
const title = tpl.replace(/\{topic\}/g, topic)
|
||||
const highlights = {
|
||||
catchy: "吸睛标题",
|
||||
emotional: "情感共鸣",
|
||||
informative: "知识干货",
|
||||
}
|
||||
results.push({
|
||||
title,
|
||||
highlight: highlights[style],
|
||||
style,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// 打乱顺序
|
||||
results.sort(() => Math.random() - 0.5)
|
||||
setAiTitleResults(results)
|
||||
setAiTitleGenerating(false)
|
||||
}, [aiTitleInput])
|
||||
|
||||
const handleSelectAiTitle = useCallback(
|
||||
(title: string) => {
|
||||
onTitleSettingsChange({ ...titleSettings, title, aiAutoSelect: false })
|
||||
message.success("已选用此标题")
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const handleRefreshAiTitles = useCallback(async () => {
|
||||
if (!aiTitleInput.trim()) return
|
||||
setAiTitleGenerating(true)
|
||||
await new Promise((resolve) => setTimeout(resolve, 800))
|
||||
// 重新生成一批
|
||||
const topic = extractTopic(aiTitleInput)
|
||||
const results: AiTitleItem[] = []
|
||||
const styles: Array<"catchy" | "emotional" | "informative"> = [
|
||||
"catchy",
|
||||
"emotional",
|
||||
"informative",
|
||||
]
|
||||
const highlights = { catchy: "吸睛标题", emotional: "情感共鸣", informative: "知识干货" }
|
||||
styles.forEach((style) => {
|
||||
const templates = AI_TITLE_TEMPLATES[style]
|
||||
const shuffled = [...templates].sort(() => Math.random() - 0.5).slice(0, 2)
|
||||
shuffled.forEach((tpl) => {
|
||||
results.push({
|
||||
title: tpl.replace(/\{topic\}/g, topic),
|
||||
highlight: highlights[style],
|
||||
style,
|
||||
})
|
||||
})
|
||||
})
|
||||
results.sort(() => Math.random() - 0.5)
|
||||
setAiTitleResults(results)
|
||||
setAiTitleGenerating(false)
|
||||
}, [aiTitleInput])
|
||||
|
||||
/* ── 标题设置更新 ── */
|
||||
const updateTitle = useCallback(
|
||||
(title: string) => {
|
||||
onTitleSettingsChange({ ...titleSettings, title })
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const toggleAiAutoSelect = useCallback(() => {
|
||||
onTitleSettingsChange({ ...titleSettings, aiAutoSelect: !titleSettings.aiAutoSelect })
|
||||
}, [titleSettings, onTitleSettingsChange])
|
||||
|
||||
const updatePosition = useCallback(
|
||||
(position: string) => {
|
||||
onTitleSettingsChange({ ...titleSettings, position })
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const updateFont = useCallback(
|
||||
(font: string) => {
|
||||
onTitleSettingsChange({ ...titleSettings, font })
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const updateSize = useCallback(
|
||||
(size: number) => {
|
||||
onTitleSettingsChange({ ...titleSettings, size })
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const updateColor = useCallback(
|
||||
(color: string) => {
|
||||
onTitleSettingsChange({ ...titleSettings, color })
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
const toggleBold = useCallback(() => {
|
||||
onTitleSettingsChange({ ...titleSettings, bold: !titleSettings.bold })
|
||||
}, [titleSettings, onTitleSettingsChange])
|
||||
|
||||
const toggleItalic = useCallback(() => {
|
||||
onTitleSettingsChange({ ...titleSettings, italic: !titleSettings.italic })
|
||||
}, [titleSettings, onTitleSettingsChange])
|
||||
|
||||
const toggleStroke = useCallback(() => {
|
||||
onTitleSettingsChange({ ...titleSettings, stroke: !titleSettings.stroke })
|
||||
}, [titleSettings, onTitleSettingsChange])
|
||||
|
||||
const toggleShadow = useCallback(() => {
|
||||
onTitleSettingsChange({ ...titleSettings, shadow: !titleSettings.shadow })
|
||||
}, [titleSettings, onTitleSettingsChange])
|
||||
|
||||
const applyPreset = useCallback(
|
||||
(presetKey: string) => {
|
||||
const preset = TITLE_PRESETS.find((p) => p.key === presetKey)
|
||||
if (!preset) return
|
||||
onTitleSettingsChange({
|
||||
...titleSettings,
|
||||
size: preset.style.size,
|
||||
color: preset.style.color,
|
||||
bold: preset.style.bold,
|
||||
italic: preset.style.italic,
|
||||
stroke: preset.style.stroke,
|
||||
shadow: preset.style.shadow,
|
||||
})
|
||||
},
|
||||
[titleSettings, onTitleSettingsChange],
|
||||
)
|
||||
|
||||
return {
|
||||
// 数据
|
||||
userTitles,
|
||||
titleSettings,
|
||||
aiTitleInput,
|
||||
setAiTitleInput,
|
||||
aiTitleGenerating,
|
||||
aiTitleResults,
|
||||
hasGeneratedTitles,
|
||||
activePreset,
|
||||
titlePresets: TITLE_PRESETS,
|
||||
// AI 标题操作
|
||||
handleGenerateAiTitles,
|
||||
handleSelectAiTitle,
|
||||
handleRefreshAiTitles,
|
||||
// 标题设置操作
|
||||
updateTitle,
|
||||
toggleAiAutoSelect,
|
||||
updatePosition,
|
||||
updateFont,
|
||||
updateSize,
|
||||
updateColor,
|
||||
toggleBold,
|
||||
toggleItalic,
|
||||
toggleStroke,
|
||||
toggleShadow,
|
||||
applyPreset,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep4Title
|
||||
@@ -0,0 +1,397 @@
|
||||
/**
|
||||
* Step 5 配音选择 Hook
|
||||
* 封装 AI 推荐、预设音色试听、TTS 自定义合成、存为素材等逻辑
|
||||
*/
|
||||
import { useState, useRef, useCallback, useEffect, useMemo } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { message } from "antd"
|
||||
import { useQuery, useMutation } from "@tanstack/react-query"
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
import { fetchPresetVoices } from "@/api/voices"
|
||||
import { synthesizeSpeech, getTTSJobStatus, saveTtsToLibrary } from "@/api/tts"
|
||||
import { getTags, createTag } from "@/api/tags"
|
||||
import { formatDuration } from "../utils/formatDuration"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
import { VOICE_GENDER_ICON, CLONE_STATUS_CONFIG } from "../constants"
|
||||
|
||||
interface UseStep5VoiceProps {
|
||||
selectedVoice: string
|
||||
onSelectedVoiceChange: (voiceId: string) => void
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
onVoiceModeChange: (mode: "preset" | "custom" | "clone") => void
|
||||
selectedClonedVoice: string
|
||||
onSelectedClonedVoiceChange: (voiceId: string) => void
|
||||
clonedVoices: VoiceClone[]
|
||||
addClone: (voice: VoiceClone) => void
|
||||
hasProcessing: boolean
|
||||
cloneModalOpen: boolean
|
||||
onCloneModalOpenChange: (open: boolean) => void
|
||||
titleText: string
|
||||
}
|
||||
|
||||
export function useStep5Voice({
|
||||
selectedVoice,
|
||||
onSelectedVoiceChange,
|
||||
voiceMode,
|
||||
onVoiceModeChange,
|
||||
selectedClonedVoice,
|
||||
onSelectedClonedVoiceChange,
|
||||
clonedVoices,
|
||||
addClone,
|
||||
hasProcessing,
|
||||
cloneModalOpen,
|
||||
onCloneModalOpenChange,
|
||||
titleText,
|
||||
}: UseStep5VoiceProps) {
|
||||
const navigate = useNavigate()
|
||||
/* ── 预置音色 API ── */
|
||||
const { data: presetVoicesData, isLoading: presetVoicesLoading } = useQuery({
|
||||
queryKey: ["preset-voices"],
|
||||
queryFn: fetchPresetVoices,
|
||||
})
|
||||
const presetVoices: PresetVoiceItem[] = useMemo(
|
||||
() => presetVoicesData?.items ?? [],
|
||||
[presetVoicesData],
|
||||
)
|
||||
|
||||
/* ── 音频播放 ── */
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const [playingVoice, setPlayingVoice] = useState<string | null>(null)
|
||||
|
||||
const toggleVoicePlay = useCallback(
|
||||
(voiceId: string, previewUrl: string | null) => {
|
||||
if (playingVoice === voiceId) {
|
||||
audioRef.current?.pause()
|
||||
audioRef.current = null
|
||||
setPlayingVoice(null)
|
||||
return
|
||||
}
|
||||
audioRef.current?.pause()
|
||||
if (!previewUrl) {
|
||||
message.warning("该音色暂无试听音频")
|
||||
return
|
||||
}
|
||||
const audio = new Audio(previewUrl)
|
||||
audioRef.current = audio
|
||||
audio.play().catch(() => {
|
||||
message.error("播放失败,请检查网络")
|
||||
})
|
||||
audio.onended = () => {
|
||||
setPlayingVoice(null)
|
||||
audioRef.current = null
|
||||
}
|
||||
setPlayingVoice(voiceId)
|
||||
},
|
||||
[playingVoice],
|
||||
)
|
||||
|
||||
/* ── 智能配音推荐 ── */
|
||||
const [voiceRecommendLoading, setVoiceRecommendLoading] = useState(false)
|
||||
const [voiceRecommendations, setVoiceRecommendations] = useState<string[]>([])
|
||||
const [hasVoiceRecommend, setHasVoiceRecommend] = useState(false)
|
||||
|
||||
const handleVoiceRecommend = useCallback(async () => {
|
||||
if (presetVoices.length === 0) return
|
||||
setVoiceRecommendLoading(true)
|
||||
setHasVoiceRecommend(true)
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||
|
||||
// 根据标题内容风格模拟推荐:情感类→温柔女声,知识类→沉稳男声,活力类→阳光少年
|
||||
const title = titleText.toLowerCase()
|
||||
let recommended: string[] = []
|
||||
|
||||
const femaleVoices = presetVoices.filter((v) => v.gender === "female").map((v) => v.voice_id)
|
||||
const maleVoices = presetVoices.filter((v) => v.gender === "male").map((v) => v.voice_id)
|
||||
const childVoices = presetVoices.filter((v) => v.gender === "child").map((v) => v.voice_id)
|
||||
|
||||
if (/情感|感人|温暖|治愈|故事|回忆/.test(title)) {
|
||||
recommended = femaleVoices.slice(0, 3)
|
||||
} else if (/教程|知识|科普|干货|讲解|分析/.test(title)) {
|
||||
recommended = maleVoices.slice(0, 2).concat(femaleVoices.slice(0, 1))
|
||||
} else if (/活力|热血|运动|搞笑|有趣/.test(title)) {
|
||||
recommended = childVoices.slice(0, 1).concat(maleVoices.slice(0, 1), femaleVoices.slice(0, 1))
|
||||
} else {
|
||||
// 默认推荐前3个
|
||||
recommended = presetVoices.slice(0, 3).map((v) => v.voice_id)
|
||||
}
|
||||
|
||||
// 不足3个时补足
|
||||
if (recommended.length < 3) {
|
||||
const others = presetVoices
|
||||
.filter((v) => !recommended.includes(v.voice_id))
|
||||
.map((v) => v.voice_id)
|
||||
recommended = recommended.concat(others.slice(0, 3 - recommended.length))
|
||||
}
|
||||
|
||||
setVoiceRecommendations(recommended)
|
||||
setVoiceRecommendLoading(false)
|
||||
}, [presetVoices, titleText])
|
||||
|
||||
const handleSelectRecommendedVoice = useCallback(
|
||||
(voiceId: string) => {
|
||||
onVoiceModeChange("preset")
|
||||
onSelectedVoiceChange(voiceId)
|
||||
},
|
||||
[onVoiceModeChange, onSelectedVoiceChange],
|
||||
)
|
||||
|
||||
/* ── TTS 自定义合成状态 ── */
|
||||
const [customVoiceText, setCustomVoiceText] = useState("")
|
||||
const [customAudioUrl, setCustomAudioUrl] = useState<string | null>(null)
|
||||
const [ttsError, setTtsError] = useState<string | null>(null)
|
||||
const [ttsJobId, setTtsJobId] = useState<string | null>(null)
|
||||
/** 合成完成后保留的 job ID,用于"存为素材" */
|
||||
const [completedTtsJobId, setCompletedTtsJobId] = useState<string | null>(null)
|
||||
|
||||
/* ── TTS mutation ── */
|
||||
const synthesizeMutation = useMutation({
|
||||
mutationFn: synthesizeSpeech,
|
||||
onSuccess: (data) => {
|
||||
setTtsJobId(data.job_id)
|
||||
message.info("语音合成已提交,等待处理…")
|
||||
},
|
||||
onError: () => {
|
||||
setTtsError("语音合成请求失败,请重试")
|
||||
},
|
||||
})
|
||||
|
||||
/** 轮询 TTS 任务状态 */
|
||||
useEffect(() => {
|
||||
if (!ttsJobId) return
|
||||
let cancelled = false
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const status = await getTTSJobStatus(ttsJobId)
|
||||
if (cancelled) return
|
||||
if (status.status === "completed") {
|
||||
setCustomAudioUrl(status.output_audio_url)
|
||||
setCompletedTtsJobId(ttsJobId)
|
||||
setTtsJobId(null)
|
||||
setTtsError(null)
|
||||
message.success("语音合成完成!")
|
||||
return
|
||||
}
|
||||
if (status.status === "failed" || status.status === "cancelled") {
|
||||
setTtsError(status.error_message || "语音合成失败")
|
||||
setTtsJobId(null)
|
||||
return
|
||||
}
|
||||
timer = setTimeout(poll, 2000)
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setTtsError("查询合成状态失败")
|
||||
setTtsJobId(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
timer = setTimeout(poll, 2000)
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [ttsJobId])
|
||||
|
||||
/** 触发自定义文本 TTS 合成 */
|
||||
const handleSynthesizeVoice = useCallback(() => {
|
||||
if (!customVoiceText.trim()) {
|
||||
message.warning("请先输入配音文案")
|
||||
return
|
||||
}
|
||||
setTtsError(null)
|
||||
setCustomAudioUrl(null)
|
||||
synthesizeMutation.mutate({
|
||||
text: customVoiceText.trim(),
|
||||
voice_id: selectedVoice || undefined,
|
||||
language: "zh-CN",
|
||||
})
|
||||
}, [customVoiceText, selectedVoice, synthesizeMutation])
|
||||
|
||||
/* ── 存为素材弹窗状态 ── */
|
||||
const [saveModalOpen, setSaveModalOpen] = useState(false)
|
||||
const [saveName, setSaveName] = useState("")
|
||||
const [saveTagIds, setSaveTagIds] = useState<string[]>([])
|
||||
const [saveNewTag, setSaveNewTag] = useState("")
|
||||
|
||||
/* ── 标签列表(用于存为素材弹窗) ── */
|
||||
const { data: allTags = [] } = useQuery({
|
||||
queryKey: ["generate-save-tags"],
|
||||
queryFn: getTags,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
/* ── 存为素材 mutation ── */
|
||||
const saveToLibraryMutation = useMutation({
|
||||
mutationFn: (params: { name?: string; tag_ids?: string[] }) =>
|
||||
saveTtsToLibrary(completedTtsJobId!, params),
|
||||
onSuccess: () => {
|
||||
message.success({
|
||||
content: (
|
||||
<span>
|
||||
已保存到配音库!{" "}
|
||||
<a
|
||||
onClick={handleGoToLibrary}
|
||||
style={{
|
||||
color: "var(--primary-500, #6366f1)",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
去视频库查看
|
||||
</a>
|
||||
</span>
|
||||
),
|
||||
duration: 5,
|
||||
})
|
||||
setSaveModalOpen(false)
|
||||
setSaveName("")
|
||||
setSaveTagIds([])
|
||||
setSaveNewTag("")
|
||||
setCompletedTtsJobId(null)
|
||||
setCustomAudioUrl(null)
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
message.error(`保存失败:${err.message || "请重试"}`)
|
||||
},
|
||||
})
|
||||
|
||||
/** 打开存为素材弹窗 */
|
||||
const handleOpenSaveModal = useCallback(() => {
|
||||
setSaveName("")
|
||||
setSaveTagIds([])
|
||||
setSaveNewTag("")
|
||||
setSaveModalOpen(true)
|
||||
}, [])
|
||||
|
||||
/** 确认保存 */
|
||||
const handleConfirmSave = useCallback(() => {
|
||||
if (!completedTtsJobId) return
|
||||
saveToLibraryMutation.mutate({
|
||||
name: saveName.trim() || undefined,
|
||||
tag_ids: saveTagIds.length > 0 ? saveTagIds : undefined,
|
||||
})
|
||||
}, [completedTtsJobId, saveName, saveTagIds, saveToLibraryMutation])
|
||||
|
||||
/** 在弹窗中新增标签(先创建再选中) */
|
||||
const handleAddTagInModal = useCallback(
|
||||
async (tagName: string) => {
|
||||
const trimmed = tagName.trim()
|
||||
if (!trimmed) return
|
||||
/* 已在选中列表则跳过 */
|
||||
const existing = allTags.find((t) => t.name === trimmed)
|
||||
if (existing) {
|
||||
if (!saveTagIds.includes(existing.id)) {
|
||||
setSaveTagIds((prev) => [...prev, existing.id])
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
const created = await createTag(trimmed)
|
||||
setSaveTagIds((prev) => [...prev, created.id])
|
||||
setSaveNewTag("")
|
||||
} catch {
|
||||
message.error(`创建标签"${trimmed}"失败`)
|
||||
}
|
||||
},
|
||||
[allTags, saveTagIds],
|
||||
)
|
||||
|
||||
/** 保存成功后跳转到视频库 */
|
||||
const handleGoToLibrary = useCallback(() => {
|
||||
navigate("/app/voice-materials")
|
||||
}, [navigate])
|
||||
|
||||
/* ── 克隆成功回调 ── */
|
||||
const handleCloneSuccess = useCallback(
|
||||
(voice: VoiceClone) => {
|
||||
addClone(voice)
|
||||
onCloneModalOpenChange(false)
|
||||
message.success("音色克隆成功!")
|
||||
},
|
||||
[addClone, onCloneModalOpenChange],
|
||||
)
|
||||
|
||||
/* ── 预设音色选择操作 ── */
|
||||
const handleSelectPresetVoice = useCallback(
|
||||
(voiceId: string) => {
|
||||
onVoiceModeChange("preset")
|
||||
onSelectedVoiceChange(voiceId)
|
||||
},
|
||||
[onVoiceModeChange, onSelectedVoiceChange],
|
||||
)
|
||||
|
||||
const handleSelectCloneVoice = useCallback(() => {
|
||||
onVoiceModeChange("clone")
|
||||
}, [onVoiceModeChange])
|
||||
|
||||
const handleSelectClonedVoice = useCallback(
|
||||
(voiceId: string) => {
|
||||
onSelectedClonedVoiceChange(voiceId)
|
||||
},
|
||||
[onSelectedClonedVoiceChange],
|
||||
)
|
||||
|
||||
const handleOpenCloneModal = useCallback(() => {
|
||||
onCloneModalOpenChange(true)
|
||||
}, [onCloneModalOpenChange])
|
||||
|
||||
return {
|
||||
// 数据
|
||||
presetVoices,
|
||||
presetVoicesLoading,
|
||||
clonedVoices,
|
||||
hasProcessing,
|
||||
// 模式 & 选择
|
||||
voiceMode,
|
||||
selectedVoice,
|
||||
selectedClonedVoice,
|
||||
// AI 推荐
|
||||
voiceRecommendLoading,
|
||||
voiceRecommendations,
|
||||
hasVoiceRecommend,
|
||||
handleVoiceRecommend,
|
||||
handleSelectRecommendedVoice,
|
||||
// 音频播放
|
||||
playingVoice,
|
||||
toggleVoicePlay,
|
||||
// 预设音色操作
|
||||
handleSelectPresetVoice,
|
||||
handleSelectCloneVoice,
|
||||
// 自定义 TTS
|
||||
customVoiceText,
|
||||
setCustomVoiceText,
|
||||
customAudioUrl,
|
||||
ttsError,
|
||||
ttsJobId,
|
||||
completedTtsJobId,
|
||||
synthesizeMutation,
|
||||
handleSynthesizeVoice,
|
||||
// 存为素材
|
||||
saveModalOpen,
|
||||
setSaveModalOpen,
|
||||
saveName,
|
||||
setSaveName,
|
||||
saveTagIds,
|
||||
setSaveTagIds,
|
||||
saveNewTag,
|
||||
setSaveNewTag,
|
||||
allTags,
|
||||
saveToLibraryMutation,
|
||||
handleOpenSaveModal,
|
||||
handleConfirmSave,
|
||||
handleAddTagInModal,
|
||||
// 克隆
|
||||
cloneModalOpen,
|
||||
handleOpenCloneModal,
|
||||
handleCloneSuccess,
|
||||
handleSelectClonedVoice,
|
||||
// utils
|
||||
VOICE_GENDER_ICON,
|
||||
CLONE_STATUS_CONFIG,
|
||||
formatDuration,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep5Voice
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Step 6 封面设置 Hook
|
||||
* 封装封面设置的交互逻辑
|
||||
*/
|
||||
import { useCallback } from "react"
|
||||
import type { CoverConfig } from "../../editing-planner/types"
|
||||
import { COVER_MODE_LABELS, COVER_MODE_ICONS, DEFAULT_COVER_SETTINGS } from "../constants"
|
||||
|
||||
interface UseStep6CoverProps {
|
||||
coverSettings: CoverConfig
|
||||
onCoverSettingsChange: (settings: CoverConfig) => void
|
||||
duration: number
|
||||
}
|
||||
|
||||
export function useStep6Cover({
|
||||
coverSettings,
|
||||
onCoverSettingsChange,
|
||||
duration,
|
||||
}: UseStep6CoverProps) {
|
||||
const formatTime = useCallback((seconds: number) => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.floor(seconds % 60)
|
||||
const ms = Math.floor((seconds % 1) * 10)
|
||||
return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}.${ms}`
|
||||
}, [])
|
||||
|
||||
const toggleEnabled = useCallback(
|
||||
(enabled: boolean) => {
|
||||
onCoverSettingsChange({ ...coverSettings, enabled })
|
||||
},
|
||||
[coverSettings, onCoverSettingsChange],
|
||||
)
|
||||
|
||||
const setMode = useCallback(
|
||||
(mode: CoverConfig["mode"]) => {
|
||||
onCoverSettingsChange({ ...coverSettings, mode })
|
||||
},
|
||||
[coverSettings, onCoverSettingsChange],
|
||||
)
|
||||
|
||||
const setFrameTime = useCallback(
|
||||
(frameTime: number) => {
|
||||
onCoverSettingsChange({ ...coverSettings, frame_time: frameTime })
|
||||
},
|
||||
[coverSettings, onCoverSettingsChange],
|
||||
)
|
||||
|
||||
const handleUpload = useCallback(
|
||||
(file: File) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = (ev) => {
|
||||
const url = ev.target?.result as string
|
||||
onCoverSettingsChange({
|
||||
...coverSettings,
|
||||
upload_url: url,
|
||||
thumbnail_url: url,
|
||||
mode: "upload",
|
||||
})
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
},
|
||||
[coverSettings, onCoverSettingsChange],
|
||||
)
|
||||
|
||||
const totalDuration = duration || 30
|
||||
|
||||
return {
|
||||
coverSettings,
|
||||
formatTime,
|
||||
toggleEnabled,
|
||||
setMode,
|
||||
setFrameTime,
|
||||
handleUpload,
|
||||
totalDuration,
|
||||
COVER_MODE_LABELS,
|
||||
COVER_MODE_ICONS,
|
||||
DEFAULT_COVER_SETTINGS,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep6Cover
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Step 7 确认生成 Hook
|
||||
* 封装生成确认页的展示逻辑
|
||||
*/
|
||||
import { useMemo } from "react"
|
||||
import type { EditingTemplate } from "@/api/editing-planner"
|
||||
import type { GeneratedVideo } from "@/api/template-editor"
|
||||
import type { CoverConfig } from "../../editing-planner/types"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
import { COVER_MODE_LABELS } from "../constants"
|
||||
|
||||
interface UseStep7GenerateProps {
|
||||
templates: EditingTemplate[]
|
||||
selectedTemplate: string
|
||||
materialMode: "manual" | "auto"
|
||||
selectedMaterials: string[]
|
||||
smartSelectedIds: string[]
|
||||
title: string
|
||||
voiceMode: "preset" | "custom" | "clone"
|
||||
selectedVoice: string
|
||||
selectedClonedVoice: string
|
||||
presetVoices: PresetVoiceItem[]
|
||||
clonedVoices: VoiceClone[]
|
||||
coverSettings: CoverConfig
|
||||
generateCount: number
|
||||
onGenerateCountChange: (count: number) => void
|
||||
generating: boolean
|
||||
generated: boolean
|
||||
generateError: string | null
|
||||
progress: number
|
||||
generatedVideos: GeneratedVideo[]
|
||||
}
|
||||
|
||||
export function useStep7Generate({
|
||||
templates,
|
||||
selectedTemplate,
|
||||
materialMode,
|
||||
selectedMaterials,
|
||||
smartSelectedIds,
|
||||
title,
|
||||
voiceMode,
|
||||
selectedVoice,
|
||||
selectedClonedVoice,
|
||||
presetVoices,
|
||||
clonedVoices,
|
||||
coverSettings,
|
||||
generateCount,
|
||||
onGenerateCountChange,
|
||||
generating,
|
||||
generated,
|
||||
generateError,
|
||||
progress,
|
||||
generatedVideos,
|
||||
}: UseStep7GenerateProps) {
|
||||
const templateName = useMemo(
|
||||
() => templates.find((t) => t.id === selectedTemplate)?.name ?? "未选择",
|
||||
[templates, selectedTemplate],
|
||||
)
|
||||
|
||||
const materialSummary = useMemo(() => {
|
||||
if (materialMode === "auto") {
|
||||
return `${smartSelectedIds.length} 个素材(智能匹配)`
|
||||
}
|
||||
return `${selectedMaterials.length} 个素材`
|
||||
}, [materialMode, selectedMaterials.length, smartSelectedIds.length])
|
||||
|
||||
const voiceName = useMemo(() => {
|
||||
if (voiceMode === "clone") {
|
||||
const cv = clonedVoices.find((v) => v.id === selectedClonedVoice)
|
||||
return cv ? cv.name : "未选择"
|
||||
}
|
||||
const pv = presetVoices.find((v) => v.voice_id === selectedVoice)
|
||||
return pv ? pv.name : "未选择"
|
||||
}, [voiceMode, selectedVoice, selectedClonedVoice, presetVoices, clonedVoices])
|
||||
|
||||
const coverSummary = useMemo(() => {
|
||||
if (!coverSettings.enabled) return "不使用"
|
||||
return COVER_MODE_LABELS[coverSettings.mode] || "智能封面"
|
||||
}, [coverSettings])
|
||||
|
||||
const getGenerationPhase = (p: number) => {
|
||||
if (p < 20) return { label: "分析素材与配置", icon: "🔍" }
|
||||
if (p < 50) return { label: "智能剪辑合成", icon: "🎬" }
|
||||
if (p < 80) return { label: "渲染视频中", icon: "⚡" }
|
||||
return { label: "即将完成", icon: "✨" }
|
||||
}
|
||||
|
||||
const handleDecrement = () => {
|
||||
onGenerateCountChange(Math.max(1, generateCount - 1))
|
||||
}
|
||||
|
||||
const handleIncrement = () => {
|
||||
onGenerateCountChange(Math.min(10, generateCount + 1))
|
||||
}
|
||||
|
||||
const handleScrollToPreview = () => {
|
||||
const el = document.querySelector(".xx-preview-section")
|
||||
el?.scrollIntoView({ behavior: "smooth", block: "start" })
|
||||
}
|
||||
|
||||
return {
|
||||
templateName,
|
||||
materialSummary,
|
||||
title,
|
||||
voiceName,
|
||||
coverSummary,
|
||||
generateCount,
|
||||
handleDecrement,
|
||||
handleIncrement,
|
||||
generating,
|
||||
generated,
|
||||
generateError,
|
||||
progress,
|
||||
generatedVideos,
|
||||
getGenerationPhase,
|
||||
handleScrollToPreview,
|
||||
}
|
||||
}
|
||||
|
||||
export default useStep7Generate
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* 时长格式化工具
|
||||
* 秒数转分秒格式,如 65 -> "1:05"
|
||||
*/
|
||||
export const formatDuration = (seconds: number): string => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = seconds % 60
|
||||
return `${m}:${String(s).padStart(2, "0")}`
|
||||
}
|
||||
Regular → Executable
+96
-1459
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,186 @@
|
||||
import React, { useState, useRef } from "react"
|
||||
import { UploadOutlined, SoundOutlined, CloseOutlined } from "@ant-design/icons"
|
||||
import { Button, Input } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { type VoiceGender, type VoiceMaterial } from "../types"
|
||||
import { GENDER_OPTIONS } from "../constants"
|
||||
import { genderClass, formatFileSize } from "../utils/format"
|
||||
import TagSelector from "./TagSelector"
|
||||
|
||||
export interface MaterialFormProps {
|
||||
initial?: VoiceMaterial
|
||||
onSubmit: (data: Omit<VoiceMaterial, "id" | "createdAt"> & { file?: File }) => void
|
||||
onCancel: () => void
|
||||
loading?: boolean
|
||||
uploadProgress?: number | null
|
||||
tags?: TagItem[]
|
||||
tagMap?: Map<string, TagItem>
|
||||
onCreateTag?: (name: string) => Promise<TagItem>
|
||||
}
|
||||
|
||||
const MaterialForm: React.FC<MaterialFormProps> = ({
|
||||
initial,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
loading,
|
||||
uploadProgress,
|
||||
tags = [],
|
||||
tagMap = new Map(),
|
||||
onCreateTag,
|
||||
}) => {
|
||||
const [name, setName] = useState(initial?.name ?? "")
|
||||
const [description, setDescription] = useState(initial?.description ?? "")
|
||||
const [gender, setGender] = useState<VoiceGender>(initial?.gender ?? "female")
|
||||
const [selectedTagIds, setSelectedTagIds] = useState<string[]>(initial?.tagIds ?? [])
|
||||
const [file, setFile] = useState<File | undefined>(undefined)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!name.trim()) return
|
||||
if (!initial && !file) return
|
||||
onSubmit({
|
||||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
gender,
|
||||
tagIds: selectedTagIds,
|
||||
fileName: file?.name ?? initial?.fileName ?? "",
|
||||
fileSize: file?.size ?? initial?.fileSize ?? 0,
|
||||
duration: initial?.duration ?? 0,
|
||||
mimeType: file?.type ?? initial?.mimeType ?? "audio/mpeg",
|
||||
file,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="vmat-form">
|
||||
{/* 音频文件上传(编辑模式不显示) */}
|
||||
{!initial && (
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">音频文件 *</label>
|
||||
<div
|
||||
className="vmat-upload-zone"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
const f = e.dataTransfer.files[0]
|
||||
if (f?.type.startsWith("audio/")) setFile(f)
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/*"
|
||||
style={{ display: "none" }}
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) setFile(f)
|
||||
}}
|
||||
/>
|
||||
{file ? (
|
||||
<div className="vmat-upload-selected">
|
||||
<SoundOutlined className="vmat-upload-icon" />
|
||||
<span className="vmat-upload-filename">{file.name}</span>
|
||||
<span className="vmat-upload-filesize">{formatFileSize(file.size)}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-upload-clear"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setFile(undefined)
|
||||
}}
|
||||
>
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="vmat-upload-placeholder">
|
||||
<UploadOutlined className="vmat-upload-icon" />
|
||||
<p>点击或拖拽音频文件到此处</p>
|
||||
<span>支持 MP3、WAV、AAC、FLAC 等格式</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* 上传进度条 */}
|
||||
{uploadProgress !== null && uploadProgress !== undefined && (
|
||||
<div className="vmat-upload-progress">
|
||||
<div className="vmat-upload-progress-bar" style={{ width: `${uploadProgress}%` }} />
|
||||
<span className="vmat-upload-progress-text">{uploadProgress}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 名称 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">名称 *</label>
|
||||
<Input
|
||||
placeholder="输入配音素材名称"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={50}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 音色描述 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">音色描述</label>
|
||||
<Input.TextArea
|
||||
placeholder="描述音色特点,如:适合产品宣传的男声配音..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={200}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 性别 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">性别</label>
|
||||
<div className="vmat-gender-group">
|
||||
{GENDER_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
className={`vmat-gender-btn${gender === opt.value ? " active" : ""} ${genderClass(opt.value)}`}
|
||||
onClick={() => setGender(opt.value)}
|
||||
>
|
||||
{opt.icon}
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 风格标签 */}
|
||||
<div className="vmat-form-field">
|
||||
<label className="vmat-form-label">风格标签</label>
|
||||
<TagSelector
|
||||
value={selectedTagIds}
|
||||
onChange={setSelectedTagIds}
|
||||
tags={tags}
|
||||
tagMap={tagMap}
|
||||
onCreateTag={onCreateTag ?? (async () => ({ id: "", name: "" }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="vmat-form-actions">
|
||||
<Button buttonType="ghost" buttonSize="md" onClick={onCancel}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
buttonType="primary"
|
||||
buttonSize="md"
|
||||
onClick={handleSubmit}
|
||||
loading={loading}
|
||||
disabled={!name.trim() || (!initial && !file)}
|
||||
>
|
||||
{initial ? "保存修改" : "上传"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MaterialForm
|
||||
@@ -0,0 +1,163 @@
|
||||
import React, { useState, useRef, useCallback, useMemo } from "react"
|
||||
import { CheckOutlined } from "@ant-design/icons"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
|
||||
export interface TagSelectorProps {
|
||||
/** 已选标签 ID 列表 */
|
||||
value: string[]
|
||||
onChange: (tagIds: string[]) => void
|
||||
/** 所有可用标签(来自 API) */
|
||||
tags: TagItem[]
|
||||
/** 标签 ID → TagItem 映射 */
|
||||
tagMap: Map<string, TagItem>
|
||||
/** 创建新标签,返回带 ID 的 TagItem */
|
||||
onCreateTag: (name: string) => Promise<TagItem>
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
const TagSelector: React.FC<TagSelectorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
tags,
|
||||
tagMap,
|
||||
onCreateTag,
|
||||
placeholder = "输入标签后回车添加",
|
||||
}) => {
|
||||
const [inputVal, setInputVal] = useState("")
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
/** 按名称查找已有标签(大小写不敏感) */
|
||||
const findTagByName = useCallback(
|
||||
(name: string) => tags.find((t) => t.name.toLowerCase() === name.toLowerCase()),
|
||||
[tags],
|
||||
)
|
||||
|
||||
/** 去重添加标签(按 ID) */
|
||||
const addTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
if (value.includes(tagId)) return
|
||||
onChange([...value, tagId])
|
||||
setInputVal("")
|
||||
setShowSuggestions(false)
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
/** 输入自定义标签名:若已存在则直接选,否则创建新标签 */
|
||||
const addTagByName = useCallback(
|
||||
async (name: string) => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) return
|
||||
const existing = findTagByName(trimmed)
|
||||
if (existing) {
|
||||
addTagId(existing.id)
|
||||
} else {
|
||||
try {
|
||||
const created = await onCreateTag(trimmed)
|
||||
addTagId(created.id)
|
||||
} catch {
|
||||
/* 创建失败静默忽略 */
|
||||
}
|
||||
}
|
||||
},
|
||||
[findTagByName, addTagId, onCreateTag],
|
||||
)
|
||||
|
||||
const removeTagId = useCallback(
|
||||
(tagId: string) => {
|
||||
onChange(value.filter((t) => t !== tagId))
|
||||
},
|
||||
[value, onChange],
|
||||
)
|
||||
|
||||
/** 输入补全建议(排除已选) */
|
||||
const suggestions = useMemo(() => {
|
||||
if (!inputVal.trim()) return []
|
||||
const lower = inputVal.toLowerCase()
|
||||
return tags.filter((t) => t.name.toLowerCase().includes(lower) && !value.includes(t.id))
|
||||
}, [inputVal, tags, value])
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault()
|
||||
if (suggestions.length > 0) {
|
||||
addTagId(suggestions[0].id)
|
||||
} else {
|
||||
addTagByName(inputVal)
|
||||
}
|
||||
} else if (e.key === "Backspace" && !inputVal && value.length > 0) {
|
||||
removeTagId(value[value.length - 1])
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="vmat-tag-selector-wrapper">
|
||||
<div className="vmat-tag-selector" onClick={() => inputRef.current?.focus()}>
|
||||
{value.map((tagId) => (
|
||||
<Tag key={tagId} variant="info" closable onClose={() => removeTagId(tagId)}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
</Tag>
|
||||
))}
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="vmat-tag-selector-input"
|
||||
value={inputVal}
|
||||
onChange={(e) => {
|
||||
setInputVal(e.target.value)
|
||||
setShowSuggestions(true)
|
||||
}}
|
||||
onFocus={() => setShowSuggestions(true)}
|
||||
onBlur={() => setTimeout(() => setShowSuggestions(false), 150)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={value.length === 0 ? placeholder : ""}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 自动补全下拉 */}
|
||||
{showSuggestions && suggestions.length > 0 && (
|
||||
<div className="vmat-tag-suggestions">
|
||||
{suggestions.slice(0, 6).map((tag) => (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
className="vmat-tag-suggestion-item"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault()
|
||||
addTagId(tag.id)
|
||||
}}
|
||||
>
|
||||
{tag.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 已有标签快捷选择 */}
|
||||
{tags.length > 0 && (
|
||||
<div className="vmat-tag-selector-presets">
|
||||
{tags.map((tag) => {
|
||||
const isSelected = value.includes(tag.id)
|
||||
return (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
className={`vmat-tag-selector-preset${isSelected ? " selected" : ""}`}
|
||||
onClick={() => {
|
||||
if (isSelected) removeTagId(tag.id)
|
||||
else addTagId(tag.id)
|
||||
}}
|
||||
>
|
||||
{isSelected && <CheckOutlined style={{ fontSize: 10, marginRight: 2 }} />}
|
||||
{tag.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TagSelector
|
||||
@@ -0,0 +1,245 @@
|
||||
import React, { useRef } from "react"
|
||||
import {
|
||||
AudioOutlined,
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
EditOutlined,
|
||||
DeleteOutlined,
|
||||
CheckOutlined,
|
||||
SoundOutlined,
|
||||
MutedOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { Tooltip } from "antd"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { type VoiceMaterial } from "../types"
|
||||
import { MAX_CARD_TAGS, TAG_VARIANTS } from "../constants"
|
||||
import {
|
||||
genderClass,
|
||||
genderIcon,
|
||||
genderLabel,
|
||||
formatDuration,
|
||||
formatFileSize,
|
||||
formatDate,
|
||||
} from "../utils/format"
|
||||
|
||||
export interface VoiceCardProps {
|
||||
material: VoiceMaterial
|
||||
isPlaying: boolean
|
||||
currentTime: number
|
||||
isSelected: boolean
|
||||
batchMode: boolean
|
||||
volume: number
|
||||
tagMap: Map<string, TagItem>
|
||||
onPlay: () => void
|
||||
onPause: () => void
|
||||
onSeek: (time: number) => void
|
||||
onEdit: () => void
|
||||
onDelete: () => void
|
||||
onToggleSelect: (id: string) => void
|
||||
onVolumeChange: (e: React.ChangeEvent<HTMLInputElement>) => void
|
||||
onToggleMute: () => void
|
||||
}
|
||||
|
||||
const VoiceMaterialCard: React.FC<VoiceCardProps> = ({
|
||||
material,
|
||||
isPlaying,
|
||||
currentTime,
|
||||
isSelected,
|
||||
batchMode,
|
||||
volume,
|
||||
tagMap,
|
||||
onPlay,
|
||||
onPause,
|
||||
onSeek,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggleSelect,
|
||||
onVolumeChange,
|
||||
onToggleMute,
|
||||
}) => {
|
||||
const progressRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleProgressMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!progressRef.current) return
|
||||
e.preventDefault()
|
||||
const doSeek = (ev: MouseEvent) => {
|
||||
if (!progressRef.current) return
|
||||
const rect = progressRef.current.getBoundingClientRect()
|
||||
const percent = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width))
|
||||
onSeek(percent * material.duration)
|
||||
}
|
||||
doSeek(e.nativeEvent)
|
||||
const handleMove = (ev: MouseEvent) => doSeek(ev)
|
||||
const handleUp = () => {
|
||||
document.removeEventListener("mousemove", handleMove)
|
||||
document.removeEventListener("mouseup", handleUp)
|
||||
}
|
||||
document.addEventListener("mousemove", handleMove)
|
||||
document.addEventListener("mouseup", handleUp)
|
||||
}
|
||||
|
||||
const progress = material.duration > 0 ? (currentTime / material.duration) * 100 : 0
|
||||
|
||||
const handleCardClick = () => {
|
||||
if (batchMode) {
|
||||
onToggleSelect(material.id)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`vmat-card ${genderClass(material.gender)}${isPlaying ? " playing" : ""}${isSelected ? " selected" : ""}${batchMode ? " batch-mode" : ""}`}
|
||||
onClick={handleCardClick}
|
||||
>
|
||||
{/* 批量选择 checkbox */}
|
||||
{(batchMode || isSelected) && (
|
||||
<div
|
||||
className={`vmat-card-checkbox vmat-checkbox${isSelected ? " checked" : ""}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onToggleSelect(material.id)
|
||||
}}
|
||||
>
|
||||
{isSelected && <CheckOutlined />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className="vmat-card-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-card-action-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onEdit()
|
||||
}}
|
||||
title="编辑"
|
||||
>
|
||||
<EditOutlined />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-card-action-btn vmat-card-action-btn--danger"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete()
|
||||
}}
|
||||
title="删除"
|
||||
>
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 头部:图标 + 名称 + 性别 */}
|
||||
<div className="vmat-card-header">
|
||||
<div className="vmat-card-avatar">
|
||||
<AudioOutlined />
|
||||
</div>
|
||||
<div className="vmat-card-title-area">
|
||||
<h4 className="vmat-card-name" title={material.name}>
|
||||
{material.name}
|
||||
</h4>
|
||||
<span className={`vmat-card-gender ${genderClass(material.gender)}`}>
|
||||
{genderIcon(material.gender)}
|
||||
{genderLabel(material.gender)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 描述 */}
|
||||
{material.description && <p className="vmat-card-desc">{material.description}</p>}
|
||||
|
||||
{/* 标签 */}
|
||||
<div className="vmat-card-tags">
|
||||
{material.tagIds.length === 0 ? (
|
||||
<span
|
||||
className="vmat-tag-empty"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onEdit()
|
||||
}}
|
||||
>
|
||||
添加标签
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{material.tagIds.slice(0, MAX_CARD_TAGS).map((tagId, i) => (
|
||||
<Tag key={tagId} variant={TAG_VARIANTS[i % TAG_VARIANTS.length]}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
</Tag>
|
||||
))}
|
||||
{material.tagIds.length > MAX_CARD_TAGS && (
|
||||
<Tooltip
|
||||
title={material.tagIds
|
||||
.slice(MAX_CARD_TAGS)
|
||||
.map((id) => tagMap.get(id)?.name ?? id)
|
||||
.join("、")}
|
||||
>
|
||||
<Tag className="vmat-tag-overflow">+{material.tagIds.length - MAX_CARD_TAGS}</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 元信息 */}
|
||||
<div className="vmat-card-meta">
|
||||
<span>{formatDuration(material.duration)}</span>
|
||||
<span>{formatFileSize(material.fileSize)}</span>
|
||||
<span>{formatDate(material.createdAt)}</span>
|
||||
</div>
|
||||
|
||||
{/* 播放控制 */}
|
||||
<div className="vmat-card-player">
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-play-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
isPlaying ? onPause() : onPlay()
|
||||
}}
|
||||
disabled={!material.fileUrl}
|
||||
>
|
||||
{isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
|
||||
</button>
|
||||
<div ref={progressRef} className="vmat-progress" onMouseDown={handleProgressMouseDown}>
|
||||
<div className="vmat-progress-bar" style={{ width: `${progress}%` }} />
|
||||
{isPlaying && <div className="vmat-progress-thumb" style={{ left: `${progress}%` }} />}
|
||||
</div>
|
||||
<span className="vmat-time">
|
||||
{isPlaying ? formatDuration(currentTime) : formatDuration(material.duration)}
|
||||
</span>
|
||||
{/* 音量控制 */}
|
||||
<div className="vmat-volume">
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-volume-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onToggleMute()
|
||||
}}
|
||||
title={volume === 0 ? "取消静音" : "静音"}
|
||||
>
|
||||
{volume === 0 ? <MutedOutlined /> : <SoundOutlined />}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
className="vmat-volume-slider"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={volume}
|
||||
onChange={(e) => {
|
||||
e.stopPropagation()
|
||||
onVolumeChange(e)
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceMaterialCard
|
||||
@@ -0,0 +1,186 @@
|
||||
import React, { useRef } from "react"
|
||||
import {
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
EditOutlined,
|
||||
DeleteOutlined,
|
||||
CheckOutlined,
|
||||
} from "@ant-design/icons"
|
||||
import { Tooltip } from "antd"
|
||||
import { Tag } from "@/components/ui"
|
||||
import { type TagItem } from "@/api/tags"
|
||||
import { type VoiceMaterial } from "../types"
|
||||
import { MAX_ROW_TAGS, TAG_VARIANTS } from "../constants"
|
||||
import {
|
||||
genderClass,
|
||||
genderIcon,
|
||||
genderLabel,
|
||||
formatDuration,
|
||||
formatFileSize,
|
||||
} from "../utils/format"
|
||||
|
||||
export interface VoiceRowProps {
|
||||
material: VoiceMaterial
|
||||
isPlaying: boolean
|
||||
currentTime: number
|
||||
isSelected: boolean
|
||||
batchMode: boolean
|
||||
tagMap: Map<string, TagItem>
|
||||
onPlay: () => void
|
||||
onPause: () => void
|
||||
onSeek: (time: number) => void
|
||||
onEdit: () => void
|
||||
onDelete: () => void
|
||||
onToggleSelect: (id: string) => void
|
||||
}
|
||||
|
||||
const VoiceMaterialRow: React.FC<VoiceRowProps> = ({
|
||||
material,
|
||||
isPlaying,
|
||||
currentTime,
|
||||
isSelected,
|
||||
batchMode,
|
||||
tagMap,
|
||||
onPlay,
|
||||
onPause,
|
||||
onSeek,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggleSelect,
|
||||
}) => {
|
||||
const progressRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleProgressMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!progressRef.current) return
|
||||
e.preventDefault()
|
||||
const doSeek = (ev: MouseEvent) => {
|
||||
if (!progressRef.current) return
|
||||
const rect = progressRef.current.getBoundingClientRect()
|
||||
const percent = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width))
|
||||
onSeek(percent * material.duration)
|
||||
}
|
||||
doSeek(e.nativeEvent)
|
||||
const handleMove = (ev: MouseEvent) => doSeek(ev)
|
||||
const handleUp = () => {
|
||||
document.removeEventListener("mousemove", handleMove)
|
||||
document.removeEventListener("mouseup", handleUp)
|
||||
}
|
||||
document.addEventListener("mousemove", handleMove)
|
||||
document.addEventListener("mouseup", handleUp)
|
||||
}
|
||||
|
||||
const progress = material.duration > 0 ? (currentTime / material.duration) * 100 : 0
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`vmat-row ${genderClass(material.gender)}${isPlaying ? " playing" : ""}${isSelected ? " selected" : ""}${batchMode ? " batch-mode" : ""}`}
|
||||
>
|
||||
{/* 批量选择 checkbox */}
|
||||
{(batchMode || isSelected) && (
|
||||
<div
|
||||
className={`vmat-row-checkbox vmat-checkbox${isSelected ? " checked" : ""}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onToggleSelect(material.id)
|
||||
}}
|
||||
>
|
||||
{isSelected && <CheckOutlined />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 播放按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-row-play"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
isPlaying ? onPause() : onPlay()
|
||||
}}
|
||||
disabled={!material.fileUrl}
|
||||
>
|
||||
{isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
|
||||
</button>
|
||||
|
||||
{/* 名称 + 描述 */}
|
||||
<div className="vmat-row-info">
|
||||
<h4 className="vmat-row-name">{material.name}</h4>
|
||||
{material.description && <p className="vmat-row-desc">{material.description}</p>}
|
||||
</div>
|
||||
|
||||
{/* 性别 */}
|
||||
<span className={`vmat-row-gender ${genderClass(material.gender)}`}>
|
||||
{genderIcon(material.gender)}
|
||||
{genderLabel(material.gender)}
|
||||
</span>
|
||||
|
||||
{/* 标签 */}
|
||||
<div className="vmat-row-tags">
|
||||
{material.tagIds.length === 0 ? (
|
||||
<span className="vmat-tag-empty" onClick={() => onEdit()}>
|
||||
添加标签
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{material.tagIds.slice(0, MAX_ROW_TAGS).map((tagId, i) => (
|
||||
<Tag key={tagId} variant={TAG_VARIANTS[i % TAG_VARIANTS.length]}>
|
||||
{tagMap.get(tagId)?.name ?? tagId}
|
||||
</Tag>
|
||||
))}
|
||||
{material.tagIds.length > MAX_ROW_TAGS && (
|
||||
<Tooltip
|
||||
title={material.tagIds
|
||||
.slice(MAX_ROW_TAGS)
|
||||
.map((id) => tagMap.get(id)?.name ?? id)
|
||||
.join("、")}
|
||||
>
|
||||
<Tag className="vmat-tag-overflow">+{material.tagIds.length - MAX_ROW_TAGS}</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 进度条(可拖拽) */}
|
||||
<div ref={progressRef} className="vmat-row-progress" onMouseDown={handleProgressMouseDown}>
|
||||
<div className="vmat-row-progress-bar" style={{ width: `${progress}%` }} />
|
||||
{isPlaying && <div className="vmat-progress-thumb" style={{ left: `${progress}%` }} />}
|
||||
</div>
|
||||
|
||||
{/* 时长 */}
|
||||
<span className="vmat-row-time">
|
||||
{isPlaying ? formatDuration(currentTime) : formatDuration(material.duration)}
|
||||
</span>
|
||||
|
||||
{/* 文件大小 */}
|
||||
<span className="vmat-row-size">{formatFileSize(material.fileSize)}</span>
|
||||
|
||||
{/* 操作 */}
|
||||
<div className="vmat-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-row-action-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onEdit()
|
||||
}}
|
||||
title="编辑"
|
||||
>
|
||||
<EditOutlined />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="vmat-row-action-btn vmat-row-action-btn--danger"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDelete()
|
||||
}}
|
||||
title="删除"
|
||||
>
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VoiceMaterialRow
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* 配音素材库常量
|
||||
*/
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import React from "react"
|
||||
import { ManOutlined, WomanOutlined, UserOutlined, SoundOutlined } from "@ant-design/icons"
|
||||
import type { VoiceGender } from "./types"
|
||||
|
||||
/** 标签溢出限制 */
|
||||
export const MAX_CARD_TAGS = 3
|
||||
export const MAX_ROW_TAGS = 2
|
||||
export const TAG_VARIANTS = ["info", "primary", "success", "warning", "error"] as const
|
||||
|
||||
/** 性别选项 */
|
||||
export const GENDER_OPTIONS: {
|
||||
value: VoiceGender
|
||||
label: string
|
||||
icon: React.ReactNode
|
||||
}[] = [
|
||||
{ value: "male", label: "男声", icon: <ManOutlined /> },
|
||||
{ value: "female", label: "女声", icon: <WomanOutlined /> },
|
||||
{ value: "child", label: "童声", icon: <UserOutlined /> },
|
||||
{ value: "neutral", label: "中性", icon: <SoundOutlined /> },
|
||||
]
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useState, useRef, useCallback, useEffect } from "react"
|
||||
import type { VoiceMaterial } from "../types"
|
||||
|
||||
/**
|
||||
* 音频播放控制 Hook
|
||||
* 封装当前播放音频状态、播放/暂停、进度控制、音量控制
|
||||
*/
|
||||
export function useAudioPlayer() {
|
||||
const [playingId, setPlayingId] = useState<string | null>(null)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [volume, setVolume] = useState(0.7)
|
||||
const [pausedMaterial, setPausedMaterial] = useState<VoiceMaterial | null>(null)
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
|
||||
/** 停止当前播放并重置状态 */
|
||||
const stopPlayback = useCallback(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause()
|
||||
audioRef.current = null
|
||||
}
|
||||
setPlayingId(null)
|
||||
setCurrentTime(0)
|
||||
setPausedMaterial(null)
|
||||
}, [])
|
||||
|
||||
/** 从头开始播放指定素材 */
|
||||
const startPlayback = useCallback(
|
||||
(material: VoiceMaterial) => {
|
||||
if (!material.fileUrl) return
|
||||
stopPlayback()
|
||||
|
||||
const audio = new Audio(material.fileUrl)
|
||||
audio.volume = volume
|
||||
audioRef.current = audio
|
||||
|
||||
audio.addEventListener("timeupdate", () => {
|
||||
setCurrentTime(audio.currentTime)
|
||||
})
|
||||
|
||||
audio.addEventListener("ended", () => {
|
||||
setPlayingId(null)
|
||||
setCurrentTime(0)
|
||||
audioRef.current = null
|
||||
setPausedMaterial(null)
|
||||
})
|
||||
|
||||
audio.play().catch(() => {
|
||||
audioRef.current = null
|
||||
setPlayingId(null)
|
||||
})
|
||||
|
||||
setPlayingId(material.id)
|
||||
setCurrentTime(0)
|
||||
setPausedMaterial(null)
|
||||
},
|
||||
[stopPlayback, volume],
|
||||
)
|
||||
|
||||
/** 播放素材(若为暂停状态则恢复) */
|
||||
const handlePlay = useCallback(
|
||||
(material: VoiceMaterial) => {
|
||||
if (playingId === material.id) return
|
||||
// 恢复暂停
|
||||
if (pausedMaterial?.id === material.id && audioRef.current && audioRef.current.paused) {
|
||||
audioRef.current.play().catch(() => {})
|
||||
setPlayingId(material.id)
|
||||
setPausedMaterial(null)
|
||||
return
|
||||
}
|
||||
startPlayback(material)
|
||||
},
|
||||
[playingId, pausedMaterial, startPlayback],
|
||||
)
|
||||
|
||||
/** 暂停播放 */
|
||||
const handlePause = useCallback((material?: VoiceMaterial) => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause()
|
||||
}
|
||||
setPlayingId(null)
|
||||
if (material) setPausedMaterial(material)
|
||||
}, [])
|
||||
|
||||
/** 跳转到指定播放时间 */
|
||||
const handleSeek = useCallback(
|
||||
(material: VoiceMaterial, time: number) => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = time
|
||||
setCurrentTime(time)
|
||||
} else {
|
||||
startPlayback(material)
|
||||
setTimeout(() => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = time
|
||||
}
|
||||
}, 100)
|
||||
}
|
||||
},
|
||||
[startPlayback],
|
||||
)
|
||||
|
||||
/** 音量调节 */
|
||||
const handleVolumeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const v = parseFloat(e.target.value)
|
||||
setVolume(v)
|
||||
if (audioRef.current) audioRef.current.volume = v
|
||||
}, [])
|
||||
|
||||
/** 静音/取消静音切换 */
|
||||
const toggleMute = useCallback(() => {
|
||||
if (volume > 0) {
|
||||
setVolume(0)
|
||||
if (audioRef.current) audioRef.current.volume = 0
|
||||
} else {
|
||||
setVolume(0.7)
|
||||
if (audioRef.current) audioRef.current.volume = 0.7
|
||||
}
|
||||
}, [volume])
|
||||
|
||||
// 组件卸载时清理 audio
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause()
|
||||
audioRef.current = null
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return {
|
||||
playingId,
|
||||
currentTime,
|
||||
volume,
|
||||
pausedMaterial,
|
||||
stopPlayback,
|
||||
handlePlay,
|
||||
handlePause,
|
||||
handleSeek,
|
||||
handleVolumeChange,
|
||||
toggleMute,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState, useCallback, useMemo } from "react"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { message } from "antd"
|
||||
import { deleteAsset } from "@/api/assets"
|
||||
import { type TagItem, createTag, tagAsset } from "@/api/tags"
|
||||
import type { VoiceMaterial } from "../types"
|
||||
|
||||
/**
|
||||
* 批量操作 Hook
|
||||
* 封装批量选择、批量删除、批量打标签等逻辑
|
||||
*/
|
||||
interface UseBatchOperationsProps {
|
||||
/** 当前筛选后的素材列表 */
|
||||
filtered: VoiceMaterial[]
|
||||
/** 标签 ID → TagItem 映射 */
|
||||
tagMap: Map<string, TagItem>
|
||||
/** 所有可用标签 */
|
||||
tags: TagItem[]
|
||||
/** 当前播放中的素材 ID */
|
||||
playingId: string | null
|
||||
/** 停止播放回调 */
|
||||
stopPlayback: () => void
|
||||
}
|
||||
|
||||
export function useBatchOperations({
|
||||
filtered,
|
||||
tagMap,
|
||||
tags,
|
||||
playingId,
|
||||
stopPlayback,
|
||||
}: UseBatchOperationsProps) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
|
||||
const [batchCustomTag, setBatchCustomTag] = useState("")
|
||||
|
||||
const batchMode = useMemo(() => selectedIds.size > 0, [selectedIds])
|
||||
const allSelected = useMemo(
|
||||
() => filtered.length > 0 && filtered.every((m) => selectedIds.has(m.id)),
|
||||
[filtered, selectedIds],
|
||||
)
|
||||
|
||||
/** 切换单个素材的选中状态 */
|
||||
const handleToggleSelect = useCallback((id: string) => {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
/** 全选 / 取消全选 */
|
||||
const handleSelectAll = useCallback(() => {
|
||||
if (allSelected) setSelectedIds(new Set())
|
||||
else setSelectedIds(new Set(filtered.map((m) => m.id)))
|
||||
}, [allSelected, filtered])
|
||||
|
||||
/** 批量删除 */
|
||||
const handleBatchDelete = useCallback(async () => {
|
||||
const ids = Array.from(selectedIds)
|
||||
let successCount = 0
|
||||
for (const id of ids) {
|
||||
try {
|
||||
await deleteAsset(id)
|
||||
successCount++
|
||||
} catch {
|
||||
/* ignore individual failures */
|
||||
}
|
||||
if (playingId === id) stopPlayback()
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
setSelectedIds(new Set())
|
||||
message.success(`已批量删除 ${successCount}/${ids.length} 个素材`)
|
||||
}, [selectedIds, playingId, stopPlayback, queryClient])
|
||||
|
||||
/** 批量打标签(已有标签) */
|
||||
const handleBatchTag = useCallback(
|
||||
async (tagId: string) => {
|
||||
const ids = Array.from(selectedIds)
|
||||
let successCount = 0
|
||||
for (const id of ids) {
|
||||
try {
|
||||
await tagAsset(id, [tagId])
|
||||
successCount++
|
||||
} catch {
|
||||
/* ignore individual failures */
|
||||
}
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
setSelectedIds(new Set())
|
||||
const tagName = tagMap.get(tagId)?.name ?? tagId
|
||||
if (successCount === 0) {
|
||||
message.error(`批量打标签失败,请重试`)
|
||||
} else {
|
||||
message.success(`已为 ${successCount}/${ids.length} 个素材添加标签「${tagName}」`)
|
||||
}
|
||||
},
|
||||
[selectedIds, queryClient, tagMap],
|
||||
)
|
||||
|
||||
/** 批量打标签(自定义输入:按名称查找或创建标签,再批量打标) */
|
||||
const handleBatchCustomTag = useCallback(
|
||||
async (name: string) => {
|
||||
// 先查找同名标签(不区分大小写)
|
||||
let existing = tags.find((t) => t.name.toLowerCase() === name.toLowerCase())
|
||||
if (!existing) {
|
||||
try {
|
||||
existing = await createTag(name)
|
||||
} catch {
|
||||
message.error(`创建标签「${name}」失败`)
|
||||
return
|
||||
}
|
||||
}
|
||||
await handleBatchTag(existing.id)
|
||||
},
|
||||
[tags, handleBatchTag],
|
||||
)
|
||||
|
||||
return {
|
||||
selectedIds,
|
||||
batchMode,
|
||||
allSelected,
|
||||
batchCustomTag,
|
||||
setBatchCustomTag,
|
||||
handleToggleSelect,
|
||||
handleSelectAll,
|
||||
handleBatchDelete,
|
||||
handleBatchTag,
|
||||
handleBatchCustomTag,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { useState, useRef, useCallback, useEffect } from "react"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { message } from "antd"
|
||||
import { synthesizeSpeech, getTTSJobStatus, saveTtsToLibrary } from "@/api/tts"
|
||||
import { fetchPresetVoices, type PresetVoiceItem } from "@/api/voices"
|
||||
|
||||
/**
|
||||
* TTS 合成 Hook
|
||||
* 封装合成弹窗状态、合成请求、轮询、保存到素材库等逻辑
|
||||
*/
|
||||
export type TtsStatus = "idle" | "synthesizing" | "done" | "error"
|
||||
|
||||
export function useTtsSynthesize() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [ttsOpen, setTtsOpen] = useState(false)
|
||||
const [ttsText, setTtsText] = useState("")
|
||||
const [ttsVoiceId, setTtsVoiceId] = useState<string>("")
|
||||
const [ttsSpeed, setTtsSpeed] = useState(1.0)
|
||||
const [ttsJobId, setTtsJobId] = useState<string | null>(null)
|
||||
const [ttsStatus, setTtsStatus] = useState<TtsStatus>("idle")
|
||||
const [ttsAudioUrl, setTtsAudioUrl] = useState<string | null>(null)
|
||||
const [ttsError, setTtsError] = useState<string | null>(null)
|
||||
const ttsTimerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
// 预设音色列表
|
||||
const { data: presetVoicesData } = useQuery({
|
||||
queryKey: ["preset-voices"],
|
||||
queryFn: fetchPresetVoices,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
const presetVoices: PresetVoiceItem[] = presetVoicesData?.items ?? []
|
||||
|
||||
/** 开始 AI 配音合成 */
|
||||
const handleTtsSynthesize = useCallback(async () => {
|
||||
if (!ttsText.trim()) {
|
||||
message.warning("请输入要合成的文本")
|
||||
return
|
||||
}
|
||||
setTtsError(null)
|
||||
setTtsStatus("synthesizing")
|
||||
setTtsAudioUrl(null)
|
||||
setTtsJobId(null)
|
||||
|
||||
try {
|
||||
const resp = await synthesizeSpeech({
|
||||
text: ttsText.trim(),
|
||||
voice_id: ttsVoiceId || undefined,
|
||||
speed: ttsSpeed,
|
||||
})
|
||||
setTtsJobId(resp.job_id)
|
||||
|
||||
// 轮询任务状态
|
||||
ttsTimerRef.current = setInterval(async () => {
|
||||
try {
|
||||
const job = await getTTSJobStatus(resp.job_id)
|
||||
if (job.status === "completed") {
|
||||
clearInterval(ttsTimerRef.current!)
|
||||
ttsTimerRef.current = null
|
||||
setTtsStatus("done")
|
||||
setTtsAudioUrl(job.output_audio_url)
|
||||
} else if (job.status === "failed") {
|
||||
clearInterval(ttsTimerRef.current!)
|
||||
ttsTimerRef.current = null
|
||||
setTtsStatus("error")
|
||||
setTtsError(job.error_message || "合成失败")
|
||||
}
|
||||
} catch {
|
||||
clearInterval(ttsTimerRef.current!)
|
||||
ttsTimerRef.current = null
|
||||
setTtsStatus("error")
|
||||
setTtsError("查询合成状态失败")
|
||||
}
|
||||
}, 2000)
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : "合成请求失败"
|
||||
setTtsStatus("error")
|
||||
setTtsError(msg)
|
||||
}
|
||||
}, [ttsText, ttsVoiceId, ttsSpeed])
|
||||
|
||||
/** 保存 TTS 结果到素材库 */
|
||||
const handleTtsSave = useCallback(async () => {
|
||||
if (!ttsJobId) return
|
||||
try {
|
||||
await saveTtsToLibrary(ttsJobId, {
|
||||
name: ttsText.slice(0, 20) || "AI配音",
|
||||
})
|
||||
message.success("已保存到配音库")
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
setTtsOpen(false)
|
||||
} catch {
|
||||
message.error("保存失败")
|
||||
}
|
||||
}, [ttsJobId, ttsText, queryClient])
|
||||
|
||||
/** 关闭 TTS 弹窗并清理状态 */
|
||||
const handleTtsClose = useCallback(() => {
|
||||
setTtsOpen(false)
|
||||
if (ttsTimerRef.current) {
|
||||
clearInterval(ttsTimerRef.current)
|
||||
ttsTimerRef.current = null
|
||||
}
|
||||
setTtsStatus("idle")
|
||||
setTtsAudioUrl(null)
|
||||
setTtsError(null)
|
||||
setTtsJobId(null)
|
||||
}, [])
|
||||
|
||||
// 组件卸载时清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (ttsTimerRef.current) clearInterval(ttsTimerRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return {
|
||||
ttsOpen,
|
||||
ttsText,
|
||||
ttsVoiceId,
|
||||
ttsSpeed,
|
||||
ttsJobId,
|
||||
ttsStatus,
|
||||
ttsAudioUrl,
|
||||
ttsError,
|
||||
presetVoices,
|
||||
setTtsOpen,
|
||||
setTtsText,
|
||||
setTtsVoiceId,
|
||||
setTtsSpeed,
|
||||
handleTtsSynthesize,
|
||||
handleTtsSave,
|
||||
handleTtsClose,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import { useState, useMemo, useCallback, useEffect } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { message } from "antd"
|
||||
import {
|
||||
getAssetsByKind,
|
||||
createAsset,
|
||||
updateAsset,
|
||||
deleteAsset,
|
||||
uploadAssetDirect,
|
||||
getAssetLibraries,
|
||||
createAssetLibrary,
|
||||
} from "@/api/assets"
|
||||
import { type TagItem, getTags, createTag, tagAsset, untagAsset } from "@/api/tags"
|
||||
import {
|
||||
type VoiceGender,
|
||||
type ViewMode,
|
||||
type VoiceMaterial,
|
||||
mapAssetToMaterial,
|
||||
buildMetadata,
|
||||
} from "../types"
|
||||
import { getAudioDuration } from "../utils/audio"
|
||||
|
||||
/**
|
||||
* 配音素材数据 Hook
|
||||
* 封装素材列表查询、筛选状态管理、增删改等数据操作逻辑
|
||||
*/
|
||||
export function useVoiceMaterials() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// ── 获取 voice 类型素材库(用于上传) ──────────────────────
|
||||
const { data: libraries = [] } = useQuery({
|
||||
queryKey: ["asset-libraries"],
|
||||
queryFn: getAssetLibraries,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const voiceLibrary = useMemo(() => libraries.find((lib) => lib.kind === "voice"), [libraries])
|
||||
|
||||
// 自动创建 voice 素材库(如果不存在)
|
||||
const createLibMutation = useMutation({
|
||||
mutationFn: () => createAssetLibrary({ name: "配音库", kind: "voice" }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["asset-libraries"] })
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (libraries.length > 0 && !voiceLibrary && !createLibMutation.isPending) {
|
||||
createLibMutation.mutate()
|
||||
}
|
||||
}, [libraries, voiceLibrary, createLibMutation])
|
||||
|
||||
// ── 获取标签列表 ───────────────────────────────────────────
|
||||
const { data: tags = [] } = useQuery({
|
||||
queryKey: ["tags"],
|
||||
queryFn: getTags,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
/** 标签 ID → TagItem 映射(用于卡片/行渲染) */
|
||||
const tagMap = useMemo(() => {
|
||||
const m = new Map<string, TagItem>()
|
||||
tags.forEach((t) => m.set(t.id, t))
|
||||
return m
|
||||
}, [tags])
|
||||
|
||||
/** 创建标签 mutation(供 TagSelector 调用) */
|
||||
const createTagMutation = useMutation({
|
||||
mutationFn: (name: string) => createTag(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["tags"] })
|
||||
},
|
||||
})
|
||||
|
||||
/** 创建标签并返回 TagItem(供 TagSelector 使用) */
|
||||
const handleCreateTag = useCallback(
|
||||
async (name: string): Promise<TagItem> => {
|
||||
return createTagMutation.mutateAsync(name)
|
||||
},
|
||||
[createTagMutation],
|
||||
)
|
||||
|
||||
// ── 视图 & 筛选状态 ────────────────────────────────────────
|
||||
const [viewMode, setViewMode] = useState<ViewMode>("card")
|
||||
const [searchText, setSearchText] = useState("")
|
||||
const [filterGender, setFilterGender] = useState<string>("all")
|
||||
const [filterTagId, setFilterTagId] = useState<string>("all")
|
||||
|
||||
// ── 获取配音素材列表(筛选参数透传后端) ─────────────────
|
||||
const filterKeyword = searchText.trim() || undefined
|
||||
const filterGenderParam = filterGender !== "all" ? filterGender : undefined
|
||||
const filterTagIdsParam = filterTagId !== "all" ? [filterTagId] : undefined
|
||||
|
||||
const { data: assets = [], isLoading } = useQuery({
|
||||
queryKey: [
|
||||
"assets",
|
||||
"voice",
|
||||
{
|
||||
keyword: filterKeyword,
|
||||
gender: filterGenderParam,
|
||||
tag_ids: filterTagIdsParam,
|
||||
},
|
||||
],
|
||||
queryFn: () =>
|
||||
getAssetsByKind("voice", {
|
||||
keyword: filterKeyword,
|
||||
gender: filterGenderParam,
|
||||
tag_ids: filterTagIdsParam,
|
||||
}),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const materials: VoiceMaterial[] = useMemo(() => assets.map(mapAssetToMaterial), [assets])
|
||||
|
||||
// ── 弹窗状态 ──────────────────────────────────────────────
|
||||
const [uploadOpen, setUploadOpen] = useState(false)
|
||||
const [editingMaterial, setEditingMaterial] = useState<VoiceMaterial | null>(null)
|
||||
|
||||
// ── 上传进度 ──────────────────────────────────────────────
|
||||
const [uploadProgress, setUploadProgress] = useState<number | null>(null)
|
||||
|
||||
// ── 上传 mutation ─────────────────────────────────────────
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: async (data: {
|
||||
file: File
|
||||
name: string
|
||||
gender: VoiceGender
|
||||
description: string
|
||||
tagIds: string[]
|
||||
}) => {
|
||||
setUploadProgress(0)
|
||||
try {
|
||||
// 1. 获取或等待 voice library
|
||||
let lib = voiceLibrary
|
||||
if (!lib) {
|
||||
if (createLibMutation.isPending) {
|
||||
await createLibMutation.mutateAsync()
|
||||
}
|
||||
const libs = await queryClient.fetchQuery({
|
||||
queryKey: ["asset-libraries"],
|
||||
queryFn: getAssetLibraries,
|
||||
})
|
||||
lib = libs.find((l) => l.kind === "voice")
|
||||
if (!lib) throw new Error("无法创建配音库")
|
||||
}
|
||||
|
||||
// 2. 上传文件(带进度)
|
||||
const { storage_key } = await uploadAssetDirect({
|
||||
file: data.file,
|
||||
library_id: lib.id,
|
||||
onProgress: (p) => setUploadProgress(p),
|
||||
})
|
||||
|
||||
// 3. 获取音频时长
|
||||
const duration = await getAudioDuration(data.file)
|
||||
|
||||
// 4. 创建素材记录
|
||||
const asset = await createAsset({
|
||||
library_id: lib.id,
|
||||
name: data.name,
|
||||
storage_key,
|
||||
mime_type: data.file.type || "audio/mpeg",
|
||||
metadata: buildMetadata({
|
||||
gender: data.gender,
|
||||
description: data.description,
|
||||
duration,
|
||||
}),
|
||||
})
|
||||
|
||||
// 5. 打标签(标签走独立 API)
|
||||
if (data.tagIds.length > 0) {
|
||||
await tagAsset(asset.id, data.tagIds)
|
||||
}
|
||||
} finally {
|
||||
setUploadProgress(null)
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["tags"] })
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
message.error(err.message || "上传失败,请重试")
|
||||
},
|
||||
})
|
||||
|
||||
// ── 编辑 mutation ─────────────────────────────────────────
|
||||
const editMutation = useMutation({
|
||||
mutationFn: async (data: {
|
||||
id: string
|
||||
name: string
|
||||
gender: VoiceGender
|
||||
description: string
|
||||
tagIds: string[]
|
||||
}) => {
|
||||
// 1. 更新基础信息
|
||||
await updateAsset(data.id, {
|
||||
name: data.name,
|
||||
metadata: buildMetadata({
|
||||
gender: data.gender,
|
||||
description: data.description,
|
||||
}),
|
||||
})
|
||||
|
||||
// 2. 对比标签差异,调用 tag/untag API
|
||||
const currentAsset = materials.find((m) => m.id === data.id)
|
||||
const oldTagIds = currentAsset?.tagIds ?? []
|
||||
const newTagIds = data.tagIds
|
||||
|
||||
const toAdd = newTagIds.filter((id) => !oldTagIds.includes(id))
|
||||
const toRemove = oldTagIds.filter((id) => !newTagIds.includes(id))
|
||||
|
||||
if (toAdd.length > 0) {
|
||||
await tagAsset(data.id, toAdd)
|
||||
}
|
||||
for (const tagId of toRemove) {
|
||||
await untagAsset(data.id, tagId)
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["tags"] })
|
||||
},
|
||||
})
|
||||
|
||||
// ── 删除 mutation ─────────────────────────────────────────
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (assetId: string) => deleteAsset(assetId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["assets", "voice"] })
|
||||
},
|
||||
})
|
||||
|
||||
/* ── 前端二次筛选(与后端筛选同时存在) ──────────────────── */
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let list = materials
|
||||
if (filterGender !== "all") {
|
||||
list = list.filter((m) => m.gender === filterGender)
|
||||
}
|
||||
if (filterTagId !== "all") {
|
||||
list = list.filter((m) => m.tagIds.includes(filterTagId))
|
||||
}
|
||||
if (searchText.trim()) {
|
||||
const q = searchText.trim().toLowerCase()
|
||||
list = list.filter(
|
||||
(m) =>
|
||||
m.name.toLowerCase().includes(q) ||
|
||||
m.description.toLowerCase().includes(q) ||
|
||||
m.tagIds.some((id) => tagMap.get(id)?.name?.toLowerCase().includes(q)),
|
||||
)
|
||||
}
|
||||
return list
|
||||
}, [materials, filterGender, filterTagId, searchText, tagMap])
|
||||
|
||||
/* ── 标签使用计数(药丸条展示,按 tag ID 统计) ──────────── */
|
||||
|
||||
const tagCountMap = useMemo(() => {
|
||||
const map: Record<string, number> = {}
|
||||
materials.forEach((m) =>
|
||||
m.tagIds.forEach((id) => {
|
||||
map[id] = (map[id] || 0) + 1
|
||||
}),
|
||||
)
|
||||
return map
|
||||
}, [materials])
|
||||
|
||||
/* ── 数据操作 handlers ──────────────────────────────────── */
|
||||
|
||||
const handleUpload = useCallback(
|
||||
(data: Omit<VoiceMaterial, "id" | "createdAt"> & { file?: File }) => {
|
||||
if (!data.file) return
|
||||
uploadMutation.mutate(
|
||||
{
|
||||
file: data.file,
|
||||
name: data.name,
|
||||
gender: data.gender,
|
||||
description: data.description,
|
||||
tagIds: data.tagIds,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setUploadOpen(false)
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
[uploadMutation],
|
||||
)
|
||||
|
||||
const handleEdit = useCallback(
|
||||
(data: Omit<VoiceMaterial, "id" | "createdAt"> & { file?: File }) => {
|
||||
if (!editingMaterial) return
|
||||
editMutation.mutate({
|
||||
id: editingMaterial.id,
|
||||
name: data.name,
|
||||
gender: data.gender,
|
||||
description: data.description,
|
||||
tagIds: data.tagIds,
|
||||
})
|
||||
setEditingMaterial(null)
|
||||
},
|
||||
[editingMaterial, editMutation],
|
||||
)
|
||||
|
||||
const handleDelete = useCallback(
|
||||
(id: string, onBeforeDelete?: () => void) => {
|
||||
const material = materials.find((m) => m.id === id)
|
||||
if (!material) return
|
||||
if (onBeforeDelete) onBeforeDelete()
|
||||
deleteMutation.mutate(id)
|
||||
},
|
||||
[materials, deleteMutation],
|
||||
)
|
||||
|
||||
return {
|
||||
// 数据
|
||||
libraries,
|
||||
voiceLibrary,
|
||||
tags,
|
||||
tagMap,
|
||||
materials,
|
||||
filtered,
|
||||
tagCountMap,
|
||||
isLoading,
|
||||
// 视图 & 筛选状态
|
||||
viewMode,
|
||||
searchText,
|
||||
filterGender,
|
||||
filterTagId,
|
||||
// 上传 & 编辑状态
|
||||
uploadProgress,
|
||||
isUploading: uploadMutation.isPending,
|
||||
isEditing: editMutation.isPending,
|
||||
// 弹窗状态
|
||||
uploadOpen,
|
||||
editingMaterial,
|
||||
// 视图控制
|
||||
setViewMode,
|
||||
setSearchText,
|
||||
setFilterGender,
|
||||
setFilterTagId,
|
||||
setUploadOpen,
|
||||
setEditingMaterial,
|
||||
// 操作
|
||||
handleCreateTag,
|
||||
handleUpload,
|
||||
handleEdit,
|
||||
handleDelete,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 配音素材库类型定义
|
||||
*/
|
||||
import type { AssetItem } from "@/api/assets"
|
||||
|
||||
export type VoiceGender = "male" | "female" | "child" | "neutral"
|
||||
export type ViewMode = "card" | "list"
|
||||
|
||||
/** 前端配音素材数据模型(从 AssetItem 映射) */
|
||||
export interface VoiceMaterial {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
gender: VoiceGender
|
||||
tagIds: string[]
|
||||
fileName: string
|
||||
fileSize: number
|
||||
duration: number
|
||||
mimeType: string
|
||||
createdAt: string
|
||||
fileUrl?: string
|
||||
}
|
||||
|
||||
/** 配音素材上传元数据(传递给 createAsset 的 metadata) */
|
||||
export interface VoiceAssetMetadata {
|
||||
gender: VoiceGender
|
||||
description: string
|
||||
duration: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** 后端 AssetItem → 前端 VoiceMaterial */
|
||||
export const mapAssetToMaterial = (asset: AssetItem): VoiceMaterial => {
|
||||
const meta = asset.metadata || {}
|
||||
|
||||
return {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
description: (meta.description as string) || "",
|
||||
gender: (meta.gender as VoiceGender) || "neutral",
|
||||
tagIds: Array.isArray(asset.tag_ids) ? asset.tag_ids : [],
|
||||
fileName: asset.storage_key?.split("/").pop() || asset.name,
|
||||
fileSize: asset.file_size || 0,
|
||||
duration: (meta.duration as number) || 0,
|
||||
mimeType: asset.mime_type || "audio/mpeg",
|
||||
createdAt: asset.created_at || new Date().toISOString(),
|
||||
fileUrl: asset.file_url,
|
||||
}
|
||||
}
|
||||
|
||||
/** 前端表单数据 → 后端 metadata(标签走独立 API,不再写 metadata.style) */
|
||||
export const buildMetadata = (data: {
|
||||
gender: VoiceGender
|
||||
description: string
|
||||
duration?: number
|
||||
}): VoiceAssetMetadata => ({
|
||||
gender: data.gender,
|
||||
description: data.description,
|
||||
duration: data.duration || 0,
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 音频相关工具函数
|
||||
*/
|
||||
|
||||
/** 获取音频文件时长(秒) */
|
||||
export const getAudioDuration = (file: File): Promise<number> => {
|
||||
return new Promise((resolve) => {
|
||||
const audio = new Audio()
|
||||
const url = URL.createObjectURL(file)
|
||||
audio.addEventListener("loadedmetadata", () => {
|
||||
resolve(audio.duration)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.addEventListener("error", () => {
|
||||
resolve(0)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.src = url
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 格式化工具函数
|
||||
*/
|
||||
import { GENDER_OPTIONS } from "../constants"
|
||||
import type { VoiceGender } from "../types"
|
||||
|
||||
export const genderLabel = (g: VoiceGender) => GENDER_OPTIONS.find((o) => o.value === g)?.label ?? g
|
||||
|
||||
export const genderIcon = (g: VoiceGender) =>
|
||||
GENDER_OPTIONS.find((o) => o.value === g)?.icon ?? null
|
||||
|
||||
export const genderClass = (g: VoiceGender) => `vmat-gender--${g}`
|
||||
|
||||
export const formatDuration = (seconds: number): string => {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.floor(seconds % 60)
|
||||
return `${m}:${s.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
export const formatFileSize = (bytes: number): string => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
export const formatDate = (iso: string): string =>
|
||||
new Date(iso).toLocaleDateString("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
})
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
import { Modal, Upload, message } from "antd"
|
||||
import { Button, Input, Select, Tooltip } from "@/components/ui"
|
||||
import PageHead from "@/components/layout/PageHead"
|
||||
import { fetchPresetVoices, fetchVoices, type PresetVoiceItem } from "@/api/voices"
|
||||
import { fetchPresetVoices, fetchVoices } from "@/api/voices"
|
||||
import {
|
||||
getVoiceClonesWithTotal,
|
||||
deleteVoiceClone,
|
||||
@@ -43,111 +43,26 @@ import {
|
||||
getAssetLibraries,
|
||||
createAsset,
|
||||
} from "@/api/assets"
|
||||
import {
|
||||
type VoiceGender,
|
||||
type TabKey,
|
||||
type ClonedVoiceDisplay,
|
||||
mapPresetToDisplay,
|
||||
mapCloneToDisplay,
|
||||
buildVoiceMetadata,
|
||||
} from "@/pages/voices/types"
|
||||
import { CLONE_STATUS_CONFIG } from "@/pages/voices/constants"
|
||||
import {
|
||||
genderLabel,
|
||||
languageLabel,
|
||||
formatTime,
|
||||
genderClass,
|
||||
formatFileSize,
|
||||
} from "@/pages/voices/utils/format"
|
||||
import { getAudioDuration } from "@/pages/voices/utils/audio"
|
||||
import CloneModal from "@/components/voice/CloneModal"
|
||||
import "./voices.css"
|
||||
|
||||
/* ============================================================
|
||||
* 类型
|
||||
* ============================================================ */
|
||||
type VoiceGender = "male" | "female" | "child" | "elderly"
|
||||
type VoiceLanguage = "zh" | "en" | "ja" | "ko"
|
||||
type TabKey = "preset" | "cloned" | "material"
|
||||
|
||||
/** 前端展示用的预置音色(从 PresetVoiceItem 映射) */
|
||||
interface PresetVoiceDisplay {
|
||||
id: string
|
||||
name: string
|
||||
gender: VoiceGender
|
||||
language: VoiceLanguage
|
||||
duration: number
|
||||
tags: string[]
|
||||
description: string
|
||||
voiceId: string
|
||||
previewUrl: string
|
||||
starred: boolean
|
||||
}
|
||||
|
||||
/** 前端展示用的克隆音色(从 VoiceClone 映射) */
|
||||
interface ClonedVoiceDisplay {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
sourceName: string
|
||||
status: "ready" | "processing" | "failed"
|
||||
createdAt: string
|
||||
duration: number
|
||||
tags: string[]
|
||||
voiceId: string
|
||||
language: string
|
||||
gender: string
|
||||
errorMessage: string | null
|
||||
sampleUrl?: string
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
* 映射函数
|
||||
* ============================================================ */
|
||||
|
||||
const mapPresetToDisplay = (item: PresetVoiceItem): PresetVoiceDisplay => ({
|
||||
id: item.voice_id,
|
||||
name: item.name,
|
||||
gender: (item.gender as VoiceGender) || "female",
|
||||
language: (item.language as VoiceLanguage) || "zh",
|
||||
duration: 0,
|
||||
tags: item.tags,
|
||||
description: item.description,
|
||||
voiceId: item.voice_id,
|
||||
previewUrl: item.preview_url || "",
|
||||
starred: false,
|
||||
})
|
||||
|
||||
const mapCloneToDisplay = (clone: VoiceClone): ClonedVoiceDisplay => ({
|
||||
id: clone.id,
|
||||
name: clone.name,
|
||||
description: clone.description || "",
|
||||
sourceName: clone.sample_url || "未知来源",
|
||||
status: clone.status,
|
||||
createdAt: new Date(clone.created_at).toLocaleDateString("zh-CN"),
|
||||
duration: clone.duration_seconds,
|
||||
tags: [],
|
||||
voiceId: clone.id,
|
||||
language: clone.language || "",
|
||||
gender: clone.gender || "",
|
||||
errorMessage: clone.error_message || null,
|
||||
sampleUrl: clone.sample_url || undefined,
|
||||
})
|
||||
|
||||
/* ============================================================
|
||||
* 工具函数
|
||||
* ============================================================ */
|
||||
const genderLabel = (g: VoiceGender) => {
|
||||
const map: Record<VoiceGender, string> = {
|
||||
male: "男声",
|
||||
female: "女声",
|
||||
child: "童声",
|
||||
elderly: "老年",
|
||||
}
|
||||
return map[g]
|
||||
}
|
||||
|
||||
const languageLabel = (l: VoiceLanguage) => {
|
||||
const map: Record<VoiceLanguage, string> = {
|
||||
zh: "中文",
|
||||
en: "英文",
|
||||
ja: "日文",
|
||||
ko: "韩文",
|
||||
}
|
||||
return map[l]
|
||||
}
|
||||
|
||||
const formatTime = (seconds: number): string => {
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
const genderClass = (g: VoiceGender) => `xx-voice-gender--${g}`
|
||||
|
||||
/* ============================================================
|
||||
* VoiceCard 组件(预置音色 + 克隆音色统一)
|
||||
* ============================================================ */
|
||||
@@ -276,16 +191,6 @@ const VoiceCard: React.FC<VoiceCardProps> = ({
|
||||
* 克隆音色卡片组件(任务 3.12)
|
||||
* ============================================================ */
|
||||
|
||||
/** 状态配置 */
|
||||
const CLONE_STATUS_CONFIG: Record<
|
||||
ClonedVoiceDisplay["status"],
|
||||
{ label: string; className: string }
|
||||
> = {
|
||||
ready: { label: "可用", className: "xx-clone-status--ready" },
|
||||
processing: { label: "处理中", className: "xx-clone-status--processing" },
|
||||
failed: { label: "失败", className: "xx-clone-status--failed" },
|
||||
}
|
||||
|
||||
/** Toast 类型 */
|
||||
interface Toast {
|
||||
id: number
|
||||
@@ -554,49 +459,6 @@ const CloneCardSkeleton: React.FC = () => (
|
||||
</div>
|
||||
)
|
||||
|
||||
/* ── 辅助函数 ─────────────────────────────────────────── */
|
||||
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const getAudioDuration = (file: File): Promise<number> =>
|
||||
new Promise((resolve) => {
|
||||
const audio = new Audio()
|
||||
const url = URL.createObjectURL(file)
|
||||
audio.addEventListener("loadedmetadata", () => {
|
||||
resolve(audio.duration)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.addEventListener("error", () => {
|
||||
resolve(0)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.src = url
|
||||
})
|
||||
|
||||
/** 音色上传元数据(传递给 createAsset 的 metadata) */
|
||||
interface VoiceUploadMetadata {
|
||||
gender?: string
|
||||
description?: string
|
||||
duration?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
const buildVoiceMetadata = (data: {
|
||||
gender?: string
|
||||
description?: string
|
||||
duration?: number
|
||||
}): VoiceUploadMetadata => {
|
||||
const metadata: VoiceUploadMetadata = {}
|
||||
if (data.gender) metadata.gender = data.gender
|
||||
if (data.description) metadata.description = data.description
|
||||
if (data.duration) metadata.duration = Math.round(data.duration)
|
||||
return metadata
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
* 主组件
|
||||
* ============================================================ */
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 配音库常量
|
||||
*/
|
||||
import type { VoiceGender, VoiceLanguage, ClonedVoiceDisplay } from "./types"
|
||||
|
||||
/** 性别选项 */
|
||||
export const GENDER_OPTIONS: { value: VoiceGender; label: string }[] = [
|
||||
{ value: "male", label: "男声" },
|
||||
{ value: "female", label: "女声" },
|
||||
{ value: "child", label: "童声" },
|
||||
{ value: "elderly", label: "老年" },
|
||||
]
|
||||
|
||||
/** 语言选项 */
|
||||
export const LANGUAGE_OPTIONS: { value: VoiceLanguage; label: string }[] = [
|
||||
{ value: "zh", label: "中文" },
|
||||
{ value: "en", label: "英文" },
|
||||
{ value: "ja", label: "日文" },
|
||||
{ value: "ko", label: "韩文" },
|
||||
]
|
||||
|
||||
/** 克隆音色状态配置 */
|
||||
export const CLONE_STATUS_CONFIG: Record<
|
||||
ClonedVoiceDisplay["status"],
|
||||
{ label: string; className: string }
|
||||
> = {
|
||||
ready: { label: "可用", className: "xx-clone-status--ready" },
|
||||
processing: { label: "处理中", className: "xx-clone-status--processing" },
|
||||
failed: { label: "失败", className: "xx-clone-status--failed" },
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 配音库类型定义
|
||||
*/
|
||||
import type { PresetVoiceItem } from "@/api/voices"
|
||||
import type { VoiceClone } from "@/api/voice-clone"
|
||||
|
||||
export type VoiceGender = "male" | "female" | "child" | "elderly"
|
||||
export type VoiceLanguage = "zh" | "en" | "ja" | "ko"
|
||||
export type TabKey = "preset" | "cloned" | "material"
|
||||
|
||||
/** 前端展示用的预置音色(从 PresetVoiceItem 映射) */
|
||||
export interface PresetVoiceDisplay {
|
||||
id: string
|
||||
name: string
|
||||
gender: VoiceGender
|
||||
language: VoiceLanguage
|
||||
duration: number
|
||||
tags: string[]
|
||||
description: string
|
||||
voiceId: string
|
||||
previewUrl: string
|
||||
starred: boolean
|
||||
}
|
||||
|
||||
/** 前端展示用的克隆音色(从 VoiceClone 映射) */
|
||||
export interface ClonedVoiceDisplay {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
sourceName: string
|
||||
status: "ready" | "processing" | "failed"
|
||||
createdAt: string
|
||||
duration: number
|
||||
tags: string[]
|
||||
voiceId: string
|
||||
language: string
|
||||
gender: string
|
||||
errorMessage: string | null
|
||||
sampleUrl?: string
|
||||
}
|
||||
|
||||
/** 音色上传元数据(传递给 createAsset 的 metadata) */
|
||||
export interface VoiceUploadMetadata {
|
||||
gender?: string
|
||||
description?: string
|
||||
duration?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** 后端 PresetVoiceItem → 前端 PresetVoiceDisplay */
|
||||
export const mapPresetToDisplay = (item: PresetVoiceItem): PresetVoiceDisplay => ({
|
||||
id: item.voice_id,
|
||||
name: item.name,
|
||||
gender: (item.gender as VoiceGender) || "female",
|
||||
language: (item.language as VoiceLanguage) || "zh",
|
||||
duration: 0,
|
||||
tags: item.tags,
|
||||
description: item.description,
|
||||
voiceId: item.voice_id,
|
||||
previewUrl: item.preview_url || "",
|
||||
starred: false,
|
||||
})
|
||||
|
||||
/** 后端 VoiceClone → 前端 ClonedVoiceDisplay */
|
||||
export const mapCloneToDisplay = (clone: VoiceClone): ClonedVoiceDisplay => ({
|
||||
id: clone.id,
|
||||
name: clone.name,
|
||||
description: clone.description || "",
|
||||
sourceName: clone.sample_url || "未知来源",
|
||||
status: clone.status,
|
||||
createdAt: new Date(clone.created_at).toLocaleDateString("zh-CN"),
|
||||
duration: clone.duration_seconds,
|
||||
tags: [],
|
||||
voiceId: clone.id,
|
||||
language: clone.language || "",
|
||||
gender: clone.gender || "",
|
||||
errorMessage: clone.error_message || null,
|
||||
sampleUrl: clone.sample_url || undefined,
|
||||
})
|
||||
|
||||
/** 前端表单数据 → 后端 metadata */
|
||||
export const buildVoiceMetadata = (data: {
|
||||
gender?: string
|
||||
description?: string
|
||||
duration?: number
|
||||
}): VoiceUploadMetadata => {
|
||||
const metadata: VoiceUploadMetadata = {}
|
||||
if (data.gender) metadata.gender = data.gender
|
||||
if (data.description) metadata.description = data.description
|
||||
if (data.duration) metadata.duration = Math.round(data.duration)
|
||||
return metadata
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 音频相关工具函数
|
||||
*/
|
||||
|
||||
/** 获取音频文件时长(秒) */
|
||||
export const getAudioDuration = (file: File): Promise<number> => {
|
||||
return new Promise((resolve) => {
|
||||
const audio = new Audio()
|
||||
const url = URL.createObjectURL(file)
|
||||
audio.addEventListener("loadedmetadata", () => {
|
||||
resolve(audio.duration)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.addEventListener("error", () => {
|
||||
resolve(0)
|
||||
URL.revokeObjectURL(url)
|
||||
})
|
||||
audio.src = url
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* 格式化工具函数
|
||||
*/
|
||||
import { GENDER_OPTIONS, LANGUAGE_OPTIONS } from "../constants"
|
||||
import type { VoiceGender, VoiceLanguage } from "../types"
|
||||
|
||||
export const genderLabel = (g: VoiceGender) => GENDER_OPTIONS.find((o) => o.value === g)?.label ?? g
|
||||
|
||||
export const languageLabel = (l: VoiceLanguage) =>
|
||||
LANGUAGE_OPTIONS.find((o) => o.value === l)?.label ?? l
|
||||
|
||||
export const genderClass = (g: VoiceGender) => `xx-voice-gender--${g}`
|
||||
|
||||
export const formatTime = (seconds: number): string => {
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = Math.floor(seconds % 60)
|
||||
return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
export const formatFileSize = (bytes: number): string => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
/**
|
||||
* GenerateHeader 组件单元测试
|
||||
* 同时 import GeneratePage 主组件,确保 vitest related 模式
|
||||
* 能匹配到 generate 目录下所有文件的改动
|
||||
*/
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import { describe, it, expect } from "vitest"
|
||||
import GenerateHeader from "@/pages/generate/components/GenerateHeader"
|
||||
// 引入主组件以建立依赖链,让 vitest related 覆盖整个 generate 目录
|
||||
import "@/pages/generate/GeneratePage"
|
||||
|
||||
describe("GenerateHeader", () => {
|
||||
it("should render title and description", () => {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* GeneratePage 模块 smoke test
|
||||
* 建立完整依赖链,确保 vitest related 模式能匹配到
|
||||
* generate 目录下所有文件的改动(包括 Phase 3 子组件)
|
||||
*/
|
||||
import { describe, it, expect } from "vitest"
|
||||
|
||||
// 直接引入所有 Step 组件,建立完整依赖链
|
||||
import "@/pages/generate/GeneratePage"
|
||||
import "@/pages/generate/components/Step2MaterialSelect"
|
||||
import "@/pages/generate/components/Step4TitleSettings"
|
||||
import "@/pages/generate/components/Step5VoiceSelect"
|
||||
import "@/pages/generate/components/voice/VoiceRecommendSection"
|
||||
import "@/pages/generate/components/voice/VoiceChoiceCard"
|
||||
import "@/pages/generate/components/voice/PresetVoiceDetail"
|
||||
import "@/pages/generate/components/voice/CustomVoicePanel"
|
||||
import "@/pages/generate/components/voice/SaveVoiceModal"
|
||||
import "@/pages/generate/components/voice/CloneVoiceSection"
|
||||
import "@/pages/generate/components/material/MaterialModeTabs"
|
||||
import "@/pages/generate/components/material/ManualMaterialList"
|
||||
import "@/pages/generate/components/material/SmartMatchInput"
|
||||
import "@/pages/generate/components/material/SmartMatchResults"
|
||||
import "@/pages/generate/components/material/SmartMatchCard"
|
||||
import "@/pages/generate/components/title/AiTitleGenerator"
|
||||
import "@/pages/generate/components/title/AiTitleCard"
|
||||
import "@/pages/generate/components/title/TitleStylePanel"
|
||||
import "@/pages/generate/components/title/TitlePresetsGrid"
|
||||
import "@/pages/generate/utils/formatDuration"
|
||||
|
||||
describe("GeneratePage module smoke test", () => {
|
||||
it("should load all generate modules", () => {
|
||||
// 纯模块加载测试,确保所有组件/工具函数能正常 import
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* TagSelector 组件单元测试
|
||||
* 同时 import VoiceMaterialLibrary 主组件,确保 vitest related 模式
|
||||
* 能匹配到 voice-materials 目录下所有文件的改动
|
||||
*/
|
||||
import { render, screen, fireEvent, within } from "@testing-library/react"
|
||||
import { describe, it, expect, vi } from "vitest"
|
||||
import TagSelector from "@/pages/voice-materials/components/TagSelector"
|
||||
// 引入主组件以建立依赖链,让 vitest related 覆盖整个 voice-materials 目录
|
||||
import "@/pages/voice-materials/VoiceMaterialLibrary"
|
||||
import type { TagItem } from "@/api/tags"
|
||||
|
||||
const mockTags: TagItem[] = [
|
||||
{ id: "tag-1", name: "搞笑" },
|
||||
{ id: "tag-2", name: "情感" },
|
||||
{ id: "tag-3", name: "励志" },
|
||||
]
|
||||
|
||||
const mockTagMap = new Map(mockTags.map((t) => [t.id, t]))
|
||||
|
||||
describe("TagSelector", () => {
|
||||
const defaultProps = {
|
||||
value: [],
|
||||
onChange: vi.fn(),
|
||||
tags: mockTags,
|
||||
tagMap: mockTagMap,
|
||||
onCreateTag: vi.fn().mockResolvedValue({ id: "new-tag", name: "新标签" }),
|
||||
}
|
||||
|
||||
it("应渲染占位符文本", () => {
|
||||
render(<TagSelector {...defaultProps} />)
|
||||
expect(screen.getByPlaceholderText("输入标签后回车添加")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("应渲染已选标签", () => {
|
||||
const { container } = render(<TagSelector {...defaultProps} value={["tag-1", "tag-2"]} />)
|
||||
// 在标签选择器区域内查找已选标签
|
||||
const selectorArea = container.querySelector(".vmat-tag-selector")
|
||||
expect(selectorArea).not.toBeNull()
|
||||
expect(within(selectorArea as HTMLElement).getByText("搞笑")).toBeInTheDocument()
|
||||
expect(within(selectorArea as HTMLElement).getByText("情感")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("应渲染预设标签快捷选择区", () => {
|
||||
const { container } = render(<TagSelector {...defaultProps} />)
|
||||
const presetsArea = container.querySelector(".vmat-tag-selector-presets")
|
||||
expect(presetsArea).not.toBeNull()
|
||||
expect(within(presetsArea as HTMLElement).getByText("搞笑")).toBeInTheDocument()
|
||||
expect(within(presetsArea as HTMLElement).getByText("情感")).toBeInTheDocument()
|
||||
expect(within(presetsArea as HTMLElement).getByText("励志")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("点击预设标签应触发 onChange", () => {
|
||||
const onChange = vi.fn()
|
||||
const { container } = render(<TagSelector {...defaultProps} onChange={onChange} />)
|
||||
const presetsArea = container.querySelector(".vmat-tag-selector-presets")
|
||||
fireEvent.click(within(presetsArea as HTMLElement).getByText("搞笑"))
|
||||
expect(onChange).toHaveBeenCalledWith(["tag-1"])
|
||||
})
|
||||
|
||||
it("点击已选预设标签应移除", () => {
|
||||
const onChange = vi.fn()
|
||||
const { container } = render(
|
||||
<TagSelector {...defaultProps} value={["tag-1"]} onChange={onChange} />,
|
||||
)
|
||||
const presetsArea = container.querySelector(".vmat-tag-selector-presets")
|
||||
// 点击预设区中已选中的标签按钮
|
||||
fireEvent.click(within(presetsArea as HTMLElement).getByText("搞笑"))
|
||||
expect(onChange).toHaveBeenCalledWith([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
import {
|
||||
genderLabel,
|
||||
genderIcon,
|
||||
genderClass,
|
||||
formatDuration,
|
||||
formatFileSize,
|
||||
formatDate,
|
||||
} from "@/pages/voice-materials/utils/format"
|
||||
|
||||
describe("voice-materials format utils", () => {
|
||||
describe("genderLabel", () => {
|
||||
it("应返回正确的性别标签", () => {
|
||||
expect(genderLabel("male")).toBe("男声")
|
||||
expect(genderLabel("female")).toBe("女声")
|
||||
expect(genderLabel("child")).toBe("童声")
|
||||
expect(genderLabel("neutral")).toBe("中性")
|
||||
})
|
||||
|
||||
it("未知性别返回原值", () => {
|
||||
expect(genderLabel("unknown" as any)).toBe("unknown")
|
||||
})
|
||||
})
|
||||
|
||||
describe("genderIcon", () => {
|
||||
it("应返回图标组件", () => {
|
||||
expect(genderIcon("male")).toBeDefined()
|
||||
expect(genderIcon("female")).toBeDefined()
|
||||
expect(genderIcon("child")).toBeDefined()
|
||||
expect(genderIcon("neutral")).toBeDefined()
|
||||
})
|
||||
|
||||
it("未知性别返回 null", () => {
|
||||
expect(genderIcon("unknown" as any)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe("genderClass", () => {
|
||||
it("应返回正确的 CSS 类名", () => {
|
||||
expect(genderClass("male")).toBe("vmat-gender--male")
|
||||
expect(genderClass("female")).toBe("vmat-gender--female")
|
||||
})
|
||||
})
|
||||
|
||||
describe("formatDuration", () => {
|
||||
it("应正确格式化秒数", () => {
|
||||
expect(formatDuration(0)).toBe("0:00")
|
||||
expect(formatDuration(5)).toBe("0:05")
|
||||
expect(formatDuration(59)).toBe("0:59")
|
||||
expect(formatDuration(60)).toBe("1:00")
|
||||
expect(formatDuration(65)).toBe("1:05")
|
||||
expect(formatDuration(125)).toBe("2:05")
|
||||
expect(formatDuration(3600)).toBe("60:00")
|
||||
})
|
||||
})
|
||||
|
||||
describe("formatFileSize", () => {
|
||||
it("应正确格式化文件大小", () => {
|
||||
expect(formatFileSize(0)).toBe("0 B")
|
||||
expect(formatFileSize(512)).toBe("512 B")
|
||||
expect(formatFileSize(1024)).toBe("1.0 KB")
|
||||
expect(formatFileSize(1536)).toBe("1.5 KB")
|
||||
expect(formatFileSize(1024 * 1024)).toBe("1.0 MB")
|
||||
expect(formatFileSize(1024 * 1024 * 2.5)).toBe("2.5 MB")
|
||||
})
|
||||
})
|
||||
|
||||
describe("formatDate", () => {
|
||||
it("应格式化 ISO 日期字符串", () => {
|
||||
const result = formatDate("2026-07-24T10:30:00.000Z")
|
||||
// 格式应该是 YYYY/MM/DD 格式
|
||||
expect(result).toMatch(/^\d{4}\/\d{2}\/\d{2}$/)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* useAudioPlayer hook 测试
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest"
|
||||
import { renderHook, act } from "@testing-library/react"
|
||||
import { useAudioPlayer } from "@/pages/voice-materials/hooks/useAudioPlayer"
|
||||
import type { VoiceMaterial } from "@/pages/voice-materials/types"
|
||||
|
||||
// Mock Audio constructor
|
||||
const mockAudioPlay = vi.fn()
|
||||
const mockAudioPause = vi.fn()
|
||||
const mockAddEventListener = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockAudioPlay.mockReset()
|
||||
mockAudioPause.mockReset()
|
||||
mockAddEventListener.mockReset()
|
||||
|
||||
// Mock HTMLAudioElement
|
||||
global.Audio = vi.fn().mockImplementation(() => ({
|
||||
play: mockAudioPlay.mockResolvedValue(undefined),
|
||||
pause: mockAudioPause,
|
||||
addEventListener: mockAddEventListener,
|
||||
currentTime: 0,
|
||||
volume: 0.7,
|
||||
paused: true,
|
||||
})) as unknown as typeof Audio
|
||||
})
|
||||
|
||||
const mockMaterial: VoiceMaterial = {
|
||||
id: "test-1",
|
||||
name: "测试素材",
|
||||
description: "测试描述",
|
||||
gender: "male",
|
||||
tagIds: ["tag-1"],
|
||||
fileName: "test.mp3",
|
||||
fileSize: 1024,
|
||||
duration: 30,
|
||||
mimeType: "audio/mpeg",
|
||||
createdAt: "2024-01-01T00:00:00Z",
|
||||
fileUrl: "https://example.com/test.mp3",
|
||||
}
|
||||
|
||||
describe("useAudioPlayer", () => {
|
||||
it("应该使用初始状态初始化", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
expect(result.current.playingId).toBeNull()
|
||||
expect(result.current.currentTime).toBe(0)
|
||||
expect(result.current.volume).toBe(0.7)
|
||||
expect(result.current.pausedMaterial).toBeNull()
|
||||
})
|
||||
|
||||
it("stopPlayback 应该重置播放状态", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
act(() => {
|
||||
result.current.stopPlayback()
|
||||
})
|
||||
|
||||
expect(result.current.playingId).toBeNull()
|
||||
expect(result.current.currentTime).toBe(0)
|
||||
expect(result.current.pausedMaterial).toBeNull()
|
||||
})
|
||||
|
||||
it("handlePause 应该暂停播放并设置 pausedMaterial", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
act(() => {
|
||||
result.current.handlePause(mockMaterial)
|
||||
})
|
||||
|
||||
expect(result.current.playingId).toBeNull()
|
||||
expect(result.current.pausedMaterial).toEqual(mockMaterial)
|
||||
})
|
||||
|
||||
it("handlePause 不传参数时不设置 pausedMaterial", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
act(() => {
|
||||
result.current.handlePause()
|
||||
})
|
||||
|
||||
expect(result.current.playingId).toBeNull()
|
||||
expect(result.current.pausedMaterial).toBeNull()
|
||||
})
|
||||
|
||||
it("toggleMute 应该切换静音状态", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
// 默认音量 0.7,静音后应为 0
|
||||
act(() => {
|
||||
result.current.toggleMute()
|
||||
})
|
||||
expect(result.current.volume).toBe(0)
|
||||
|
||||
// 再次切换,恢复到 0.7
|
||||
act(() => {
|
||||
result.current.toggleMute()
|
||||
})
|
||||
expect(result.current.volume).toBe(0.7)
|
||||
})
|
||||
|
||||
it("handlePlay 应该开始播放素材", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
act(() => {
|
||||
result.current.handlePlay(mockMaterial)
|
||||
})
|
||||
|
||||
expect(result.current.playingId).toBe("test-1")
|
||||
expect(result.current.currentTime).toBe(0)
|
||||
expect(global.Audio).toHaveBeenCalledWith("https://example.com/test.mp3")
|
||||
expect(mockAudioPlay).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("handlePlay 对同一个素材不应重复播放", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
act(() => {
|
||||
result.current.handlePlay(mockMaterial)
|
||||
})
|
||||
|
||||
const playCallCount = mockAudioPlay.mock.calls.length
|
||||
|
||||
act(() => {
|
||||
result.current.handlePlay(mockMaterial)
|
||||
})
|
||||
|
||||
// 不应该再次调用 play
|
||||
expect(mockAudioPlay.mock.calls.length).toBe(playCallCount)
|
||||
})
|
||||
|
||||
it("返回值应该包含所有必要的方法和状态", () => {
|
||||
const { result } = renderHook(() => useAudioPlayer())
|
||||
|
||||
expect(typeof result.current.handlePlay).toBe("function")
|
||||
expect(typeof result.current.handlePause).toBe("function")
|
||||
expect(typeof result.current.handleSeek).toBe("function")
|
||||
expect(typeof result.current.handleVolumeChange).toBe("function")
|
||||
expect(typeof result.current.toggleMute).toBe("function")
|
||||
expect(typeof result.current.stopPlayback).toBe("function")
|
||||
expect(typeof result.current.playingId).toBe("object") // string | null
|
||||
expect(typeof result.current.currentTime).toBe("number")
|
||||
expect(typeof result.current.volume).toBe("number")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* VoiceMaterialLibrary 模块 smoke test
|
||||
* 建立完整依赖链,确保 vitest related 模式能匹配到
|
||||
* voice-materials 目录下所有文件的改动(包括子组件和工具函数)
|
||||
*/
|
||||
import { describe, it, expect } from "vitest"
|
||||
|
||||
// 主组件
|
||||
import "@/pages/voice-materials/VoiceMaterialLibrary"
|
||||
|
||||
// 子组件
|
||||
import "@/pages/voice-materials/components/TagSelector"
|
||||
import "@/pages/voice-materials/components/MaterialForm"
|
||||
import "@/pages/voice-materials/components/VoiceMaterialCard"
|
||||
import "@/pages/voice-materials/components/VoiceMaterialRow"
|
||||
|
||||
// 工具函数
|
||||
import "@/pages/voice-materials/utils/format"
|
||||
import "@/pages/voice-materials/utils/audio"
|
||||
|
||||
describe("VoiceMaterialLibrary module smoke test", () => {
|
||||
it("should load all voice-material modules", () => {
|
||||
// 纯模块加载测试,确保所有组件/工具函数能正常 import
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* VoiceLibrary 模块 smoke test
|
||||
* 建立完整依赖链,确保 vitest related 模式能匹配到
|
||||
* voices 目录下所有文件的改动(包括工具函数)
|
||||
*/
|
||||
import { describe, it, expect } from "vitest"
|
||||
|
||||
// 主组件
|
||||
import "@/pages/voices/VoiceLibrary"
|
||||
|
||||
// 类型与常量
|
||||
import "@/pages/voices/types"
|
||||
import "@/pages/voices/constants"
|
||||
|
||||
// 工具函数
|
||||
import "@/pages/voices/utils/format"
|
||||
import "@/pages/voices/utils/audio"
|
||||
|
||||
describe("VoiceLibrary module smoke test", () => {
|
||||
it("should load all voice-library modules", () => {
|
||||
// 纯模块加载测试,确保所有组件/工具函数能正常 import
|
||||
expect(true).toBe(true)
|
||||
})
|
||||
})
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
# 端口分配清单
|
||||
|
||||
> 本文档梳理 xiaoxia-saas 项目中所有服务、容器及 CI 环境使用的端口,
|
||||
> 作为运维、排障和新功能开发时的统一参考。
|
||||
>
|
||||
> 最后更新:2026-07-24
|
||||
|
||||
---
|
||||
|
||||
## 一、应用服务端口
|
||||
|
||||
| 服务 | 容器内端口 | 环境变量名 | Staging 宿主机 | Production 宿主机 | 说明 |
|
||||
| -------- | ---------- | ---------------- | -------------- | ----------------- | ----------------------------------- |
|
||||
| API | 8000 | `API_PORT` | 8000 | 8001 | FastAPI 服务,Nginx 反代后端 |
|
||||
| Web | 80 | `WEB_PORT` | 3001 | 3002 | Nginx + 前端静态文件 |
|
||||
| Worker | — | — | — | — | Celery 任务队列,不暴露端口 |
|
||||
|
||||
### 补充说明
|
||||
- API 容器内部固定监听 8000(`API_HOST=0.0.0.0`,`API_PORT=8000`)
|
||||
- Web 容器内部 Nginx 固定监听 80
|
||||
- 所有端口均绑定 `127.0.0.1`,不直接暴露公网,由前置 Nginx/CDN 转发
|
||||
|
||||
---
|
||||
|
||||
## 二、基础设施端口
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
| 环境 | 容器内端口 | 宿主机映射 | 环境变量名 | 默认值 |
|
||||
| ------------ | ---------- | ---------- | --------------------- | -------- |
|
||||
| Production | 5432 | 5433 | `POSTGRES_PORT` | 5433 |
|
||||
| Staging | 5432 | 5434 | `POSTGRES_PORT` | 5434 |
|
||||
| 开发本地 | 5432 | 5432 | `DATABASE_URL` 中端口 | 5432 |
|
||||
| CI 共享 PG | 5432 | 5433 | `CI_SHARED_PG_PORT` | 5433 |
|
||||
| CI 本地 PG | 5432 | 5432 | `CI_LOCAL_PG_PORT` | 5432 |
|
||||
|
||||
### Redis
|
||||
|
||||
| 环境 | 容器内端口 | 宿主机映射 | 环境变量名 | 默认值 |
|
||||
| ------------ | ---------- | ---------- | ------------------- | -------- |
|
||||
| Production | 6379 | 6380 | `REDIS_URL` 中端口 | — |
|
||||
| Staging | 6379 | 6381 | `REDIS_URL` 中端口 | — |
|
||||
| 开发本地 | 6379 | 6379 | `REDIS_URL` | 6379 |
|
||||
| CI 动态创建 | 6379 | 随机 | 运行时 `REDIS_PORT` | — |
|
||||
|
||||
> CI Integration Tests 中 Redis 容器使用 `-P` 随机映射端口,
|
||||
> 通过 `docker port` 命令获取实际端口后写入 `REDIS_URL`。
|
||||
|
||||
### 容器镜像 Registry
|
||||
|
||||
| 服务 | 端口 | 地址 | 说明 |
|
||||
| ----------------- | ----- | ---------------------- | ------------------------------ |
|
||||
| Gitea Registry | 5000 | 172.30.18.198:5000 | CI 构建服务器内网 Registry |
|
||||
| ACR(生产镜像源) | 443 | crpi-xxx.aliyuncs.com | 阿里云容器镜像服务(HTTPS) |
|
||||
|
||||
---
|
||||
|
||||
## 三、CI / DevOps 端口
|
||||
|
||||
| 服务/用途 | 端口 | 环境变量名 | 默认值 | 说明 |
|
||||
| ------------------- | ----- | --------------------- | ------ | ------------------------------------- |
|
||||
| CI ChatOps Webhook | 8090 | `CHATOPS_WEBHOOK_PORT`| 8090 | Gitea webhook 接收服务(`scripts/ci/chatops/`) |
|
||||
| Staging SSH 部署 | 22222 | `STAGING_SSH_PORT` | 22222 | Staging 服务器 SSH 端口(secrets 配置) |
|
||||
| Preview SSH 部署 | 22222 | `PREVIEW_SSH_PORT` | 22222 | Preview 服务器 SSH 端口(secrets 配置) |
|
||||
| Preview 前端访问 | 80 | — | 80 | Nginx 子域名路由,`*.preview.xiaoxiajianji.com` |
|
||||
|
||||
---
|
||||
|
||||
## 四、开发环境默认端口(.env.example)
|
||||
|
||||
| 用途 | 端口 | 环境变量名 / 出处 |
|
||||
| ------------ | ----- | ------------------------------------------ |
|
||||
| API 服务 | 8000 | `API_PORT` |
|
||||
| 数据库 | 5432 | `DATABASE_URL`(`postgresql+psycopg://...:5432/...`) |
|
||||
| Redis | 6379 | `REDIS_URL` / `CELERY_BROKER_URL` / `CELERY_RESULT_BACKEND` |
|
||||
| SMTP | 587 | `SMTP_PORT` |
|
||||
| 前端开发服务 | 3000 | `APP_BASE_URL`(默认 localhost:3000) |
|
||||
| Vite Dev | 5173 | `CORS_ORIGINS_RAW` 中包含 |
|
||||
|
||||
---
|
||||
|
||||
## 五、CI Workflow 中的端口变量
|
||||
|
||||
### ci-pipeline.yml 顶层 env
|
||||
|
||||
| 变量名 | 默认值 | 用途 |
|
||||
| ------------------- | ------ | ------------------------ |
|
||||
| `CI_PG_PORT` | 5432 | CI PG 容器端口(本地) |
|
||||
| `CI_SHARED_PG_PORT` | 5433 | CI 共享常驻 PG 端口 |
|
||||
|
||||
### scripts/ci/ci_env.sh(统一常量)
|
||||
|
||||
| 变量名 | 默认值 | 说明 |
|
||||
| ------------------- | ----------- | ----------------------------- |
|
||||
| `CI_SHARED_PG_PORT` | 5433 | 共享常驻 PG 实例端口 |
|
||||
| `CI_LOCAL_PG_PORT` | 5432 | 本地 PG 容器默认端口 |
|
||||
| `CI_DEFAULT_DB` | xiaoxia_saas | 默认数据库名 |
|
||||
|
||||
---
|
||||
|
||||
## 六、命名规范
|
||||
|
||||
### 推荐命名格式
|
||||
|
||||
统一使用 `{服务/用途}_PORT` 格式:
|
||||
|
||||
```bash
|
||||
API_PORT # 应用服务
|
||||
WEB_PORT # 应用服务
|
||||
POSTGRES_PORT # 基础设施
|
||||
REDIS_PORT # 基础设施
|
||||
SMTP_PORT # 外部服务
|
||||
CI_SHARED_PG_PORT # CI 特定
|
||||
CI_LOCAL_PG_PORT # CI 特定
|
||||
CHATOPS_WEBHOOK_PORT # DevOps 服务
|
||||
```
|
||||
|
||||
### 历史命名不一致(待统一)
|
||||
|
||||
- `WEBHOOK_PORT`(chatops config.py 内部变量)→ 应与外部 env 名 `CHATOPS_WEBHOOK_PORT` 对齐
|
||||
- `STAGING_SSH_PORT` / `PREVIEW_SSH_PORT` → 符合规范,保留
|
||||
- `CI_PG_PORT`(workflow 中)→ 建议统一为 `CI_LOCAL_PG_PORT` 与 `ci_env.sh` 对齐
|
||||
|
||||
---
|
||||
|
||||
## 七、相关配置文件路径
|
||||
|
||||
| 文件路径 | 端口相关内容 |
|
||||
| ------------------------------------- | -------------------------------- |
|
||||
| `infra/docker/compose.yml` | API / Web / Worker 端口映射 |
|
||||
| `infra/docker/infra.yml` | Staging PG / Redis 端口 |
|
||||
| `infra/docker/infra-production.yml` | Production PG / Redis 端口 |
|
||||
| `.env.example` | 开发环境全部端口变量 |
|
||||
| `.gitea/workflows/ci-pipeline.yml` | CI PG 端口配置 |
|
||||
| `scripts/ci/ci_env.sh` | CI 端口统一常量 |
|
||||
| `scripts/ci/chatops/config.py` | ChatOps Webhook 端口 |
|
||||
| `scripts/ci/run_integration_tests.sh` | Redis 动态端口 + PG 端口 |
|
||||
| `scripts/ci/run_validate.sh` | PG 端口 |
|
||||
| `scripts/ci/validate_migration.sh` | PG 端口 |
|
||||
|
||||
Executable
+198
@@ -0,0 +1,198 @@
|
||||
# VoiceLibrary 页面重构方案
|
||||
|
||||
## 现状分析
|
||||
|
||||
**当前文件:** `apps/web/src/pages/voices/VoiceLibrary.tsx` — 1783 行
|
||||
|
||||
**代码质量:**
|
||||
- `any`: 0 处
|
||||
- `ts-ignore`: 0 处
|
||||
- `eslint-disable`: 0 处
|
||||
- `TODO`: 1 处
|
||||
- 整体质量良好,重构阻力小
|
||||
|
||||
## 目录结构(重构后)
|
||||
|
||||
```
|
||||
apps/web/src/pages/voices/
|
||||
├── VoiceLibrary.tsx # 主组件(目标:~550 行,-69%)
|
||||
├── types.ts # 类型定义
|
||||
├── constants.ts # 常量 + 配置
|
||||
├── utils/
|
||||
│ ├── format.ts # 格式化工具函数
|
||||
│ └── audio.ts # 音频工具函数
|
||||
├── components/
|
||||
│ ├── VoiceCard.tsx # 预设音色卡片
|
||||
│ ├── CloneVoiceCard.tsx # 克隆音色卡片
|
||||
│ ├── CloneDetailModal.tsx # 克隆详情弹窗
|
||||
│ ├── CloneCardSkeleton.tsx # 克隆卡片骨架屏
|
||||
│ ├── UploadModal.tsx # 上传音色弹窗
|
||||
│ ├── TTSModal.tsx # TTS合成弹窗
|
||||
│ ├── VoiceFilterBar.tsx # 筛选栏(搜索/性别/语言)
|
||||
│ └── VoiceTabBar.tsx # Tab切换栏
|
||||
└── hooks/
|
||||
├── useVoices.ts # 音色数据查询 + 筛选
|
||||
├── useAudioPlayer.ts # 音频播放控制
|
||||
├── useVoiceUpload.ts # 音色上传逻辑
|
||||
├── useTTS.ts # TTS合成逻辑
|
||||
└── useCloneVoice.ts # 克隆音色操作
|
||||
```
|
||||
|
||||
## 三阶段渐进式重构
|
||||
|
||||
### Phase 1:抽离类型、常量、工具函数
|
||||
|
||||
**目标:** 主文件 1783 → ~1550 行(-13%)
|
||||
|
||||
**抽出内容:**
|
||||
|
||||
1. **`types.ts`** — 类型定义(~60行)
|
||||
- `PresetVoiceDisplay` / `ClonedVoiceDisplay` / `VoiceCardProps` / `CloneVoiceCardProps`
|
||||
- `TabKey` / `Toast` / `VoiceUploadMetadata`
|
||||
- 现有 `mapPresetToDisplay` / `mapCloneToDisplay` 数据映射函数
|
||||
|
||||
2. **`constants.ts`** — 常量配置(~40行)
|
||||
- `CLONE_STATUS_CONFIG` 克隆状态配置
|
||||
- `GENDER_LABEL_MAP` / `LANGUAGE_LABEL_MAP` 性别/语言标签映射
|
||||
- Tab 配置项
|
||||
|
||||
3. **`utils/format.ts`** — 格式化工具(~25行)
|
||||
- `formatTime` 时长格式化
|
||||
- `formatFileSize` 文件大小格式化
|
||||
- `genderLabel` / `languageLabel` / `genderClass`
|
||||
|
||||
4. **`utils/audio.ts`** — 音频工具(~15行)
|
||||
- `getAudioDuration` 获取音频文件时长
|
||||
|
||||
5. **`format.test.ts`** — 工具函数单测
|
||||
- 覆盖 formatTime / formatFileSize 等纯函数
|
||||
|
||||
**Phase 1 交付:**
|
||||
- 新增文件:6 个(types.ts / constants.ts / utils/format.ts / utils/audio.ts / format.test.ts)
|
||||
- 主文件减少:~230 行
|
||||
- 纯机械抽离,无逻辑改动
|
||||
|
||||
---
|
||||
|
||||
### Phase 2:抽离子组件
|
||||
|
||||
**目标:** 主文件 1550 → ~950 行(-39%)
|
||||
|
||||
**抽出组件:**
|
||||
|
||||
1. **`components/VoiceCard.tsx`** — 预设音色卡片(~120行)
|
||||
- 卡片渲染:头像、名称、性别标签、播放按钮、进度条、收藏
|
||||
- Props:voice / playingId / currentTime / onPlay / onPause / onSeek / onToggleStar
|
||||
|
||||
2. **`components/CloneVoiceCard.tsx`** — 克隆音色卡片(~160行)
|
||||
- 三种状态:processing / success / failed
|
||||
- 操作:播放、详情、删除、重试、使用
|
||||
- Props:voice / playingId / currentTime / onPlayPause / onShowDetail / onDelete / onRetry / onUse
|
||||
|
||||
3. **`components/CloneDetailModal.tsx`** — 克隆详情弹窗(~90行)
|
||||
- 展示克隆音色详细信息
|
||||
- 状态展示、音频播放、操作按钮
|
||||
|
||||
4. **`components/CloneCardSkeleton.tsx`** — 克隆卡片骨架屏(~20行)
|
||||
- 加载状态占位
|
||||
|
||||
5. **`components/UploadModal.tsx`** — 上传音色弹窗(~180行)
|
||||
- 文件选择、名称/性别/描述填写
|
||||
- 上传进度展示
|
||||
- Props:open / onClose / onUpload
|
||||
|
||||
6. **`components/TTSModal.tsx`** — TTS合成弹窗(~170行)
|
||||
- 文本输入、音色选择、语速调节
|
||||
- 合成状态轮询(idle/synthesizing/done/error)
|
||||
- 保存到素材库
|
||||
- Props:open / onClose / onSave
|
||||
|
||||
7. **`components/VoiceFilterBar.tsx`** — 筛选栏(~80行)
|
||||
- 搜索框、性别筛选、语言筛选
|
||||
- Props:searchText / filterGender / filterLang / onChange handlers
|
||||
|
||||
**Phase 2 交付:**
|
||||
- 新增组件:7 个
|
||||
- 主文件减少:~600 行
|
||||
- 纯UI抽离,业务逻辑保留在主组件
|
||||
|
||||
---
|
||||
|
||||
### Phase 3:抽离业务逻辑 Hook
|
||||
|
||||
**目标:** 主文件 950 → ~550 行(-42%)
|
||||
|
||||
**抽出 Hook:**
|
||||
|
||||
1. **`hooks/useVoices.ts`** — 音色数据 Hook(~200行)
|
||||
- 三个 useQuery:presetVoices / cloneVoices / materialVoices / unifiedStats
|
||||
- 筛选逻辑:searchText / filterGender / filterLang → filteredPreset / filteredClone
|
||||
- 统计数据:presetCount / cloneCount / materialCount
|
||||
- 收藏切换 handleToggleStar
|
||||
- 返回:data / loading / filtered / counts / handlers
|
||||
|
||||
2. **`hooks/useAudioPlayer.ts`** — 音频播放控制 Hook(~120行)
|
||||
- playingId / currentTime / intervalRef 状态
|
||||
- handlePlay / handlePause / handleSeek
|
||||
- 自动停止(切换新音频时停止旧的)
|
||||
- 组件卸载清理
|
||||
- 注意:与 VoiceMaterialLibrary 的 useAudioPlayer 类似但有差异(一个操作DOM音频,一个操作audio元素),评估是否复用还是独立
|
||||
|
||||
3. **`hooks/useVoiceUpload.ts`** — 音色上传 Hook(~120行)
|
||||
- uploadFile / uploadName / uploadGender / uploadDesc / uploadProgress 状态
|
||||
- uploadMutation(上传文件 + 创建音色)
|
||||
- buildVoiceMetadata 元数据构建
|
||||
- getAudioDuration 时长获取
|
||||
- 成功后刷新列表 + toast 关闭弹窗
|
||||
|
||||
4. **`hooks/useTTS.ts`** — TTS合成 Hook(~110行)
|
||||
- ttsOpen / ttsText / ttsVoiceId / ttsSpeed 弹窗状态
|
||||
- ttsJobId / ttsStatus / ttsAudioUrl / ttsError 合成状态
|
||||
- handleTtsSynthesize 发起合成 + 轮询
|
||||
- handleTtsSave 保存到素材库
|
||||
- handleTtsClose 清理状态
|
||||
|
||||
5. **`hooks/useCloneVoice.ts`** — 克隆音色操作 Hook(~80行)
|
||||
- deleteMutation / retryMutation
|
||||
- handleCloneDelete / handleCloneRetry
|
||||
- detailVoice 详情状态
|
||||
- 操作后刷新列表
|
||||
|
||||
**Phase 3 交付:**
|
||||
- 新增 Hook:5 个
|
||||
- 主文件减少:~400 行
|
||||
- 主文件只剩:Tab切换逻辑 + JSX 组装 + 顶层状态编排
|
||||
|
||||
---
|
||||
|
||||
## 最终效果汇总
|
||||
|
||||
| 阶段 | 主文件行数 | 减少行数 | 减少比例 | 新增文件 |
|
||||
|------|-----------|---------|----------|----------|
|
||||
| 初始 | 1783 | — | — | — |
|
||||
| Phase 1 | ~1550 | -233 | -13.1% | 5 |
|
||||
| Phase 2 | ~950 | -600 | -38.7% | 7 |
|
||||
| Phase 3 | ~550 | -400 | -42.1% | 5 |
|
||||
| **总计** | **~550** | **-1233** | **-69.2%** | **17** |
|
||||
|
||||
## 与 GeneratePage / VoiceMaterialLibrary 的异同
|
||||
|
||||
**相同点:**
|
||||
- 三阶段渐进式重构(类型常量 → 组件 → Hook)
|
||||
- 每阶段独立PR,独立验证
|
||||
- 每阶段加 smoke test 保证 vitest related 模式可用
|
||||
- 代码质量基线高(0 any / 0 ts-ignore)
|
||||
|
||||
**不同点:**
|
||||
- VoiceLibrary 有两个数据源(预设音色 + 克隆音色),还有TTS和上传功能
|
||||
- 音频播放逻辑与 VoiceMaterialLibrary 类似但操作的音频类型不同
|
||||
- 有 CloneModal 是外部组件(已在 @/components/voice/CloneModal),不需要重写
|
||||
- 骨架屏组件比较简单
|
||||
|
||||
## 风险与注意事项
|
||||
|
||||
1. **vitest related 模式**:每阶段新增文件需建立测试覆盖,避免 "No test files found"
|
||||
2. **Preview Deploy**:环境问题导致失败,不影响代码质量
|
||||
3. **音频播放逻辑**:VoiceLibrary 和 VoiceMaterialLibrary 的播放控制类似但是两套独立实现,后续可考虑抽象为共享 Hook
|
||||
4. **克隆状态**:CLONE_STATUS_CONFIG 是核心常量,抽离时注意类型完整
|
||||
5. **上传逻辑**:uploadMutation 内部逻辑较复杂(上传文件 + 获取时长 + 创建音色),抽 Hook 时保持逻辑不变
|
||||
Executable
+198
@@ -0,0 +1,198 @@
|
||||
# VoiceMaterialLibrary 页面拆分方案
|
||||
|
||||
## 一、现状摸底
|
||||
|
||||
**文件:** `apps/web/src/pages/voice-materials/VoiceMaterialLibrary.tsx`
|
||||
**总行数:** 1966 行
|
||||
**CSS 文件:** `apps/web/src/pages/voice-materials/voice-materials.css` (1262 行)
|
||||
|
||||
### 代码质量
|
||||
|
||||
| 指标 | 数量 | 评价 |
|
||||
|------|------|------|
|
||||
| `any` 类型 | 0 | ✅ 优秀 |
|
||||
| `@ts-ignore` | 0 | ✅ 优秀 |
|
||||
| `eslint-disable` | 0 | ✅ 优秀 |
|
||||
| TODO/FIXME | 0 | ✅ 干净 |
|
||||
|
||||
### 内联组件分布
|
||||
|
||||
| 组件 | 行数 | 职责 |
|
||||
|------|------|------|
|
||||
| `TagSelector` | 148行 (197-345) | 标签选择器(输入+建议+选择) |
|
||||
| `MaterialForm` | 187行 (356-543) | 上传/编辑表单(名称/描述/性别/标签/文件) |
|
||||
| `VoiceMaterialCard` | 220行 (543-763) | 卡片视图 + 音频播放进度条 |
|
||||
| `VoiceMaterialRow` | 153行 (763-916) | 列表视图 + 音频播放进度条 |
|
||||
| **VoiceMaterialLibrary(主组件)** | **1051行 (916-1966)** | **页面主逻辑 + 渲染** |
|
||||
|
||||
### 主组件内部结构(1051行)
|
||||
|
||||
- **状态 & hooks**:约 230行
|
||||
- 数据查询:assets / libraries / tags / presetVoices
|
||||
- 视图状态:viewMode / searchText / filterGender / filterTagId
|
||||
- 播放状态:playingId / currentTime / audioRef / volume / pausedMaterial
|
||||
- 弹窗:uploadOpen / editingMaterial / ttsOpen
|
||||
- 批量:selectedIds / uploadProgress / batchCustomTag
|
||||
- TTS:ttsText / ttsVoiceId / ttsSpeed / ttsJobId / ttsStatus / ttsAudioUrl / ttsError
|
||||
- **播放控制函数**:约 100行(stopPlayback/startPlayback/handlePlay/handlePause/handleSeek/handleVolumeChange/toggleMute)
|
||||
- **数据操作函数**:约 60行(handleUpload/handleEdit/handleDelete)
|
||||
- **筛选 & 统计**:约 40行(filtered/tagCountMap)
|
||||
- **批量操作**:约 80行(handleToggleSelect/handleSelectAll/handleBatchDelete/handleBatchTag/handleBatchCustomTag)
|
||||
- **TTS 合成**:约 70行(handleTtsSynthesize/handleTtsSave)
|
||||
- **渲染 JSX**:约 473行
|
||||
|
||||
## 二、拆分策略
|
||||
|
||||
跟 GeneratePage 同样的思路:**按职责拆分,功能不变,纯结构优化。**
|
||||
|
||||
拆分四阶段,每个阶段独立 PR,逐步降低主文件复杂度。
|
||||
|
||||
---
|
||||
|
||||
## Phase 1:抽离常量、类型、工具函数
|
||||
|
||||
**目标:** 把纯数据定义和纯函数抽出去,主文件只留组件。
|
||||
|
||||
### 抽离内容
|
||||
|
||||
| 新文件 | 内容 | 行数估计 |
|
||||
|--------|------|---------|
|
||||
| `types.ts` | `VoiceGender` / `ViewMode` / `VoiceMaterial` / `VoiceAssetMetadata` 等类型定义 | ~40行 |
|
||||
| `constants.ts` | `MAX_CARD_TAGS` / `MAX_ROW_TAGS` / `TAG_VARIANTS` / `GENDER_OPTIONS` | ~25行 |
|
||||
| `utils/format.ts` | `formatDuration` / `formatFileSize` / `formatDate` / `genderLabel` / `genderIcon` / `genderClass` | ~35行 |
|
||||
| `utils/audio.ts` | `getAudioDuration`(纯工具,跟组件无关) | ~20行 |
|
||||
| `utils/mappers.ts` | `mapAssetToMaterial` / `buildMetadata`(数据映射) | ~35行 |
|
||||
|
||||
### 预期效果
|
||||
|
||||
- 主文件减少约 **155 行**(1966 → ~1811)
|
||||
- 工具函数可复用、可单测
|
||||
|
||||
---
|
||||
|
||||
## Phase 2:抽离已有内联子组件
|
||||
|
||||
**目标:** 把 4 个已经定义好的内联组件拆成独立文件,主文件只保留 VoiceMaterialLibrary 主组件。
|
||||
|
||||
### 抽离内容
|
||||
|
||||
| 新文件 | 原位置 | 行数 | 备注 |
|
||||
|--------|--------|------|------|
|
||||
| `components/TagSelector.tsx` | 197-345行 | ~148行 | 标签选择器 |
|
||||
| `components/MaterialForm.tsx` | 356-543行 | ~187行 | 上传/编辑表单 |
|
||||
| `components/VoiceMaterialCard.tsx` | 543-763行 | ~220行 | 卡片视图,带播放控制 |
|
||||
| `components/VoiceMaterialRow.tsx` | 763-916行 | ~153行 | 列表视图,带播放控制 |
|
||||
|
||||
### 播放状态共享方案
|
||||
|
||||
Card 和 Row 都有播放进度条(共 ~60行重复代码),但播放状态在主组件里。
|
||||
|
||||
**方案:** 播放状态提升到主组件,Card/Row 只接收 prop 并回调:
|
||||
- `isPlaying` / `currentTime` / `onPlay` / `onPause` / `onSeek`
|
||||
- 主组件统一管理 audioRef 和播放状态
|
||||
|
||||
这样 Card 和 Row 是纯展示组件,播放逻辑集中在主组件。
|
||||
|
||||
### 预期效果
|
||||
|
||||
- 主文件减少约 **700 行**(1811 → ~1111)
|
||||
- 主组件专注页面逻辑,子组件专注展示
|
||||
|
||||
---
|
||||
|
||||
## Phase 3:主组件拆分 — 业务逻辑抽 Hook
|
||||
|
||||
**目标:** 把主组件里的业务逻辑按领域拆成自定义 Hook,主组件只负责组装。
|
||||
|
||||
### 抽离 Hooks
|
||||
|
||||
| Hook 文件 | 职责 | 管理的状态 |
|
||||
|-----------|------|-----------|
|
||||
| `hooks/useVoiceMaterials.ts` | 素材列表查询 + 筛选 + 增删改 | assets / searchText / filterGender / filterTagId / uploadMutation / editMutation / deleteMutation |
|
||||
| `hooks/useAudioPlayer.ts` | 音频播放控制 | playingId / currentTime / volume / audioRef / pausedMaterial |
|
||||
| `hooks/useBatchOperations.ts` | 批量操作 | selectedIds / handleToggleSelect / handleSelectAll / handleBatchDelete / handleBatchTag |
|
||||
| `hooks/useTtsSynthesize.ts` | TTS 合成逻辑 | ttsText / ttsVoiceId / ttsSpeed / ttsJobId / ttsStatus / ttsAudioUrl / ttsError |
|
||||
|
||||
### 预期效果
|
||||
|
||||
- 主组件减少约 **500 行**(1111 → ~611)
|
||||
- 每个 Hook 职责单一,可独立测试
|
||||
- 主组件变成"组装器",可读性大幅提升
|
||||
|
||||
---
|
||||
|
||||
## Phase 4:UI 组件细化 — 工具栏 & 弹窗拆分
|
||||
|
||||
**目标:** 把主组件里的大块 JSX 拆成独立 UI 组件。
|
||||
|
||||
### 抽离 UI 组件
|
||||
|
||||
| 组件文件 | 内容 | 行数估计 |
|
||||
|----------|------|---------|
|
||||
| `components/LibraryToolbar.tsx` | 顶部工具栏:搜索框 + 性别筛选 + 视图切换 + 结果计数 | ~60行 |
|
||||
| `components/TagFilterBar.tsx` | 标签筛选药丸条(全部 + 各标签计数) | ~45行 |
|
||||
| `components/BatchActionBar.tsx` | 批量操作栏:全选 + 计数 + 批量打标签 + 批量删除 | ~70行 |
|
||||
| `components/UploadModal.tsx` | 上传弹窗(包裹 MaterialForm) | ~30行 |
|
||||
| `components/EditModal.tsx` | 编辑弹窗(包裹 MaterialForm) | ~30行 |
|
||||
| `components/TtsSynthesizeModal.tsx` | AI 配音合成弹窗:文本输入 + 音色选择 + 语速 + 合成结果预览 + 保存 | ~150行 |
|
||||
| `components/EmptyState.tsx` | 空状态展示 | ~20行 |
|
||||
| `components/VoiceMaterialGrid.tsx` | 卡片视图网格容器 | ~25行 |
|
||||
| `components/VoiceMaterialList.tsx` | 列表视图表格容器 | ~25行 |
|
||||
|
||||
### 预期效果
|
||||
|
||||
- 主组件 JSX 部分减少约 **400 行**(611 → ~211)
|
||||
- 每个 UI 组件职责清晰,方便后续迭代
|
||||
|
||||
---
|
||||
|
||||
## 三、拆分后文件结构
|
||||
|
||||
```
|
||||
apps/web/src/pages/voice-materials/
|
||||
├── VoiceMaterialLibrary.tsx # 主组件(~211行,组装器)
|
||||
├── voice-materials.css # 样式(保持不变,后续再拆)
|
||||
├── types.ts # 类型定义
|
||||
├── constants.ts # 常量
|
||||
├── utils/
|
||||
│ ├── format.ts # 格式化工具
|
||||
│ ├── audio.ts # 音频工具
|
||||
│ └── mappers.ts # 数据映射
|
||||
├── hooks/
|
||||
│ ├── useVoiceMaterials.ts # 素材数据 + 筛选 + 增删改
|
||||
│ ├── useAudioPlayer.ts # 音频播放控制
|
||||
│ ├── useBatchOperations.ts # 批量操作
|
||||
│ └── useTtsSynthesize.ts # TTS合成
|
||||
└── components/
|
||||
├── TagSelector.tsx # 标签选择器
|
||||
├── MaterialForm.tsx # 上传/编辑表单
|
||||
├── VoiceMaterialCard.tsx # 卡片视图
|
||||
├── VoiceMaterialRow.tsx # 列表视图
|
||||
├── VoiceMaterialGrid.tsx # 卡片网格容器
|
||||
├── VoiceMaterialList.tsx # 列表容器
|
||||
├── LibraryToolbar.tsx # 顶部工具栏
|
||||
├── TagFilterBar.tsx # 标签筛选条
|
||||
├── BatchActionBar.tsx # 批量操作栏
|
||||
├── UploadModal.tsx # 上传弹窗
|
||||
├── EditModal.tsx # 编辑弹窗
|
||||
├── TtsSynthesizeModal.tsx # TTS合成弹窗
|
||||
└── EmptyState.tsx # 空状态
|
||||
```
|
||||
|
||||
### 拆分前后对比
|
||||
|
||||
| 指标 | 拆分前 | 拆分后 | 变化 |
|
||||
|------|--------|--------|------|
|
||||
| 主文件行数 | 1966 | ~211 | **-89%** |
|
||||
| 文件数量 | 2 | 22 | +20 |
|
||||
| 最大文件 | 1966行 | ~220行 | -89% |
|
||||
| 可测试性 | 低 | 高 | 每个Hook/组件可单测 |
|
||||
|
||||
## 四、实施顺序 & 风险
|
||||
|
||||
1. **Phase 1**:最低风险,纯抽离,零逻辑变化
|
||||
2. **Phase 2**:低风险,组件本来就是独立定义的,只是挪位置
|
||||
3. **Phase 3**:中风险,Hook 拆分需要仔细梳理状态依赖
|
||||
4. **Phase 4**:低风险,JSX 拆分,纯结构调整
|
||||
|
||||
**每个 Phase 完成后提 PR,CI 全绿再合,跟 GeneratePage 同样节奏。**
|
||||
@@ -2,7 +2,6 @@
|
||||
# Worker Dockerfile - 分层缓存优化版
|
||||
# 优化:基础依赖 + Worker大包预构建为基础镜像,业务构建仅叠加业务依赖
|
||||
# 基础镜像:worker-base-builder / worker-base-runtime
|
||||
# 预计节省:依赖不变时构建时间从23min降至5min以内
|
||||
# ============================================================
|
||||
|
||||
# ==================== Builder 阶段 ====================
|
||||
@@ -24,8 +23,7 @@ RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
-r /tmp/requirements.txt \
|
||||
&& rm /tmp/requirements.txt
|
||||
|
||||
# ---- 增量瘦身(只处理新增的业务依赖)----
|
||||
RUN find /opt/venv -name "*.so" -type f -exec strip --strip-all {} \; 2>/dev/null || true
|
||||
# ---- 增量瘦身(清理新增业务依赖的冗余文件)----
|
||||
RUN find /opt/venv -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null; \
|
||||
find /opt/venv -name "*.pyc" -delete 2>/dev/null || true
|
||||
|
||||
@@ -41,30 +39,33 @@ ARG APP_VERSION=dev
|
||||
# 从 builder 复制 Python 虚拟环境
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 复制应用代码
|
||||
COPY apps/worker/ /app/apps/worker/
|
||||
COPY apps/api/app/config.py /app/apps/api/app/config.py
|
||||
COPY apps/api/app/core/ /app/apps/api/app/core/
|
||||
COPY packages/ /app/packages/
|
||||
COPY alembic.ini /app/alembic.ini
|
||||
COPY migrations/ /app/migrations/
|
||||
|
||||
# 复制 Worker 启动脚本
|
||||
COPY infra/docker/entrypoint-worker.sh /usr/local/bin/entrypoint-worker.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint-worker.sh
|
||||
|
||||
# 设置 Python 路径
|
||||
# 设置 Python 环境变量
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
ENV PYTHONPATH=/app:/app/packages
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV APP_VERSION=$APP_VERSION
|
||||
|
||||
# 创建非 root 用户运行 Worker
|
||||
RUN groupadd -r celery && useradd -r -g celery -d /app -s /sbin/nologin celery \
|
||||
&& mkdir -p /app/generated && chown celery:celery /app/generated
|
||||
# 创建非 root 用户(极少变化,放最前)
|
||||
RUN groupadd -r celery \
|
||||
&& useradd -r -g celery -d /app -s /sbin/nologin celery \
|
||||
&& mkdir -p /app/generated \
|
||||
&& chown celery:celery /app/generated
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 复制文件按变化频率从低到高排序,最大化层缓存命中
|
||||
COPY alembic.ini /app/alembic.ini
|
||||
COPY migrations/ /app/migrations/
|
||||
COPY packages/ /app/packages/
|
||||
COPY apps/api/app/config.py /app/apps/api/app/config.py
|
||||
COPY apps/api/app/core/ /app/apps/api/app/core/
|
||||
|
||||
# 复制 Worker 启动脚本
|
||||
COPY infra/docker/entrypoint-worker.sh /usr/local/bin/entrypoint-worker.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint-worker.sh
|
||||
|
||||
# 业务代码(变化最频繁,放最后)
|
||||
COPY apps/worker/ /app/apps/worker/
|
||||
|
||||
USER celery
|
||||
|
||||
|
||||
@@ -28,6 +28,28 @@ class EditPlanStatus(StrEnum):
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> "EditPlanStatus":
|
||||
"""兼容历史脏数据,避免枚举转换失败导致500。
|
||||
|
||||
- success/done/finished/complete → COMPLETED
|
||||
- fail/error/err → FAILED
|
||||
- render/rendering → RENDERING
|
||||
- edit/editing → EDITING
|
||||
- 其他未知值 → DRAFT(兜底,不阻塞业务)
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in ("done", "success", "finished", "complete", "completed"):
|
||||
return cls.COMPLETED
|
||||
if normalized in ("fail", "failed", "error", "err"):
|
||||
return cls.FAILED
|
||||
if normalized in ("render", "rendering", "generating", "generating_video"):
|
||||
return cls.RENDERING
|
||||
if normalized in ("edit", "editing", "working"):
|
||||
return cls.EDITING
|
||||
return cls.DRAFT
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EditPlan:
|
||||
|
||||
@@ -31,6 +31,25 @@ class EditPlanClipStatus(StrEnum):
|
||||
RENDERED = "rendered" # 已渲染
|
||||
FAILED = "failed" # 渲染失败
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> "EditPlanClipStatus":
|
||||
"""兼容历史脏数据,避免枚举转换失败导致500。
|
||||
|
||||
- success/done/finished/complete/rendered → RENDERED
|
||||
- fail/error/err → FAILED
|
||||
- ready/available → READY
|
||||
- 其他未知值 → PENDING(兜底,不阻塞业务)
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in ("done", "success", "finished", "complete", "rendered", "render"):
|
||||
return cls.RENDERED
|
||||
if normalized in ("fail", "failed", "error", "err"):
|
||||
return cls.FAILED
|
||||
if normalized in ("ready", "available", "prepared"):
|
||||
return cls.READY
|
||||
return cls.PENDING
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EditPlanClip:
|
||||
|
||||
@@ -43,6 +43,28 @@ class GenerationTaskStatus(StrEnum):
|
||||
CANCELLED = "cancelled"
|
||||
"""已取消(用户取消或系统取消)"""
|
||||
|
||||
@classmethod
|
||||
def _missing_(cls, value: object) -> "GenerationTaskStatus":
|
||||
"""兼容历史脏数据,避免枚举转换失败导致500。
|
||||
|
||||
- success/done/finished/complete → COMPLETED
|
||||
- fail/error/err → FAILED
|
||||
- process/processing/run/running → RUNNING
|
||||
- cancel/canceled → CANCELLED
|
||||
- 其他未知值 → PENDING(兜底,不阻塞业务)
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in ("done", "success", "finished", "complete", "completed"):
|
||||
return cls.COMPLETED
|
||||
if normalized in ("fail", "failed", "error", "err"):
|
||||
return cls.FAILED
|
||||
if normalized in ("process", "processing", "run", "running", "in_progress"):
|
||||
return cls.RUNNING
|
||||
if normalized in ("cancel", "cancelled", "canceled"):
|
||||
return cls.CANCELLED
|
||||
return cls.PENDING
|
||||
|
||||
|
||||
# 终态集合
|
||||
TERMINAL_STATUSES = frozenset(
|
||||
|
||||
Executable
+118
@@ -0,0 +1,118 @@
|
||||
"""Storage 端口接口 — 统一存储服务的抽象定义。
|
||||
|
||||
所有存储实现(OSS、本地、S3等)都必须实现这个端口。
|
||||
API 和 Worker 都通过这个端口与存储交互,消除两套独立实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
|
||||
class StoragePort(ABC):
|
||||
"""统一存储服务端口。
|
||||
|
||||
定义所有存储后端必须实现的核心能力。
|
||||
具体实现见 packages.shared.storage.SharedStorageService。
|
||||
"""
|
||||
|
||||
# ── 基础上传 / 下载 ────────────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def upload_file(
|
||||
self,
|
||||
file_or_path: Union[str, Path, object],
|
||||
storage_key: str,
|
||||
content_type: str = "application/octet-stream",
|
||||
) -> str:
|
||||
"""上传文件到存储,返回公开 URL。
|
||||
|
||||
Args:
|
||||
file_or_path: 本地文件路径(str/Path)或类文件对象
|
||||
storage_key: 目标存储键
|
||||
content_type: MIME 类型
|
||||
|
||||
Returns:
|
||||
公开访问 URL
|
||||
"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def download_file(self, storage_key_or_url: str, local_path: Union[str, Path]) -> bool:
|
||||
"""从存储下载文件到本地。
|
||||
|
||||
自动识别输入:完整URL走HTTP下载(支持预签名),存储键走SDK下载。
|
||||
|
||||
Args:
|
||||
storage_key_or_url: 存储键或完整 URL
|
||||
local_path: 本地保存路径
|
||||
|
||||
Returns:
|
||||
True 成功,False 失败
|
||||
"""
|
||||
...
|
||||
|
||||
# ── URL 生成 ──────────────────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def get_url(self, storage_key: str) -> str:
|
||||
"""获取公开 URL。"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def get_download_url(self, storage_key_or_url: str, expires_seconds: int = 3600) -> str:
|
||||
"""获取预签名下载 URL(私有 bucket 用)。
|
||||
|
||||
未配置OSS时降级为公开URL。
|
||||
"""
|
||||
...
|
||||
|
||||
# ── 文件操作 ──────────────────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def delete_file(self, storage_key: str) -> None:
|
||||
"""删除文件(不抛异常)。"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def file_exists(self, storage_key: str) -> bool:
|
||||
"""检查文件是否存在。"""
|
||||
...
|
||||
|
||||
# ── 浏览器直传 ────────────────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def create_direct_upload_post(
|
||||
self,
|
||||
storage_key: str,
|
||||
content_type: str,
|
||||
max_size_bytes: int,
|
||||
expires_seconds: int,
|
||||
) -> dict[str, object]:
|
||||
"""创建浏览器直传 POST 表单(用于前端直传OSS)。"""
|
||||
...
|
||||
|
||||
# ── Asset 解析(Worker 用)────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def resolve_asset_path(self, asset_id: str, work_dir: Union[str, Path]) -> Optional[Path]:
|
||||
"""从 asset_id 解析到本地文件路径。
|
||||
|
||||
策略:本地路径 → 缓存命中 → OSS下载 → None
|
||||
缓存:SHA256(asset_id)[:16] 为文件名,避免重复下载
|
||||
"""
|
||||
...
|
||||
|
||||
# ── 工具方法 ──────────────────────────────────────────────────────
|
||||
|
||||
@abstractmethod
|
||||
def normalize_storage_key(self, storage_key_or_url: str) -> str:
|
||||
"""从 URL 提取存储键,URL decode 处理。"""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def diagnose(self) -> None:
|
||||
"""输出存储配置诊断日志。"""
|
||||
...
|
||||
+321
-61
@@ -1,4 +1,13 @@
|
||||
"""Shared OSS storage service for API and Worker."""
|
||||
"""统一存储服务 — API 和 Worker 共用的唯一存储入口。
|
||||
|
||||
实现 StoragePort 端口接口,整合原来分散在各处的存储能力:
|
||||
- API端 SharedStorageService 的全部能力(上传/下载/签名URL/直传POST)
|
||||
- Worker端 oss_helpers 的高级能力(分片上传/超时保护/HTTP下载/Asset路径解析)
|
||||
|
||||
所有服务都通过这个统一入口与存储交互,消除重复实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime as dt
|
||||
@@ -7,53 +16,70 @@ import hmac
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
import requests
|
||||
|
||||
try:
|
||||
import oss2
|
||||
except ImportError: # pragma: no cover
|
||||
oss2 = None
|
||||
|
||||
from packages.shared.config import get_shared_settings
|
||||
from packages.config import get_shared_settings
|
||||
from packages.ports.storage_port import StoragePort
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── OSS 高级配置(从 oss_helpers 合并)─────────────────────────────────
|
||||
OSS_CONNECT_TIMEOUT = 10 # 连接超时(秒)
|
||||
OSS_UPLOAD_TOTAL_TIMEOUT = 300 # 单文件上传总超时(秒)
|
||||
OSS_MULTIPART_THRESHOLD = 100 * 1024 * 1024 # 分片上传阈值:100MB
|
||||
OSS_PART_SIZE = 8 * 1024 * 1024 # 分片大小:8MB
|
||||
OSS_MULTIPART_NUM_THREADS = 3 # 分片上传并发数
|
||||
OSS_HTTP_DOWNLOAD_TIMEOUT = 300 # HTTP下载超时(秒)
|
||||
|
||||
class SharedStorageService:
|
||||
"""Shared OSS storage service."""
|
||||
|
||||
class SharedStorageService(StoragePort):
|
||||
"""统一存储服务 — 实现 StoragePort,API 和 Worker 共用。
|
||||
|
||||
整合了原 SharedStorageService + oss_helpers 的全部能力。
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
settings = get_shared_settings()
|
||||
self.bucket_name = settings.oss_bucket_name
|
||||
self.endpoint = settings.oss_endpoint
|
||||
self.public_url = f"https://{settings.oss_bucket_name}.{settings.oss_endpoint}"
|
||||
self.local_url_prefix = os.getenv("GENERATED_FILES_URL_PREFIX", "/generated-files")
|
||||
self.bucket = None
|
||||
|
||||
has_key_id = bool(settings.oss_access_key_id)
|
||||
has_key_secret = bool(settings.oss_access_key_secret)
|
||||
self.access_key_id = settings.oss_access_key_id
|
||||
self.access_key_secret = settings.oss_access_key_secret
|
||||
|
||||
has_key_id = bool(self.access_key_id)
|
||||
has_key_secret = bool(self.access_key_secret)
|
||||
|
||||
if has_key_id and has_key_secret:
|
||||
if oss2 is not None:
|
||||
try:
|
||||
# P0-2 修复:oss2.Bucket 的 endpoint 必须带 https:// 前缀,
|
||||
# 否则 sign_url 默认生成 HTTP URL。
|
||||
bucket_endpoint = settings.oss_endpoint
|
||||
# endpoint 不带 scheme 时补 https:// 前缀
|
||||
bucket_endpoint = self.endpoint
|
||||
if not bucket_endpoint.startswith(("http://", "https://")):
|
||||
bucket_endpoint = f"https://{bucket_endpoint}"
|
||||
auth = oss2.Auth(
|
||||
settings.oss_access_key_id,
|
||||
settings.oss_access_key_secret,
|
||||
)
|
||||
auth = oss2.Auth(self.access_key_id, self.access_key_secret)
|
||||
self.bucket = oss2.Bucket(
|
||||
auth,
|
||||
bucket_endpoint,
|
||||
settings.oss_bucket_name,
|
||||
self.bucket_name,
|
||||
connect_timeout=OSS_CONNECT_TIMEOUT,
|
||||
)
|
||||
logger.info(
|
||||
"OSS initialized: endpoint=%s bucket=%s",
|
||||
settings.oss_endpoint,
|
||||
settings.oss_bucket_name,
|
||||
self.endpoint,
|
||||
self.bucket_name,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error("Failed to initialize OSS bucket client: %s", error)
|
||||
@@ -67,12 +93,10 @@ class SharedStorageService:
|
||||
missing.append("OSS_ACCESS_KEY_SECRET")
|
||||
logger.error("OSS credentials not configured — missing: %s", ", ".join(missing))
|
||||
|
||||
self.access_key_id = settings.oss_access_key_id
|
||||
self.access_key_secret = settings.oss_access_key_secret
|
||||
self.endpoint = settings.oss_endpoint
|
||||
# ── 诊断 ───────────────────────────────────────────────────────────
|
||||
|
||||
def diagnose(self) -> None:
|
||||
"""启动诊断:输出 OSS 配置状态,帮助排查预签名 URL 问题。"""
|
||||
"""输出存储配置诊断日志。"""
|
||||
key_id_display = (
|
||||
f"{self.access_key_id[:4]}...{self.access_key_id[-4:]}" if len(self.access_key_id) > 8 else "(empty)"
|
||||
)
|
||||
@@ -86,89 +110,234 @@ class SharedStorageService:
|
||||
logger.error(
|
||||
"[OSS诊断] ❌ bucket=None — 预签名URL不可用!"
|
||||
"原因: OSS_ACCESS_KEY_ID/OSS_ACCESS_KEY_SECRET 未配置或 oss2 未安装。"
|
||||
"请检查服务器 .env 文件(如 /var/lib/xiaoxia-saas-staging/.env)"
|
||||
)
|
||||
else:
|
||||
logger.info("[OSS诊断] ✅ bucket 已配置,预签名URL可用")
|
||||
|
||||
# ── 工具方法 ───────────────────────────────────────────────────────
|
||||
|
||||
def _is_local_generated_url(self, storage_key_or_url: str) -> bool:
|
||||
parsed = urlparse(storage_key_or_url)
|
||||
path = parsed.path if parsed.scheme else storage_key_or_url
|
||||
return path.startswith(f"{self.local_url_prefix}/")
|
||||
|
||||
def _normalize_storage_key(self, storage_key_or_url: str) -> str:
|
||||
"""从 URL 提取存储键,并做 URL 解码。
|
||||
|
||||
防止 URL 编码的字符(空格=%20、中文=%XX)导致签名不匹配。
|
||||
"""
|
||||
if storage_key_or_url.startswith("http://") or storage_key_or_url.startswith("https://"):
|
||||
parsed = urlparse(storage_key_or_url)
|
||||
return unquote(parsed.path.lstrip("/"))
|
||||
return storage_key_or_url.lstrip("/")
|
||||
|
||||
def normalize_storage_key(self, storage_key_or_url: str) -> str:
|
||||
"""从 URL 提取存储键(公开方法)。"""
|
||||
return self._normalize_storage_key(storage_key_or_url)
|
||||
|
||||
# ── 上传 ───────────────────────────────────────────────────────────
|
||||
|
||||
def upload_file(
|
||||
self,
|
||||
file_or_path,
|
||||
file_or_path: Union[str, Path, object],
|
||||
storage_key: str,
|
||||
content_type: str = "application/octet-stream",
|
||||
) -> str:
|
||||
"""Upload file to OSS."""
|
||||
"""上传文件到存储,返回公开 URL(简单上传,API端原有行为)。
|
||||
|
||||
- 路径字符串 → bucket.put_object_from_file
|
||||
- 类文件对象 → bucket.put_object
|
||||
- bucket未配置 → 抛 RuntimeError
|
||||
"""
|
||||
if self.bucket is None:
|
||||
raise RuntimeError("OSS storage is not configured")
|
||||
|
||||
try:
|
||||
if isinstance(file_or_path, str):
|
||||
self.bucket.put_object_from_file(storage_key, file_or_path, headers={"Content-Type": content_type})
|
||||
if isinstance(file_or_path, (str, Path)):
|
||||
self.bucket.put_object_from_file(storage_key, str(file_or_path), headers={"Content-Type": content_type})
|
||||
else:
|
||||
file_or_path.seek(0)
|
||||
file_or_path.seek(0) # type: ignore[attr-defined]
|
||||
self.bucket.put_object(storage_key, file_or_path, headers={"Content-Type": content_type})
|
||||
return f"{self.public_url}/{storage_key}"
|
||||
except Exception as e:
|
||||
raise Exception(f"Failed to upload file to OSS: {e}") from e
|
||||
|
||||
def get_url(self, storage_key: str) -> str:
|
||||
"""Get public URL for a file."""
|
||||
return f"{self.public_url}/{storage_key}"
|
||||
def upload_file_smart(
|
||||
self,
|
||||
local_path: Union[str, Path],
|
||||
storage_key: str,
|
||||
) -> Optional[str]:
|
||||
"""智能上传:大文件自动分片+超时保护(从 oss_helpers 合并)。
|
||||
|
||||
def download_file(self, storage_key: str, local_path: str):
|
||||
"""Download file from OSS to local path."""
|
||||
- 大文件(>100MB)走分片上传,3 线程并发
|
||||
- 总超时 300s,防止网络异常时挂死
|
||||
- 成功返回 URL,失败返回 None(不抛异常)
|
||||
|
||||
Worker端 oss_helpers.upload_to_oss 的统一入口。
|
||||
"""
|
||||
local_path = Path(local_path)
|
||||
if not local_path.exists():
|
||||
logger.error("上传文件不存在: %s", local_path)
|
||||
return None
|
||||
if self.bucket is None:
|
||||
logger.error("OSS未配置,无法上传: %s", storage_key[:80])
|
||||
return None
|
||||
|
||||
result: dict = {"url": None, "error": None, "file_size": 0}
|
||||
done = threading.Event()
|
||||
|
||||
def _do_upload():
|
||||
try:
|
||||
try:
|
||||
file_size = local_path.stat().st_size
|
||||
result["file_size"] = file_size
|
||||
use_multipart = file_size >= OSS_MULTIPART_THRESHOLD
|
||||
except OSError:
|
||||
use_multipart = False
|
||||
file_size = 0
|
||||
|
||||
if use_multipart:
|
||||
logger.info(
|
||||
"大文件分片上传: storage_key=%s, size=%.1fMB, part_size=%dMB, threads=%d",
|
||||
storage_key[:80],
|
||||
file_size / 1024 / 1024,
|
||||
OSS_PART_SIZE // 1024 // 1024,
|
||||
OSS_MULTIPART_NUM_THREADS,
|
||||
)
|
||||
oss2.resumable_upload(
|
||||
self.bucket,
|
||||
storage_key,
|
||||
str(local_path),
|
||||
multipart_threshold=OSS_MULTIPART_THRESHOLD,
|
||||
part_size=OSS_PART_SIZE,
|
||||
num_threads=OSS_MULTIPART_NUM_THREADS,
|
||||
)
|
||||
else:
|
||||
self.bucket.put_object_from_file(storage_key, str(local_path))
|
||||
|
||||
result["url"] = f"{self.public_url}/{storage_key}"
|
||||
except Exception as e:
|
||||
result["error"] = e
|
||||
logger.exception("上传 OSS 失败: %s", storage_key)
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
upload_thread = threading.Thread(target=_do_upload, daemon=True)
|
||||
upload_thread.start()
|
||||
finished = done.wait(timeout=OSS_UPLOAD_TOTAL_TIMEOUT)
|
||||
|
||||
if not finished:
|
||||
logger.error(
|
||||
"OSS 上传超时(%.0fs),强制中止: storage_key=%s, size=%.1fMB",
|
||||
OSS_UPLOAD_TOTAL_TIMEOUT,
|
||||
storage_key[:80],
|
||||
result["file_size"] / 1024 / 1024 if result["file_size"] else 0,
|
||||
)
|
||||
return None
|
||||
|
||||
if result["error"]:
|
||||
return None
|
||||
|
||||
return result["url"]
|
||||
|
||||
# ── 下载 ───────────────────────────────────────────────────────────
|
||||
|
||||
def download_file(self, storage_key: str, local_path: Union[str, Path]) -> None:
|
||||
"""从 OSS 下载文件(简单下载,API端原有行为)。
|
||||
|
||||
bucket未配置 → 抛 RuntimeError
|
||||
"""
|
||||
if self.bucket is None:
|
||||
raise RuntimeError("OSS storage is not configured")
|
||||
|
||||
local_path = Path(local_path)
|
||||
os.makedirs(local_path.parent, exist_ok=True)
|
||||
try:
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
self.bucket.get_object_to_file(storage_key, local_path)
|
||||
self.bucket.get_object_to_file(self._normalize_storage_key(storage_key), str(local_path))
|
||||
except Exception as e:
|
||||
raise Exception(f"Failed to download file from OSS: {e}") from e
|
||||
|
||||
def download_asset(self, asset_storage_key: str, local_path: Union[str, Path]) -> bool:
|
||||
"""下载素材(从 oss_helpers 合并)。
|
||||
|
||||
自动识别输入类型:
|
||||
- 完整 URL → 走 HTTP 下载(支持预签名URL)
|
||||
- 存储键 → 走 oss2 SDK 下载
|
||||
|
||||
成功返回 True,失败返回 False(不抛异常)。
|
||||
"""
|
||||
local_path = Path(local_path)
|
||||
os.makedirs(local_path.parent, exist_ok=True)
|
||||
|
||||
# 完整URL走HTTP下载(兼容预签名URL)
|
||||
if asset_storage_key.startswith(("http://", "https://")):
|
||||
return self._download_via_http(asset_storage_key, local_path)
|
||||
|
||||
# OSS存储键走SDK
|
||||
if self.bucket is None:
|
||||
logger.error("OSS not configured, cannot download: %s", asset_storage_key[:80])
|
||||
return False
|
||||
try:
|
||||
self.bucket.get_object_to_file(self._normalize_storage_key(asset_storage_key), str(local_path))
|
||||
return local_path.exists() and local_path.stat().st_size > 0
|
||||
except Exception:
|
||||
logger.exception("下载素材失败: %s", asset_storage_key)
|
||||
return False
|
||||
|
||||
def _download_via_http(self, url: str, local_path: Path) -> bool:
|
||||
"""通过 HTTP 下载文件(支持预签名 URL)。
|
||||
|
||||
流式下载避免大文件内存溢出。
|
||||
"""
|
||||
try:
|
||||
resp = requests.get(url, stream=True, timeout=OSS_HTTP_DOWNLOAD_TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
with open(local_path, "wb") as f:
|
||||
for chunk in resp.iter_content(chunk_size=8 * 1024 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
return local_path.exists() and local_path.stat().st_size > 0
|
||||
except Exception:
|
||||
logger.exception("HTTP下载素材失败: %s", url[:100])
|
||||
return False
|
||||
|
||||
# ── URL 生成 ──────────────────────────────────────────────────────
|
||||
|
||||
def get_url(self, storage_key: str) -> str:
|
||||
"""获取公开 URL。"""
|
||||
return f"{self.public_url}/{storage_key}"
|
||||
|
||||
def get_download_url(self, storage_key_or_url: str, expires_seconds: int = 3600) -> str:
|
||||
"""Get signed download URL."""
|
||||
"""获取预签名下载 URL。
|
||||
|
||||
bucket未配置时降级为公开URL;本地产物URL直接返回。
|
||||
"""
|
||||
if self.bucket is None:
|
||||
if self._is_local_generated_url(storage_key_or_url):
|
||||
return storage_key_or_url
|
||||
logger.warning(
|
||||
"get_download_url: OSS bucket not configured, returning raw URL. storage_key_or_url=%s",
|
||||
"get_download_url: OSS bucket not configured, returning raw URL. key=%s",
|
||||
storage_key_or_url[:200],
|
||||
)
|
||||
return self.get_url(self._normalize_storage_key(storage_key_or_url))
|
||||
return self.get_url(self.normalize_storage_key(storage_key_or_url))
|
||||
|
||||
storage_key = self._normalize_storage_key(storage_key_or_url)
|
||||
storage_key = self.normalize_storage_key(storage_key_or_url)
|
||||
try:
|
||||
signed = self.bucket.sign_url("GET", storage_key, expires_seconds)
|
||||
logger.info(
|
||||
"get_download_url: signed URL generated. storage_key=%s url_prefix=%s",
|
||||
"get_download_url: signed URL generated. key=%s url_prefix=%s",
|
||||
storage_key[:80],
|
||||
signed[:60],
|
||||
)
|
||||
return signed
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"get_download_url: sign_url failed, falling back to raw URL. storage_key=%s",
|
||||
"get_download_url: sign_url failed, falling back to raw URL. key=%s",
|
||||
storage_key[:200],
|
||||
)
|
||||
return self.get_url(storage_key)
|
||||
|
||||
def _normalize_storage_key(self, storage_key_or_url: str) -> str:
|
||||
"""Extract storage key from URL.
|
||||
|
||||
从完整 URL 提取 OSS 存储键,并做 URL 解码 — 否则 URL 编码的字符
|
||||
(如空格=%20、中文=%XX)会导致 sign_url 计算的签名与 OSS 服务端
|
||||
不匹配(SignatureDoesNotMatch)。原始 key 传入时直接返回。
|
||||
"""
|
||||
if storage_key_or_url.startswith("http://") or storage_key_or_url.startswith("https://"):
|
||||
parsed = urlparse(storage_key_or_url)
|
||||
return unquote(parsed.path.lstrip("/"))
|
||||
return storage_key_or_url.lstrip("/")
|
||||
# ── 浏览器直传 POST ────────────────────────────────────────────────
|
||||
|
||||
def create_direct_upload_post(
|
||||
self,
|
||||
@@ -177,10 +346,10 @@ class SharedStorageService:
|
||||
max_size_bytes: int,
|
||||
expires_seconds: int,
|
||||
) -> dict[str, object]:
|
||||
"""Create browser direct upload POST form."""
|
||||
"""创建浏览器直传 POST 表单。"""
|
||||
if not self.access_key_id or not self.access_key_secret:
|
||||
raise RuntimeError("OSS storage is not configured")
|
||||
normalized_key = self._normalize_storage_key(storage_key)
|
||||
normalized_key = self.normalize_storage_key(storage_key)
|
||||
if not normalized_key.startswith("uploads/"):
|
||||
raise ValueError("direct upload key must be under uploads/")
|
||||
|
||||
@@ -193,12 +362,20 @@ class SharedStorageService:
|
||||
{"bucket": self.bucket_name},
|
||||
{"key": normalized_key},
|
||||
["content-length-range", 1, max_size_bytes],
|
||||
["starts-with", "$Content-Type", content_type.split("/", 1)[0] + "/" if "/" in content_type else ""],
|
||||
[
|
||||
"starts-with",
|
||||
"$Content-Type",
|
||||
content_type.split("/", 1)[0] + "/" if "/" in content_type else "",
|
||||
],
|
||||
],
|
||||
}
|
||||
encoded_policy = base64.b64encode(json.dumps(policy, separators=(",", ":")).encode("utf-8")).decode("ascii")
|
||||
signature = base64.b64encode(
|
||||
hmac.new(self.access_key_secret.encode("utf-8"), encoded_policy.encode("utf-8"), hashlib.sha1).digest()
|
||||
hmac.new(
|
||||
self.access_key_secret.encode("utf-8"),
|
||||
encoded_policy.encode("utf-8"),
|
||||
hashlib.sha1,
|
||||
).digest()
|
||||
).decode("ascii")
|
||||
|
||||
return {
|
||||
@@ -216,8 +393,10 @@ class SharedStorageService:
|
||||
},
|
||||
}
|
||||
|
||||
def delete_file(self, storage_key: str):
|
||||
"""Delete file from OSS."""
|
||||
# ── 文件操作 ───────────────────────────────────────────────────────
|
||||
|
||||
def delete_file(self, storage_key: str) -> None:
|
||||
"""删除文件(不抛异常)。"""
|
||||
if self.bucket is None:
|
||||
return
|
||||
try:
|
||||
@@ -226,17 +405,98 @@ class SharedStorageService:
|
||||
logger.warning("Failed to delete file from OSS", extra={"storage_key": storage_key, "error": str(error)})
|
||||
|
||||
def file_exists(self, storage_key: str) -> bool:
|
||||
"""Check if file exists."""
|
||||
"""检查文件是否存在。"""
|
||||
if self.bucket is None:
|
||||
return False
|
||||
return self.bucket.object_exists(storage_key)
|
||||
|
||||
# ── Asset 路径解析(Worker 用)────────────────────────────────────
|
||||
|
||||
def resolve_asset_path(self, asset_id: str, work_dir: Union[str, Path]) -> Optional[Path]:
|
||||
"""从 asset_id 解析到本地文件路径。
|
||||
|
||||
策略(按优先级):
|
||||
1. 本地绝对路径(在允许目录内)→ 直接返回
|
||||
2. work_dir 缓存命中 → 返回缓存路径
|
||||
3. 从OSS下载到缓存 → 返回下载路径
|
||||
4. 全部失败 → None
|
||||
|
||||
从 oss_helpers.resolve_asset_path 合并而来。
|
||||
"""
|
||||
# 延迟导入,避免循环依赖
|
||||
from video_processing.path_security import ( # type: ignore[import-not-found]
|
||||
PathSecurityError,
|
||||
get_allowed_local_dirs,
|
||||
is_in_allowed_dirs,
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
if not asset_id or not isinstance(asset_id, str):
|
||||
return None
|
||||
|
||||
work_dir = Path(work_dir)
|
||||
os.makedirs(work_dir, exist_ok=True)
|
||||
|
||||
# 空字节检测
|
||||
if "\x00" in asset_id:
|
||||
logger.warning("asset_id 包含空字节,拒绝: %s", asset_id[:50])
|
||||
return None
|
||||
|
||||
# 1. 本地绝对路径 — 必须在允许的目录内
|
||||
if asset_id.startswith("/") and os.path.exists(asset_id):
|
||||
try:
|
||||
resolved = Path(asset_id).resolve()
|
||||
if is_in_allowed_dirs(resolved, get_allowed_local_dirs()):
|
||||
return resolved
|
||||
else:
|
||||
logger.warning(
|
||||
"本地素材路径不在允许目录内,拒绝: %s (allowed=%s)",
|
||||
asset_id[:80],
|
||||
get_allowed_local_dirs(),
|
||||
)
|
||||
return None
|
||||
except (OSError, PathSecurityError):
|
||||
return None
|
||||
|
||||
# 2. 缓存命中(SHA256 hash 防路径遍历)
|
||||
cache_hash = hashlib.sha256(asset_id.encode()).hexdigest()[:16]
|
||||
safe_name = sanitize_filename(cache_hash)
|
||||
cached_path = work_dir / f"{safe_name}.mp4"
|
||||
if cached_path.exists() and cached_path.stat().st_size > 0:
|
||||
return cached_path
|
||||
|
||||
# 3. 从 OSS 下载(先标准化 key,防路径遍历注入)
|
||||
safe_key = self.normalize_storage_key(asset_id)
|
||||
if ".." in safe_key or safe_key.startswith("/"):
|
||||
logger.warning("asset_id 包含路径遍历模式,拒绝下载: %s", asset_id[:80])
|
||||
return None
|
||||
|
||||
if self.download_asset(safe_key, cached_path):
|
||||
return cached_path
|
||||
|
||||
return None
|
||||
|
||||
def resolve_asset_ids_to_paths(
|
||||
self,
|
||||
asset_ids: list[str],
|
||||
work_dir: Union[str, Path],
|
||||
) -> dict[str, Path]:
|
||||
"""批量解析 asset_id → 本地路径。"""
|
||||
result: dict[str, Path] = {}
|
||||
for aid in asset_ids:
|
||||
local_path = self.resolve_asset_path(aid, work_dir)
|
||||
if local_path:
|
||||
result[aid] = local_path
|
||||
return result
|
||||
|
||||
|
||||
# ── 单例管理 ────────────────────────────────────────────────────────────
|
||||
|
||||
_storage_service: Optional[SharedStorageService] = None
|
||||
|
||||
|
||||
def get_shared_storage_service() -> SharedStorageService:
|
||||
"""Get shared storage service instance (global singleton)."""
|
||||
"""获取统一存储服务单例。"""
|
||||
global _storage_service
|
||||
if _storage_service is None:
|
||||
_storage_service = SharedStorageService()
|
||||
@@ -244,7 +504,7 @@ def get_shared_storage_service() -> SharedStorageService:
|
||||
return _storage_service
|
||||
|
||||
|
||||
# Backward compatibility alias
|
||||
# 向后兼容别名
|
||||
def get_storage_service() -> SharedStorageService:
|
||||
"""Backward compatibility: returns shared storage service."""
|
||||
"""向后兼容:返回统一存储服务。"""
|
||||
return get_shared_storage_service()
|
||||
|
||||
@@ -34,7 +34,7 @@ FEISHU_APP_SECRET = os.environ.get("FEISHU_APP_SECRET", "")
|
||||
NOTIFY_BRANCHES = [b.strip() for b in os.environ.get("CHATOPS_NOTIFY_BRANCHES", "main,develop").split(",") if b.strip()]
|
||||
|
||||
# ── Webhook 服务配置 ──────────────────────────────────
|
||||
WEBHOOK_PORT = int(os.environ.get("CHATOPS_WEBHOOK_PORT", "8090"))
|
||||
CHATOPS_WEBHOOK_PORT = int(os.environ.get("CHATOPS_WEBHOOK_PORT", "8090"))
|
||||
WEBHOOK_SECRET = os.environ.get("CHATOPS_WEBHOOK_SECRET", "")
|
||||
|
||||
# ── 常量 ──────────────────────────────────────────────
|
||||
|
||||
@@ -417,7 +417,7 @@ def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="CI ChatOps Webhook 服务")
|
||||
parser.add_argument("--port", type=int, default=config.WEBHOOK_PORT, help="监听端口")
|
||||
parser.add_argument("--port", type=int, default=config.CHATOPS_WEBHOOK_PORT, help="监听端口")
|
||||
parser.add_argument("--host", default="0.0.0.0", help="监听地址")
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
Executable
+137
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
检查 Alembic migration 文件命名规范。
|
||||
|
||||
规则:
|
||||
1. 文件名必须以数字前缀开头(3位补零),如 001_xxx.py、052_add_table.py
|
||||
2. 数字前缀必须连续递增(与 check_migration_chain.py 一致,但只看文件名)
|
||||
3. 数字前缀后必须跟有描述性后缀(不能只有数字)
|
||||
4. 文件名使用小写+下划线(snake_case)
|
||||
5. revision 变量值必须与文件名数字前缀一致(可选带描述后缀)
|
||||
|
||||
用法:
|
||||
python3 scripts/ci/check_migration_naming.py [alembic_versions_dir]
|
||||
|
||||
默认目录: alembic/versions/
|
||||
|
||||
退出码:
|
||||
0 - 全部通过
|
||||
1 - 有命名违规
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 文件名格式: 3位数字_描述.py
|
||||
FILE_NAME_PATTERN = re.compile(r"^(\d{3})_[a-z][a-z0-9_]*\.py$")
|
||||
# 纯数字文件名(不允许)
|
||||
PURE_NUM_PATTERN = re.compile(r"^\d{3}\.py$")
|
||||
# revision 值的数字前缀
|
||||
REV_NUM_PATTERN = re.compile(r"^(\d{3})")
|
||||
# revision 变量行
|
||||
REV_LINE_PATTERN = re.compile(
|
||||
r'^\s*revision\s*(?::\s*str\s*)?=\s*["\']([^"\']+)["\']',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
|
||||
def check_naming(versions_dir: Path) -> list[str]:
|
||||
"""检查 migration 文件命名,返回错误列表。"""
|
||||
errors: list[str] = []
|
||||
|
||||
if not versions_dir.is_dir():
|
||||
return [f"目录不存在: {versions_dir}"]
|
||||
|
||||
py_files = sorted(f for f in versions_dir.iterdir() if f.suffix == ".py")
|
||||
if not py_files:
|
||||
return [f"目录下没有 migration 文件: {versions_dir}"]
|
||||
|
||||
print(f"检查 migration 文件命名: {versions_dir}")
|
||||
print(f"共 {len(py_files)} 个文件")
|
||||
print()
|
||||
|
||||
# 1. 文件名格式检查
|
||||
print("1. 文件名格式检查...")
|
||||
file_nums: list[int] = []
|
||||
for f in py_files:
|
||||
name = f.name
|
||||
if PURE_NUM_PATTERN.match(name):
|
||||
errors.append(f" ❌ {name}: 只有数字编号,缺少描述性后缀")
|
||||
continue
|
||||
m = FILE_NAME_PATTERN.match(name)
|
||||
if not m:
|
||||
errors.append(f" ❌ {name}: 命名格式不规范,应为 NNN_description.py " f"(3位数字前缀+下划线+小写描述)")
|
||||
continue
|
||||
file_nums.append(int(m.group(1)))
|
||||
|
||||
if not any("命名格式不规范" in e or "缺少描述性后缀" in e for e in errors):
|
||||
print(f" ✅ 全部 {len(py_files)} 个文件名格式正确")
|
||||
else:
|
||||
for e in errors:
|
||||
if "命名格式不规范" in e or "缺少描述性后缀" in e:
|
||||
print(e)
|
||||
|
||||
# 2. 编号连续性检查(基于文件名数字前缀)
|
||||
print()
|
||||
print("2. 编号连续性检查...")
|
||||
if file_nums:
|
||||
expected = set(range(min(file_nums), max(file_nums) + 1))
|
||||
actual = set(file_nums)
|
||||
missing = sorted(expected - actual)
|
||||
if missing:
|
||||
errors.append(f" ❌ 编号不连续,缺少: {', '.join(f'{n:03d}' for n in missing)}")
|
||||
print(f" ❌ 编号不连续,缺少 {len(missing)} 个: " f"{', '.join(f'{n:03d}' for n in missing)}")
|
||||
else:
|
||||
print(f" ✅ 编号连续({min(file_nums):03d} ~ {max(file_nums):03d})")
|
||||
|
||||
# 3. revision 变量与文件名前缀一致性检查
|
||||
print()
|
||||
print("3. revision变量与文件名一致性检查...")
|
||||
rev_mismatch = 0
|
||||
for f in py_files:
|
||||
m = FILE_NAME_PATTERN.match(f.name)
|
||||
if not m:
|
||||
continue # 格式不对的已经报过了
|
||||
file_num = m.group(1)
|
||||
content = f.read_text(encoding="utf-8")
|
||||
rev_match = REV_LINE_PATTERN.search(content)
|
||||
if not rev_match:
|
||||
errors.append(f" ❌ {f.name}: 未找到 revision 变量定义")
|
||||
rev_mismatch += 1
|
||||
continue
|
||||
rev_value = rev_match.group(1)
|
||||
rev_num_match = REV_NUM_PATTERN.match(rev_value)
|
||||
if not rev_num_match or rev_num_match.group(1) != file_num:
|
||||
errors.append(f" ❌ {f.name}: revision='{rev_value}' 与文件名前缀 {file_num} 不一致")
|
||||
rev_mismatch += 1
|
||||
|
||||
if rev_mismatch == 0:
|
||||
print(f" ✅ 全部 {len(py_files)} 个文件的 revision 与文件名一致")
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
versions_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("alembic/versions")
|
||||
|
||||
errors = check_naming(versions_dir)
|
||||
|
||||
print()
|
||||
if errors:
|
||||
print(f"❌ 发现 {len(errors)} 个命名问题")
|
||||
print()
|
||||
print("命名规范:")
|
||||
print(" - 文件名格式: NNN_description.py(3位数字前缀 + 下划线 + 小写描述)")
|
||||
print(" - 编号必须连续,不能跳号")
|
||||
print(" - revision 变量的数字前缀必须与文件名一致")
|
||||
return 1
|
||||
|
||||
print("✅ 所有 migration 文件命名规范检查通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -3,6 +3,9 @@
|
||||
# 包含:依赖安装、增量测试选择、覆盖率测试、diff覆盖率门禁
|
||||
set -eu
|
||||
|
||||
# 测试环境必须的密钥变量
|
||||
export JWT_SECRET_KEY=${JWT_SECRET_KEY:-test-jwt-secret-for-ci-only-2026}
|
||||
|
||||
JOB_NAME="${1:-Unit Tests}"
|
||||
|
||||
echo "=== CI Unit Tests 开始 ==="
|
||||
|
||||
Regular → Executable
+172
-33
@@ -1,15 +1,63 @@
|
||||
#!/bin/bash
|
||||
# CI Validate: Alembic迁移验证(并行Job 3/3)
|
||||
# 需要PostgreSQL数据库
|
||||
# CI Validate: Alembic迁移验证(升级版)
|
||||
# 检查项:
|
||||
# 1. migration文件命名规范检查
|
||||
# 2. migration编号链完整性检查
|
||||
# 3. upgrade head 升级验证(真实PG执行)
|
||||
# 4. downgrade -1 回滚验证
|
||||
# 5. alembic check 检测未生成migration的model变更
|
||||
#
|
||||
# 需要PostgreSQL数据库(共享PG或临时容器)
|
||||
|
||||
set -eu
|
||||
# 加载CI共享常量
|
||||
|
||||
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"
|
||||
# shellcheck source=ci_env.sh
|
||||
source "${SCRIPT_DIR}/ci_env.sh"
|
||||
|
||||
echo "=== CI Validate: Alembic迁移验证 ==="
|
||||
echo "=== CI Validate: Alembic迁移验证(升级版)==="
|
||||
echo ""
|
||||
|
||||
# ============================================================
|
||||
# 阶段0: 静态检查(不需要数据库,先快速失败)
|
||||
# ============================================================
|
||||
|
||||
echo "📋 阶段0: 静态检查(命名规范 + 链完整性)"
|
||||
echo ""
|
||||
|
||||
STATIC_FAILED=0
|
||||
|
||||
echo "0.1 检查 migration 文件命名规范..."
|
||||
if python3 scripts/ci/check_migration_naming.py alembic/versions; then
|
||||
echo " ✅ 命名规范检查通过"
|
||||
else
|
||||
echo " ❌ 命名规范检查失败"
|
||||
STATIC_FAILED=1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "0.2 检查 migration 编号链完整性..."
|
||||
if python3 scripts/ci/check_migration_chain.py alembic/versions; then
|
||||
echo " ✅ 编号链完整性检查通过"
|
||||
else
|
||||
echo " ❌ 编号链完整性检查失败"
|
||||
STATIC_FAILED=1
|
||||
fi
|
||||
|
||||
if [ "$STATIC_FAILED" -ne 0 ]; then
|
||||
echo ""
|
||||
echo "❌ 静态检查失败,请修复上述问题后重试"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✅ 静态检查全部通过"
|
||||
echo ""
|
||||
|
||||
# ============================================================
|
||||
# DooD模式检测:确定宿主机访问地址
|
||||
# ============================================================
|
||||
|
||||
# --- DooD模式检测:确定宿主机访问地址 ---
|
||||
detect_docker_host() {
|
||||
local test_port="${1:-${CI_LOCAL_PG_PORT}}"
|
||||
|
||||
@@ -63,20 +111,6 @@ except:
|
||||
return 1
|
||||
}
|
||||
|
||||
# 获取宿主机IP
|
||||
if [ -S /var/run/docker.sock ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host "${CI_SHARED_PG_PORT}")
|
||||
if [ "$DOCKER_HOST_IP" = "127.0.0.1" ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host 22)
|
||||
fi
|
||||
echo "检测到DooD模式,宿主机地址: $DOCKER_HOST_IP"
|
||||
else
|
||||
DOCKER_HOST_IP="127.0.0.1"
|
||||
echo "非DooD模式,使用 127.0.0.1"
|
||||
fi
|
||||
PG_HOST="$DOCKER_HOST_IP"
|
||||
echo "PG host: $PG_HOST"
|
||||
|
||||
# 指数退避TCP连接检查
|
||||
wait_tcp_ready() {
|
||||
local host="$1"
|
||||
@@ -96,8 +130,32 @@ wait_tcp_ready() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# 获取宿主机IP
|
||||
if [ -S /var/run/docker.sock ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host "${CI_SHARED_PG_PORT}")
|
||||
if [ "$DOCKER_HOST_IP" = "127.0.0.1" ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host 22)
|
||||
fi
|
||||
echo "检测到DooD模式,宿主机地址: $DOCKER_HOST_IP"
|
||||
else
|
||||
DOCKER_HOST_IP="127.0.0.1"
|
||||
echo "非DooD模式,使用 127.0.0.1"
|
||||
fi
|
||||
PG_HOST="$DOCKER_HOST_IP"
|
||||
echo "PG host: $PG_HOST"
|
||||
echo ""
|
||||
|
||||
USE_SHARED_PG="${CI_USE_SHARED_PG:-false}"
|
||||
|
||||
# ============================================================
|
||||
# 准备数据库
|
||||
# ============================================================
|
||||
|
||||
echo "🗄️ 阶段1: 准备测试数据库"
|
||||
echo ""
|
||||
|
||||
CI_DB_NAME="ci_migrate_${GITHUB_RUN_ID:-$$}"
|
||||
|
||||
if [ "$USE_SHARED_PG" = "true" ]; then
|
||||
# 使用常驻共享PG实例
|
||||
echo "使用常驻共享PG实例(CI_USE_SHARED_PG=true)"
|
||||
@@ -105,7 +163,6 @@ if [ "$USE_SHARED_PG" = "true" ]; then
|
||||
SHARED_PG_PORT="${CI_SHARED_PG_PORT}"
|
||||
SHARED_PG_USER="${CI_SHARED_PG_USER}"
|
||||
SHARED_PG_PASSWORD="${CI_SHARED_PG_PASSWORD}"
|
||||
CI_DB_NAME="ci_run_${GITHUB_RUN_ID:-$$}"
|
||||
|
||||
echo "等待共享PG连接就绪..."
|
||||
wait_tcp_ready "$SHARED_PG_HOST" "$SHARED_PG_PORT" 5
|
||||
@@ -124,13 +181,10 @@ conn.close()
|
||||
export DATABASE_URL="postgresql+psycopg://${SHARED_PG_USER}:${SHARED_PG_PASSWORD}@${SHARED_PG_HOST}:${SHARED_PG_PORT}/${CI_DB_NAME}"
|
||||
echo "✅ 共享PG数据库已创建: $CI_DB_NAME"
|
||||
|
||||
# 执行迁移
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ Alembic migrations applied successfully"
|
||||
|
||||
# 清理数据库
|
||||
echo "清理测试数据库: $CI_DB_NAME"
|
||||
PGPASSWORD="$SHARED_PG_PASSWORD" python3 -c "
|
||||
cleanup_db() {
|
||||
echo ""
|
||||
echo "清理测试数据库: $CI_DB_NAME"
|
||||
PGPASSWORD="$SHARED_PG_PASSWORD" python3 -c "
|
||||
import psycopg2
|
||||
conn = psycopg2.connect(host='$SHARED_PG_HOST', port=$SHARED_PG_PORT, user='$SHARED_PG_USER', password='$SHARED_PG_PASSWORD', dbname='postgres')
|
||||
conn.autocommit = True
|
||||
@@ -139,7 +193,8 @@ cur.execute(f'DROP DATABASE IF EXISTS \"$CI_DB_NAME\" WITH (FORCE)')
|
||||
cur.close()
|
||||
conn.close()
|
||||
" 2>/dev/null || echo "WARN: 数据库清理失败"
|
||||
echo "✅ 共享PG数据库已清理"
|
||||
echo "✅ 数据库已清理"
|
||||
}
|
||||
else
|
||||
# 使用临时PG容器(默认模式)
|
||||
echo "使用临时PG容器模式"
|
||||
@@ -176,12 +231,96 @@ else
|
||||
wait_tcp_ready "$PG_HOST" "$PG_PORT" 5
|
||||
echo "TCP connectivity to PostgreSQL confirmed on port $PG_PORT"
|
||||
|
||||
# 执行迁移
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ Alembic migrations applied successfully"
|
||||
cleanup_db() {
|
||||
docker rm -f "$PG_CONTAINER" 2>/dev/null || true
|
||||
}
|
||||
fi
|
||||
|
||||
docker rm -f "$PG_CONTAINER" 2>/dev/null || true
|
||||
trap cleanup_db EXIT
|
||||
|
||||
echo ""
|
||||
|
||||
# ============================================================
|
||||
# 阶段2: upgrade head 升级验证
|
||||
# ============================================================
|
||||
|
||||
echo "⬆️ 阶段2: upgrade head 升级验证"
|
||||
echo ""
|
||||
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ upgrade head 通过"
|
||||
echo ""
|
||||
|
||||
# ============================================================
|
||||
# 阶段3: downgrade -1 回滚验证
|
||||
# ============================================================
|
||||
|
||||
echo "⬇️ 阶段3: downgrade -1 回滚验证"
|
||||
echo ""
|
||||
|
||||
# 获取当前head版本号
|
||||
HEAD_REV=$(PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic current 2>&1 | awk '{print $1}' | head -1)
|
||||
echo "当前版本 (head): $HEAD_REV"
|
||||
|
||||
# 检查是否只有1个migration(baseline),downgrade -1会到base
|
||||
TOTAL_REVS=$(PYTHONPATH="$PWD/apps/api:$PWD" python3 -c "
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
config = Config('alembic.ini')
|
||||
script = ScriptDirectory.from_config(config)
|
||||
print(len(list(script.walk_revisions())))
|
||||
")
|
||||
|
||||
echo "总 migration 数量: $TOTAL_REVS"
|
||||
|
||||
if [ "$TOTAL_REVS" -le 1 ]; then
|
||||
echo "⚠️ 只有1个migration,跳过 downgrade 回滚验证(没有可回滚的版本)"
|
||||
else
|
||||
echo "执行 downgrade -1..."
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic downgrade -1
|
||||
echo "✅ downgrade -1 通过"
|
||||
|
||||
# 回滚后再升级回去,确保双向都通
|
||||
echo ""
|
||||
echo "重新 upgrade head 验证双向一致性..."
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ 重新 upgrade head 通过(双向验证完成)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== CI Validate: Alembic迁移验证 通过 ✅ ==="
|
||||
|
||||
# ============================================================
|
||||
# 阶段4: alembic check - 检测未生成migration的model变更
|
||||
# ============================================================
|
||||
|
||||
echo "🔍 阶段4: 检查是否有未生成migration的model变更"
|
||||
echo ""
|
||||
|
||||
# alembic check: 没有待生成的migration时退出码0,有变更时退出码1
|
||||
# 这里只检测,不阻断(警告模式),因为有些场景model变更不需要migration
|
||||
set +e
|
||||
CHECK_OUTPUT=$(PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic check 2>&1)
|
||||
CHECK_EXIT=$?
|
||||
set -e
|
||||
|
||||
if [ "$CHECK_EXIT" -eq 0 ]; then
|
||||
echo "✅ 没有检测到未生成migration的model变更"
|
||||
else
|
||||
if echo "$CHECK_OUTPUT" | grep -q "New upgrade operations detected"; then
|
||||
echo "⚠️ 检测到未生成migration的model变更!"
|
||||
echo ""
|
||||
echo "$CHECK_OUTPUT"
|
||||
echo ""
|
||||
echo "提示: 如果model变更是有意的且需要生成migration,请运行:"
|
||||
echo " alembic revision --autogenerate -m \"description\""
|
||||
echo "如果model变更不涉及数据库schema(如仅索引/约束重命名或纯业务逻辑),请确认后忽略此警告。"
|
||||
# 暂时不阻断,避免误报
|
||||
echo "(当前为警告模式,不阻断CI,后续稳定后可升级为阻断)"
|
||||
else
|
||||
echo "⚠️ alembic check 执行出错(非阻断)"
|
||||
echo "$CHECK_OUTPUT"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== CI Validate: Alembic迁移验证 全部通过 ✅ ==="
|
||||
|
||||
@@ -12,11 +12,23 @@ from packages.config.base import SharedSettings, get_cached_settings, reload_set
|
||||
def _reset_cache():
|
||||
"""每个测试前清空配置缓存,避免单例污染."""
|
||||
reload_settings_cache()
|
||||
# 保存关键环境变量(避免其他测试模块的全局污染)
|
||||
_saved_env = {}
|
||||
for key in ["JWT_SECRET_KEY", "DATABASE_URL", "USE_IN_MEMORY_DB", "APP_ENV"]:
|
||||
_saved_env[key] = os.environ.get(key)
|
||||
# 设置必要的环境变量,避免 JWT 校验失败
|
||||
os.environ["JWT_SECRET_KEY"] = "test-secret-key-for-unit-tests-only-12345"
|
||||
# 清除可能被其他模块污染的变量,确保默认值测试准确
|
||||
for key in ["DATABASE_URL", "APP_ENV"]:
|
||||
os.environ.pop(key, None)
|
||||
yield
|
||||
reload_settings_cache()
|
||||
os.environ.pop("JWT_SECRET_KEY", None)
|
||||
# 恢复所有保存的环境变量,避免污染其他测试模块
|
||||
for key, val in _saved_env.items():
|
||||
if val is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = val
|
||||
|
||||
|
||||
class TestSharedSettingsDefaults:
|
||||
|
||||
Executable
+90
@@ -0,0 +1,90 @@
|
||||
"""ASR 服务工厂单元测试."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from services.asr_service_factory import get_asr_service, reset_asr_service_cache
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_env():
|
||||
"""每个测试前后清理环境变量和缓存."""
|
||||
# 保存原始值
|
||||
old = os.environ.get("ASR_PROVIDER")
|
||||
reset_asr_service_cache()
|
||||
yield
|
||||
# 恢复
|
||||
if old is not None:
|
||||
os.environ["ASR_PROVIDER"] = old
|
||||
elif "ASR_PROVIDER" in os.environ:
|
||||
del os.environ["ASR_PROVIDER"]
|
||||
reset_asr_service_cache()
|
||||
|
||||
|
||||
class TestGetAsrService:
|
||||
"""ASR服务工厂测试."""
|
||||
|
||||
def test_default_no_provider_returns_none(self):
|
||||
"""未配置ASR_PROVIDER时返回None."""
|
||||
if "ASR_PROVIDER" in os.environ:
|
||||
del os.environ["ASR_PROVIDER"]
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is None
|
||||
|
||||
def test_empty_provider_returns_none(self):
|
||||
"""ASR_PROVIDER为空字符串时返回None."""
|
||||
os.environ["ASR_PROVIDER"] = ""
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is None
|
||||
|
||||
def test_whitespace_provider_returns_none(self):
|
||||
"""ASR_PROVIDER为空白字符时返回None."""
|
||||
os.environ["ASR_PROVIDER"] = " "
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is None
|
||||
|
||||
def test_mock_provider_returns_mock_service(self):
|
||||
"""mock provider返回MockASRService."""
|
||||
os.environ["ASR_PROVIDER"] = "mock"
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is not None
|
||||
# 检查类型名称
|
||||
assert type(result).__name__ == "MockASRService"
|
||||
|
||||
def test_mock_provider_case_insensitive(self):
|
||||
"""provider大小写不敏感."""
|
||||
os.environ["ASR_PROVIDER"] = "MOCK"
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is not None
|
||||
assert type(result).__name__ == "MockASRService"
|
||||
|
||||
def test_unknown_provider_returns_none(self):
|
||||
"""未知provider返回None(不阻断主流程)."""
|
||||
os.environ["ASR_PROVIDER"] = "unknown_provider_xyz"
|
||||
reset_asr_service_cache()
|
||||
result = get_asr_service()
|
||||
assert result is None
|
||||
|
||||
def test_singleton_caching(self):
|
||||
"""单例缓存有效,多次调用返回同一实例."""
|
||||
os.environ["ASR_PROVIDER"] = "mock"
|
||||
reset_asr_service_cache()
|
||||
s1 = get_asr_service()
|
||||
s2 = get_asr_service()
|
||||
assert s1 is s2
|
||||
|
||||
def test_reset_cache_clears_singleton(self):
|
||||
"""重置缓存后返回新实例."""
|
||||
os.environ["ASR_PROVIDER"] = "mock"
|
||||
reset_asr_service_cache()
|
||||
s1 = get_asr_service()
|
||||
reset_asr_service_cache()
|
||||
s2 = get_asr_service()
|
||||
assert s1 is not s2
|
||||
+94
-342
@@ -1,359 +1,111 @@
|
||||
"""BGM 混音单元测试.
|
||||
"""BGM混音单元测试 - 配置解析等纯逻辑."""
|
||||
|
||||
测试:
|
||||
- BGMConfig 配置解析与边界值
|
||||
- 预设 BGM 库查询
|
||||
- 纯 BGM 音频生成(端到端 ffmpeg)
|
||||
- BGM + 主音频混音(端到端 ffmpeg)
|
||||
- 淡入淡出效果
|
||||
- 音量边界(0 和 1)
|
||||
- sidechain 人声闪避
|
||||
"""
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "worker"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from video_processing.bgm_mixer import BGMConfig, build_bgm_only, mix_bgm_with_main, prepare_bgm_track
|
||||
from video_processing.render_audio import RenderContext
|
||||
|
||||
# ── Fixtures ──────────────────────────────────────────────────────────────────
|
||||
from video_processing.bgm_mixer import BGMConfig
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def work_dir(tmp_path):
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ctx(work_dir):
|
||||
return RenderContext(work_dir=work_dir, plan_id="test_plan")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def main_audio_path(work_dir):
|
||||
"""生成 10 秒测试主音频(正弦波模拟人声)。"""
|
||||
import subprocess
|
||||
|
||||
path = work_dir / "main.aac"
|
||||
# 生成 10 秒 440Hz 正弦波模拟主音频
|
||||
subprocess.run(
|
||||
[
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"sine=frequency=440:duration=10:sample_rate=44100",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"128k",
|
||||
str(path),
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
)
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bgm_audio_path(work_dir):
|
||||
"""生成 5 秒测试 BGM(更低频率模拟背景音乐)。"""
|
||||
import subprocess
|
||||
|
||||
path = work_dir / "bgm.aac"
|
||||
# 生成 5 秒 220Hz 正弦波模拟 BGM
|
||||
subprocess.run(
|
||||
[
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"sine=frequency=220:duration=5:sample_rate=44100",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"128k",
|
||||
str(path),
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
)
|
||||
return str(path)
|
||||
|
||||
|
||||
# ── BGMConfig 测试 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBGMConfig:
|
||||
"""BGMConfig 配置解析测试。"""
|
||||
class TestBGMConfigDefaults:
|
||||
"""BGMConfig 默认值测试."""
|
||||
|
||||
def test_default_values(self):
|
||||
cfg = BGMConfig(bgm_path="/tmp/bgm.mp3")
|
||||
assert cfg.volume == 0.3
|
||||
assert cfg.fade_in == 0.0
|
||||
assert cfg.fade_out == 0.0
|
||||
assert cfg.loop_enabled is True
|
||||
assert cfg.sidechain_enabled is False
|
||||
assert cfg.sidechain_ratio == 0.3
|
||||
|
||||
def test_from_config_dict(self):
|
||||
config_dict = {
|
||||
"enabled": True,
|
||||
"volume": 0.5,
|
||||
"fade_in": 2.0,
|
||||
"fade_out": 3.0,
|
||||
"loop_enabled": False,
|
||||
"sidechain_enabled": True,
|
||||
"sidechain_ratio": 0.5,
|
||||
}
|
||||
cfg = BGMConfig.from_config_dict("/bgm.mp3", config_dict)
|
||||
assert cfg.bgm_path == "/bgm.mp3"
|
||||
assert cfg.volume == 0.5
|
||||
assert cfg.fade_in == 2.0
|
||||
assert cfg.fade_out == 3.0
|
||||
assert cfg.loop_enabled is False
|
||||
assert cfg.sidechain_enabled is True
|
||||
assert cfg.sidechain_ratio == 0.5
|
||||
|
||||
def test_volume_clamped_by_config_schema(self):
|
||||
"""音量边界由 Pydantic Schema 在入口层保证,内部直接使用。"""
|
||||
from packages.domain.config_schemas import BGMConfig as BGMConfigSchema
|
||||
|
||||
# 边界值测试
|
||||
cfg = BGMConfigSchema(enabled=True, volume=0.0)
|
||||
assert cfg.volume == 0.0
|
||||
|
||||
cfg = BGMConfigSchema(enabled=True, volume=1.0)
|
||||
assert cfg.volume == 1.0
|
||||
|
||||
def test_fade_boundaries(self):
|
||||
from packages.domain.config_schemas import BGMConfig as BGMConfigSchema
|
||||
|
||||
# 0 是合法值
|
||||
cfg = BGMConfigSchema(fade_in=0, fade_out=0)
|
||||
assert cfg.fade_in == 0.0
|
||||
assert cfg.fade_out == 0.0
|
||||
"""默认值正确."""
|
||||
config = BGMConfig(bgm_path="/bgm.mp3")
|
||||
assert config.bgm_path == "/bgm.mp3"
|
||||
assert config.volume == 0.3
|
||||
assert config.fade_in == 0.0
|
||||
assert config.fade_out == 0.0
|
||||
assert config.loop_enabled is True
|
||||
assert config.sidechain_enabled is False
|
||||
assert config.sidechain_ratio == 0.3
|
||||
assert config.sidechain_attack == 0.02
|
||||
assert config.sidechain_release == 0.5
|
||||
assert config.sidechain_threshold == -25.0
|
||||
|
||||
|
||||
# ── 预设 BGM 库测试 ─────────────────────────────────────────────────────────
|
||||
class TestBGMConfigFromConfigDict:
|
||||
"""BGMConfig.from_config_dict 解析测试."""
|
||||
|
||||
def test_empty_dict_defaults(self):
|
||||
"""空字典用默认值."""
|
||||
config = BGMConfig.from_config_dict("/bgm.mp3", {})
|
||||
assert config.bgm_path == "/bgm.mp3"
|
||||
assert config.volume == 0.3
|
||||
assert config.loop_enabled is True
|
||||
assert config.sidechain_enabled is False
|
||||
|
||||
class TestPresetBGM:
|
||||
"""预设 BGM 库查询测试。"""
|
||||
def test_custom_volume(self):
|
||||
"""自定义音量."""
|
||||
config = BGMConfig.from_config_dict("/a.mp3", {"volume": 0.5})
|
||||
assert config.volume == 0.5
|
||||
|
||||
def test_total_count(self):
|
||||
from packages.domain.preset_bgm import PRESET_BGM_LIBRARY
|
||||
|
||||
assert len(PRESET_BGM_LIBRARY) >= 10
|
||||
|
||||
def test_get_preset_by_id(self):
|
||||
from packages.domain.preset_bgm import get_preset_bgm
|
||||
|
||||
bgm = get_preset_bgm("bgm_upbeat_001")
|
||||
assert bgm is not None
|
||||
assert bgm.name == "阳光清晨"
|
||||
assert bgm.style == "upbeat"
|
||||
|
||||
def test_get_preset_not_found(self):
|
||||
from packages.domain.preset_bgm import get_preset_bgm
|
||||
|
||||
assert get_preset_bgm("nonexistent") is None
|
||||
|
||||
def test_list_by_style(self):
|
||||
from packages.domain.preset_bgm import list_preset_bgm_by_style
|
||||
|
||||
upbeat = list_preset_bgm_by_style("upbeat")
|
||||
assert len(upbeat) >= 3
|
||||
assert all(b.style == "upbeat" for b in upbeat)
|
||||
|
||||
def test_search_by_keyword(self):
|
||||
from packages.domain.preset_bgm import search_preset_bgm
|
||||
|
||||
results = search_preset_bgm("钢琴")
|
||||
assert len(results) >= 2
|
||||
assert any("钢琴" in b.tags for b in results)
|
||||
|
||||
def test_all_presets_have_basic_fields(self):
|
||||
from packages.domain.preset_bgm import PRESET_BGM_LIBRARY
|
||||
|
||||
for bgm in PRESET_BGM_LIBRARY:
|
||||
assert bgm.id, f"{bgm.name} 缺少 id"
|
||||
assert bgm.name, "缺少 name"
|
||||
assert bgm.style, f"{bgm.name} 缺少 style"
|
||||
assert bgm.duration > 0, f"{bgm.name} 时长无效"
|
||||
|
||||
|
||||
# ── BGM 处理端到端测试 ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestPrepareBGMTrack:
|
||||
"""prepare_bgm_track 端到端测试。"""
|
||||
|
||||
def test_bgm_without_loop_short_duration(self, ctx, bgm_audio_path):
|
||||
"""BGM 比目标时长短且不循环 → 截断到目标时长(但前面没有足够内容)。"""
|
||||
bgm = BGMConfig(bgm_path=bgm_audio_path, volume=0.5, loop_enabled=False)
|
||||
result = prepare_bgm_track(ctx, bgm, target_duration=3.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_bgm_with_loop_longer_duration(self, ctx, bgm_audio_path):
|
||||
"""BGM 比目标时长短,循环铺满。"""
|
||||
bgm = BGMConfig(bgm_path=bgm_audio_path, volume=0.3, loop_enabled=True)
|
||||
# BGM 5 秒,目标 12 秒,需要循环 3 次
|
||||
result = prepare_bgm_track(ctx, bgm, target_duration=12.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_bgm_fade_in_and_fade_out(self, ctx, bgm_audio_path):
|
||||
"""BGM 淡入淡出效果。"""
|
||||
bgm = BGMConfig(
|
||||
bgm_path=bgm_audio_path,
|
||||
volume=0.5,
|
||||
fade_in=1.0,
|
||||
fade_out=1.0,
|
||||
loop_enabled=False,
|
||||
)
|
||||
result = prepare_bgm_track(ctx, bgm, target_duration=4.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_volume_zero(self, ctx, bgm_audio_path):
|
||||
"""音量为 0 时仍能正常处理。"""
|
||||
bgm = BGMConfig(bgm_path=bgm_audio_path, volume=0.0, loop_enabled=False)
|
||||
result = prepare_bgm_track(ctx, bgm, target_duration=3.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_volume_one(self, ctx, bgm_audio_path):
|
||||
"""音量为 1(最大)时正常处理。"""
|
||||
bgm = BGMConfig(bgm_path=bgm_audio_path, volume=1.0, loop_enabled=False)
|
||||
result = prepare_bgm_track(ctx, bgm, target_duration=3.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
|
||||
class TestMixBGMMain:
|
||||
"""BGM + 主音频混音端到端测试。"""
|
||||
|
||||
def test_simple_mix(self, ctx, main_audio_path, bgm_audio_path):
|
||||
"""普通 amix 混音(无 sidechain)。"""
|
||||
bgm = BGMConfig(
|
||||
bgm_path=bgm_audio_path,
|
||||
volume=0.3,
|
||||
loop_enabled=True,
|
||||
sidechain_enabled=False,
|
||||
)
|
||||
result = mix_bgm_with_main(ctx, Path(main_audio_path), bgm, target_duration=8.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_sidechain_mix(self, ctx, main_audio_path, bgm_audio_path):
|
||||
"""sidechain 人声闪避混音。"""
|
||||
bgm = BGMConfig(
|
||||
bgm_path=bgm_audio_path,
|
||||
volume=0.5,
|
||||
loop_enabled=True,
|
||||
sidechain_enabled=True,
|
||||
sidechain_ratio=0.3,
|
||||
sidechain_threshold=-25.0,
|
||||
sidechain_attack=0.02,
|
||||
sidechain_release=0.5,
|
||||
)
|
||||
result = mix_bgm_with_main(ctx, Path(main_audio_path), bgm, target_duration=8.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
def test_sidechain_max_ratio(self, ctx, main_audio_path, bgm_audio_path):
|
||||
"""sidechain 最大闪避比例。"""
|
||||
bgm = BGMConfig(
|
||||
bgm_path=bgm_audio_path,
|
||||
volume=0.5,
|
||||
loop_enabled=True,
|
||||
sidechain_enabled=True,
|
||||
sidechain_ratio=0.9, # 降低 90%
|
||||
)
|
||||
result = mix_bgm_with_main(ctx, Path(main_audio_path), bgm, target_duration=5.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
|
||||
class TestBuildBGMOnly:
|
||||
"""纯 BGM 模式测试。"""
|
||||
|
||||
def test_build_bgm_only(self, ctx, bgm_audio_path):
|
||||
"""只有 BGM、没有主音频时生成纯 BGM 音频。"""
|
||||
bgm = BGMConfig(
|
||||
bgm_path=bgm_audio_path,
|
||||
volume=0.3,
|
||||
fade_in=1.0,
|
||||
fade_out=1.0,
|
||||
loop_enabled=True,
|
||||
)
|
||||
result = build_bgm_only(ctx, bgm, target_duration=15.0)
|
||||
|
||||
assert result.exists()
|
||||
assert result.stat().st_size > 0
|
||||
|
||||
|
||||
# ── Config Schema 集成测试 ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestConfigSchemaIntegration:
|
||||
"""config schema 与渲染配置的集成测试。"""
|
||||
|
||||
def test_full_bgm_config(self):
|
||||
"""完整 BGM 配置能正确解析。"""
|
||||
from packages.domain.config_schemas import EditPlanConfigSchema, normalize_plan_config
|
||||
|
||||
config = normalize_plan_config(
|
||||
def test_fade_in_out(self):
|
||||
"""淡入淡出."""
|
||||
config = BGMConfig.from_config_dict(
|
||||
"/a.mp3",
|
||||
{
|
||||
"bgm": {
|
||||
"enabled": True,
|
||||
"source": "library",
|
||||
"asset_id": "bgm-asset-001",
|
||||
"volume": 0.4,
|
||||
"fade_in": 2.5,
|
||||
"fade_out": 3.0,
|
||||
"loop_enabled": True,
|
||||
"sidechain_enabled": True,
|
||||
"sidechain_ratio": 0.4,
|
||||
}
|
||||
}
|
||||
"fade_in": 2.0,
|
||||
"fade_out": 3.0,
|
||||
},
|
||||
)
|
||||
assert config.fade_in == 2.0
|
||||
assert config.fade_out == 3.0
|
||||
|
||||
bgm = config["bgm"]
|
||||
assert bgm["enabled"] is True
|
||||
assert bgm["volume"] == 0.4
|
||||
assert bgm["fade_in"] == 2.5
|
||||
assert bgm["fade_out"] == 3.0
|
||||
assert bgm["loop_enabled"] is True
|
||||
assert bgm["sidechain_enabled"] is True
|
||||
assert bgm["sidechain_ratio"] == 0.4
|
||||
# 默认值保留
|
||||
assert bgm["sidechain_attack"] == 0.02
|
||||
assert bgm["sidechain_release"] == 0.5
|
||||
assert bgm["sidechain_threshold"] == -25.0
|
||||
def test_loop_disabled(self):
|
||||
"""禁用循环."""
|
||||
config = BGMConfig.from_config_dict("/a.mp3", {"loop_enabled": False})
|
||||
assert config.loop_enabled is False
|
||||
|
||||
def test_bgm_disabled_by_default(self):
|
||||
"""默认 BGM 是关闭的。"""
|
||||
from packages.domain.config_schemas import normalize_plan_config
|
||||
def test_sidechain_enabled(self):
|
||||
"""启用人声闪避."""
|
||||
config = BGMConfig.from_config_dict("/a.mp3", {"sidechain_enabled": True})
|
||||
assert config.sidechain_enabled is True
|
||||
|
||||
config = normalize_plan_config({})
|
||||
assert config["bgm"]["enabled"] is False
|
||||
def test_sidechain_custom_params(self):
|
||||
"""闪避自定义参数."""
|
||||
config = BGMConfig.from_config_dict(
|
||||
"/a.mp3",
|
||||
{
|
||||
"sidechain_enabled": True,
|
||||
"sidechain_ratio": 0.5,
|
||||
"sidechain_attack": 0.05,
|
||||
"sidechain_release": 0.8,
|
||||
"sidechain_threshold": -30.0,
|
||||
},
|
||||
)
|
||||
assert config.sidechain_ratio == 0.5
|
||||
assert config.sidechain_attack == 0.05
|
||||
assert config.sidechain_release == 0.8
|
||||
assert config.sidechain_threshold == -30.0
|
||||
|
||||
def test_bgm_path_preserved(self):
|
||||
"""bgm_path保持不变."""
|
||||
config = BGMConfig.from_config_dict("/custom/path.mp3", {"volume": 0.5})
|
||||
assert config.bgm_path == "/custom/path.mp3"
|
||||
|
||||
def test_all_params_custom(self):
|
||||
"""所有参数自定义."""
|
||||
config = BGMConfig.from_config_dict(
|
||||
"/full.mp3",
|
||||
{
|
||||
"volume": 0.7,
|
||||
"fade_in": 1.5,
|
||||
"fade_out": 2.0,
|
||||
"loop_enabled": False,
|
||||
"sidechain_enabled": True,
|
||||
"sidechain_ratio": 0.4,
|
||||
"sidechain_attack": 0.03,
|
||||
"sidechain_release": 0.6,
|
||||
"sidechain_threshold": -20.0,
|
||||
},
|
||||
)
|
||||
assert config.volume == 0.7
|
||||
assert config.fade_in == 1.5
|
||||
assert config.fade_out == 2.0
|
||||
assert config.loop_enabled is False
|
||||
assert config.sidechain_enabled is True
|
||||
assert config.sidechain_ratio == 0.4
|
||||
assert config.sidechain_attack == 0.03
|
||||
assert config.sidechain_release == 0.6
|
||||
assert config.sidechain_threshold == -20.0
|
||||
|
||||
Executable
+210
@@ -0,0 +1,210 @@
|
||||
"""绿幕抠像引擎单元测试 - 配置解析等纯逻辑."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from video_processing.chroma_key_engine import (
|
||||
CHROMA_KEY_PRESETS,
|
||||
ChromaKeyConfig,
|
||||
)
|
||||
|
||||
|
||||
class TestChromaKeyConfigDefaults:
|
||||
"""默认配置测试."""
|
||||
|
||||
def test_default_values(self):
|
||||
"""默认值正确."""
|
||||
config = ChromaKeyConfig()
|
||||
assert config.enabled is False
|
||||
assert config.key_color == "#00FF00"
|
||||
assert config.similarity == 0.3
|
||||
assert config.blend == 0.1
|
||||
assert config.spill_suppress == 0.0
|
||||
|
||||
|
||||
class TestChromaKeyConfigFromDict:
|
||||
"""from_dict 配置解析测试."""
|
||||
|
||||
def test_none_returns_disabled(self):
|
||||
"""None 返回禁用配置."""
|
||||
config = ChromaKeyConfig.from_dict(None)
|
||||
assert config.enabled is False
|
||||
|
||||
def test_empty_dict_returns_disabled(self):
|
||||
"""空字典返回禁用."""
|
||||
config = ChromaKeyConfig.from_dict({})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_disabled_returns_disabled(self):
|
||||
"""enabled=False 返回禁用."""
|
||||
config = ChromaKeyConfig.from_dict({"enabled": False})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_enabled_default_values(self):
|
||||
"""启用时使用默认参数."""
|
||||
config = ChromaKeyConfig.from_dict({"enabled": True})
|
||||
assert config.enabled is True
|
||||
assert config.key_color == "#00FF00"
|
||||
assert config.similarity == 0.3
|
||||
assert config.blend == 0.1
|
||||
assert config.spill_suppress == 0.0
|
||||
|
||||
def test_custom_key_color(self):
|
||||
"""自定义抠像颜色."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"key_color": "#0000FF",
|
||||
}
|
||||
)
|
||||
assert config.key_color == "#0000FF"
|
||||
|
||||
def test_similarity_parsed(self):
|
||||
"""相似度解析."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"similarity": 0.5,
|
||||
}
|
||||
)
|
||||
assert config.similarity == 0.5
|
||||
|
||||
def test_similarity_clamped_min(self):
|
||||
"""相似度下限钳制."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"similarity": 0.001,
|
||||
}
|
||||
)
|
||||
assert config.similarity == 0.01
|
||||
|
||||
def test_similarity_clamped_max(self):
|
||||
"""相似度上限钳制."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"similarity": 2.0,
|
||||
}
|
||||
)
|
||||
assert config.similarity == 1.0
|
||||
|
||||
def test_blend_clamped_min(self):
|
||||
"""混合度下限钳制."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"blend": -0.5,
|
||||
}
|
||||
)
|
||||
assert config.blend == 0.0
|
||||
|
||||
def test_blend_clamped_max(self):
|
||||
"""混合度上限钳制."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"blend": 1.5,
|
||||
}
|
||||
)
|
||||
assert config.blend == 1.0
|
||||
|
||||
def test_spill_suppress_clamped(self):
|
||||
"""溢色抑制钳制."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"spill_suppress": 2.0,
|
||||
}
|
||||
)
|
||||
assert config.spill_suppress == 1.0
|
||||
|
||||
def test_invalid_similarity_falls_back(self):
|
||||
"""无效相似度回退到默认."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"similarity": "not_a_number",
|
||||
}
|
||||
)
|
||||
assert config.similarity == 0.3
|
||||
|
||||
def test_invalid_blend_falls_back(self):
|
||||
"""无效混合度回退."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"blend": "high",
|
||||
}
|
||||
)
|
||||
assert config.blend == 0.1
|
||||
|
||||
def test_key_color_stripped(self):
|
||||
"""颜色值去除首尾空格."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"key_color": " #FF0000 ",
|
||||
}
|
||||
)
|
||||
assert config.key_color == "#FF0000"
|
||||
|
||||
def test_all_params_custom(self):
|
||||
"""所有参数自定义."""
|
||||
config = ChromaKeyConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"key_color": "#0000FF",
|
||||
"similarity": 0.45,
|
||||
"blend": 0.15,
|
||||
"spill_suppress": 0.6,
|
||||
}
|
||||
)
|
||||
assert config.enabled is True
|
||||
assert config.key_color == "#0000FF"
|
||||
assert config.similarity == 0.45
|
||||
assert config.blend == 0.15
|
||||
assert config.spill_suppress == 0.6
|
||||
|
||||
|
||||
class TestHasEffect:
|
||||
"""has_effect 方法测试."""
|
||||
|
||||
def test_disabled_no_effect(self):
|
||||
"""禁用时无效果."""
|
||||
config = ChromaKeyConfig(enabled=False)
|
||||
assert config.has_effect() is False
|
||||
|
||||
def test_enabled_with_similarity_has_effect(self):
|
||||
"""启用且有相似度时有效果."""
|
||||
config = ChromaKeyConfig(enabled=True, similarity=0.3)
|
||||
assert config.has_effect() is True
|
||||
|
||||
def test_zero_similarity_no_effect(self):
|
||||
"""相似度为0时无效果."""
|
||||
config = ChromaKeyConfig(enabled=True, similarity=0.0)
|
||||
assert config.has_effect() is False
|
||||
|
||||
|
||||
class TestChromaKeyPresets:
|
||||
"""预设配置测试."""
|
||||
|
||||
def test_five_presets(self):
|
||||
"""5个预设."""
|
||||
assert len(CHROMA_KEY_PRESETS) == 5
|
||||
|
||||
def test_preset_names(self):
|
||||
"""预设名称正确."""
|
||||
assert "green_screen" in CHROMA_KEY_PRESETS
|
||||
assert "blue_screen" in CHROMA_KEY_PRESETS
|
||||
assert "red_screen" in CHROMA_KEY_PRESETS
|
||||
assert "precise_green" in CHROMA_KEY_PRESETS
|
||||
assert "soft_green" in CHROMA_KEY_PRESETS
|
||||
|
||||
def test_presets_have_required_keys(self):
|
||||
"""每个预设包含必要字段."""
|
||||
for name, preset in CHROMA_KEY_PRESETS.items():
|
||||
assert "key_color" in preset, f"{name} missing key_color"
|
||||
assert "similarity" in preset, f"{name} missing similarity"
|
||||
assert "blend" in preset, f"{name} missing blend"
|
||||
assert "spill_suppress" in preset, f"{name} missing spill_suppress"
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
"""classification 分类领域模型单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.classification import (
|
||||
AssetClassification,
|
||||
AssetLibraryKind,
|
||||
ClassificationJob,
|
||||
ClassificationJobStatus,
|
||||
ClassificationStatus,
|
||||
IngestJobStatus,
|
||||
)
|
||||
|
||||
|
||||
class TestAssetLibraryKind:
|
||||
def test_values(self):
|
||||
assert AssetLibraryKind.VIDEO.value == "video"
|
||||
assert AssetLibraryKind.VOICE.value == "voice"
|
||||
assert AssetLibraryKind.IMAGE.value == "image"
|
||||
|
||||
def test_is_str(self):
|
||||
assert isinstance(AssetLibraryKind.VIDEO, str)
|
||||
|
||||
|
||||
class TestIngestJobStatus:
|
||||
def test_values(self):
|
||||
assert IngestJobStatus.PENDING.value == "pending"
|
||||
assert IngestJobStatus.PROCESSING.value == "processing"
|
||||
assert IngestJobStatus.COMPLETED.value == "completed"
|
||||
assert IngestJobStatus.FAILED.value == "failed"
|
||||
|
||||
|
||||
class TestClassificationJobStatusMissing:
|
||||
"""ClassificationJobStatus._missing_ 兼容性测试."""
|
||||
|
||||
def test_normal_values(self):
|
||||
assert ClassificationJobStatus("pending") == ClassificationJobStatus.PENDING
|
||||
assert ClassificationJobStatus("processing") == ClassificationJobStatus.PROCESSING
|
||||
assert ClassificationJobStatus("completed") == ClassificationJobStatus.COMPLETED
|
||||
assert ClassificationJobStatus("failed") == ClassificationJobStatus.FAILED
|
||||
|
||||
@pytest.mark.parametrize("value", ["done", "success", "finished", "complete"])
|
||||
def test_completed_aliases(self, value):
|
||||
assert ClassificationJobStatus(value) == ClassificationJobStatus.COMPLETED
|
||||
|
||||
@pytest.mark.parametrize("value", ["fail", "error", "err"])
|
||||
def test_failed_aliases(self, value):
|
||||
assert ClassificationJobStatus(value) == ClassificationJobStatus.FAILED
|
||||
|
||||
@pytest.mark.parametrize("value", ["process", "processing", "running", "run"])
|
||||
def test_processing_aliases(self, value):
|
||||
assert ClassificationJobStatus(value) == ClassificationJobStatus.PROCESSING
|
||||
|
||||
@pytest.mark.parametrize("value", ["unknown", "foobar", ""])
|
||||
def test_unknown_fallback_to_pending(self, value):
|
||||
assert ClassificationJobStatus(value) == ClassificationJobStatus.PENDING
|
||||
|
||||
def test_none_fallback_to_pending(self):
|
||||
assert ClassificationJobStatus(None) == ClassificationJobStatus.PENDING # type: ignore[arg-type]
|
||||
|
||||
def test_case_insensitive_with_strip(self):
|
||||
assert ClassificationJobStatus(" DONE ") == ClassificationJobStatus.COMPLETED
|
||||
assert ClassificationJobStatus("ERROR") == ClassificationJobStatus.FAILED
|
||||
|
||||
def test_backward_compat_alias(self):
|
||||
"""ClassificationStatus 是 ClassificationJobStatus 的别名."""
|
||||
assert ClassificationStatus is ClassificationJobStatus
|
||||
assert ClassificationStatus("done") == ClassificationJobStatus.COMPLETED
|
||||
|
||||
|
||||
class TestAssetClassification:
|
||||
def test_values(self):
|
||||
assert AssetClassification.SCENIC.value == "scenic"
|
||||
assert AssetClassification.PRODUCT.value == "product"
|
||||
assert AssetClassification.PERSON.value == "person"
|
||||
assert AssetClassification.ANIMAL.value == "animal"
|
||||
assert AssetClassification.FOOD.value == "food"
|
||||
assert AssetClassification.TECH.value == "tech"
|
||||
assert AssetClassification.SPORT.value == "sport"
|
||||
assert AssetClassification.MUSIC.value == "music"
|
||||
assert AssetClassification.OTHER.value == "other"
|
||||
|
||||
|
||||
class TestClassificationJobCreate:
|
||||
def test_create_normal(self):
|
||||
job = ClassificationJob.create(project_id="proj1", asset_id="asset1")
|
||||
assert job.id
|
||||
assert job.project_id == "proj1"
|
||||
assert job.asset_id == "asset1"
|
||||
assert job.status == ClassificationJobStatus.PENDING
|
||||
assert job.classification == ""
|
||||
assert job.confidence == 0.0
|
||||
assert job.error_message == ""
|
||||
|
||||
def test_create_strips_whitespace(self):
|
||||
job = ClassificationJob.create(project_id=" proj1 ", asset_id=" asset1 ")
|
||||
assert job.project_id == "proj1"
|
||||
assert job.asset_id == "asset1"
|
||||
|
||||
def test_create_empty_project_id_raises(self):
|
||||
with pytest.raises(ValueError, match="project_id 不能为空"):
|
||||
ClassificationJob.create(project_id="", asset_id="a1")
|
||||
|
||||
def test_create_empty_asset_id_raises(self):
|
||||
with pytest.raises(ValueError, match="asset_id 不能为空"):
|
||||
ClassificationJob.create(project_id="p1", asset_id="")
|
||||
|
||||
def test_create_whitespace_project_id_raises(self):
|
||||
with pytest.raises(ValueError, match="project_id 不能为空"):
|
||||
ClassificationJob.create(project_id=" ", asset_id="a1")
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
job1 = ClassificationJob.create(project_id="p1", asset_id="a1")
|
||||
job2 = ClassificationJob.create(project_id="p1", asset_id="a2")
|
||||
assert job1.id != job2.id
|
||||
@@ -1,4 +1,4 @@
|
||||
"""滤镜调色引擎单元测试."""
|
||||
"""调色引擎单元测试 - 配置解析等纯逻辑."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -6,92 +6,19 @@ import pytest
|
||||
from video_processing.color_grade_engine import (
|
||||
DEFAULT_PARAMS,
|
||||
PARAM_RANGES,
|
||||
PRESET_BW,
|
||||
PRESET_CINEMA,
|
||||
PRESET_COOL,
|
||||
PRESET_DISPLAY_NAMES,
|
||||
PRESET_FILM,
|
||||
PRESET_FRESH,
|
||||
PRESET_JAPANESE,
|
||||
PRESET_PARAMS,
|
||||
PRESET_VINTAGE,
|
||||
PRESET_WARM,
|
||||
VALID_PRESETS,
|
||||
ColorGradeConfig,
|
||||
ColorGradeEngine,
|
||||
get_preset_names,
|
||||
get_preset_params,
|
||||
)
|
||||
|
||||
# ── 预设常量测试 ──────────────────────────────────────────────────────────────
|
||||
|
||||
class TestColorGradeConfigDefaults:
|
||||
"""默认配置测试."""
|
||||
|
||||
class TestPresetConstants:
|
||||
"""预设常量完整性测试."""
|
||||
|
||||
def test_eight_presets_defined(self):
|
||||
"""应该有8种预设."""
|
||||
assert len(PRESET_PARAMS) == 8
|
||||
assert len(PRESET_DISPLAY_NAMES) == 8
|
||||
|
||||
def test_all_presets_have_display_names(self):
|
||||
"""每个预设都应该有中文显示名."""
|
||||
for key in PRESET_PARAMS:
|
||||
assert key in PRESET_DISPLAY_NAMES
|
||||
assert PRESET_DISPLAY_NAMES[key] # 非空
|
||||
|
||||
def test_preset_params_have_all_keys(self):
|
||||
"""每个预设应该包含所有5个参数."""
|
||||
required_keys = {"brightness", "contrast", "saturation", "temperature", "hue"}
|
||||
for key, params in PRESET_PARAMS.items():
|
||||
assert required_keys.issubset(params.keys()), f"预设 {key} 缺少参数"
|
||||
|
||||
def test_preset_params_in_valid_range(self):
|
||||
"""所有预设参数应该在合法范围内."""
|
||||
for preset_name, params in PRESET_PARAMS.items():
|
||||
for param_name, value in params.items():
|
||||
min_val, max_val = PARAM_RANGES[param_name]
|
||||
assert (
|
||||
min_val <= value <= max_val
|
||||
), f"预设 {preset_name} 的 {param_name}={value} 超出范围 [{min_val}, {max_val}]"
|
||||
|
||||
def test_black_white_has_zero_saturation(self):
|
||||
"""黑白预设饱和度应该为0."""
|
||||
assert PRESET_PARAMS[PRESET_BW]["saturation"] == 0
|
||||
|
||||
def test_warm_preset_has_positive_temperature(self):
|
||||
"""暖色预设色温应该为正."""
|
||||
assert PRESET_PARAMS[PRESET_WARM]["temperature"] > 0
|
||||
|
||||
def test_cool_preset_has_negative_temperature(self):
|
||||
"""冷色预设色温应该为负."""
|
||||
assert PRESET_PARAMS[PRESET_COOL]["temperature"] < 0
|
||||
|
||||
|
||||
# ── ColorGradeConfig.from_dict 测试 ───────────────────────────────────────────
|
||||
|
||||
|
||||
class TestColorGradeConfigFromDict:
|
||||
"""配置字典解析测试."""
|
||||
|
||||
def test_none_config(self):
|
||||
"""None返回disabled."""
|
||||
config = ColorGradeConfig.from_dict(None)
|
||||
assert not config.enabled
|
||||
|
||||
def test_empty_dict(self):
|
||||
"""空字典返回disabled."""
|
||||
config = ColorGradeConfig.from_dict({})
|
||||
assert not config.enabled
|
||||
|
||||
def test_enabled_false(self):
|
||||
"""enabled=False返回disabled."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": False})
|
||||
assert not config.enabled
|
||||
|
||||
def test_enabled_only(self):
|
||||
"""只开enabled,无预设无自定义参数."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": True})
|
||||
assert config.enabled
|
||||
def test_default_values(self):
|
||||
"""默认值正确."""
|
||||
config = ColorGradeConfig()
|
||||
assert config.enabled is False
|
||||
assert config.preset == ""
|
||||
assert config.brightness is None
|
||||
assert config.contrast is None
|
||||
@@ -99,50 +26,83 @@ class TestColorGradeConfigFromDict:
|
||||
assert config.temperature is None
|
||||
assert config.hue is None
|
||||
|
||||
|
||||
class TestColorGradeConfigFromDict:
|
||||
"""from_dict 配置解析测试."""
|
||||
|
||||
def test_none_returns_disabled(self):
|
||||
"""None 返回禁用配置."""
|
||||
config = ColorGradeConfig.from_dict(None)
|
||||
assert config.enabled is False
|
||||
|
||||
def test_empty_dict_returns_disabled(self):
|
||||
"""空字典返回禁用."""
|
||||
config = ColorGradeConfig.from_dict({})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_disabled_returns_disabled(self):
|
||||
"""enabled=False 返回禁用."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": False})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_enabled_no_params(self):
|
||||
"""启用但无自定义参数."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": True})
|
||||
assert config.enabled is True
|
||||
assert config.preset == ""
|
||||
assert config.brightness is None
|
||||
|
||||
def test_with_preset(self):
|
||||
"""指定预设."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": True, "preset": PRESET_FRESH})
|
||||
assert config.enabled
|
||||
assert config.preset == PRESET_FRESH
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"preset": "fresh",
|
||||
}
|
||||
)
|
||||
assert config.enabled is True
|
||||
assert config.preset == "fresh"
|
||||
|
||||
def test_invalid_preset_ignored(self):
|
||||
"""无效预设名应该被忽略."""
|
||||
config = ColorGradeConfig.from_dict({"enabled": True, "preset": "invalid_preset"})
|
||||
assert config.preset == "" # 被清空
|
||||
"""无效预设被忽略."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"preset": "unknown_preset",
|
||||
}
|
||||
)
|
||||
assert config.preset == ""
|
||||
|
||||
def test_with_custom_params(self):
|
||||
"""自定义参数覆盖."""
|
||||
def test_custom_brightness(self):
|
||||
"""自定义亮度."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"brightness": 20,
|
||||
"contrast": -10,
|
||||
"saturation": 150,
|
||||
"temperature": 25,
|
||||
"hue": 30,
|
||||
}
|
||||
)
|
||||
assert config.enabled
|
||||
assert config.brightness == 20
|
||||
assert config.contrast == -10
|
||||
assert config.saturation == 150
|
||||
assert config.temperature == 25
|
||||
assert config.hue == 30
|
||||
assert config.brightness == 20.0
|
||||
|
||||
def test_string_numeric_values(self):
|
||||
"""字符串形式的数字应该能解析."""
|
||||
def test_custom_all_params(self):
|
||||
"""所有参数自定义."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"brightness": "20.5",
|
||||
"saturation": "150",
|
||||
"brightness": 10,
|
||||
"contrast": 15,
|
||||
"saturation": 120,
|
||||
"temperature": -5,
|
||||
"hue": 10,
|
||||
}
|
||||
)
|
||||
assert config.brightness == 20.5
|
||||
assert config.saturation == 150.0
|
||||
assert config.brightness == 10.0
|
||||
assert config.contrast == 15.0
|
||||
assert config.saturation == 120.0
|
||||
assert config.temperature == -5.0
|
||||
assert config.hue == 10.0
|
||||
|
||||
def test_invalid_value_returns_none(self):
|
||||
"""无效值应该返回None(不覆盖)."""
|
||||
def test_invalid_param_value_returns_none(self):
|
||||
"""无效参数值返回None(不覆盖)."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
@@ -151,422 +111,151 @@ class TestColorGradeConfigFromDict:
|
||||
)
|
||||
assert config.brightness is None
|
||||
|
||||
def test_null_param_returns_none(self):
|
||||
"""null参数值返回None."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"contrast": None,
|
||||
}
|
||||
)
|
||||
assert config.contrast is None
|
||||
|
||||
# ── ColorGradeConfig.resolve_params 测试 ──────────────────────────────────────
|
||||
def test_preset_with_custom_override(self):
|
||||
"""预设 + 自定义覆盖."""
|
||||
config = ColorGradeConfig.from_dict(
|
||||
{
|
||||
"enabled": True,
|
||||
"preset": "vintage",
|
||||
"brightness": 5,
|
||||
}
|
||||
)
|
||||
assert config.preset == "vintage"
|
||||
assert config.brightness == 5.0
|
||||
|
||||
|
||||
class TestResolveParams:
|
||||
"""参数解析与边界钳制测试."""
|
||||
"""resolve_params 参数解析测试."""
|
||||
|
||||
def test_default_params_when_empty(self):
|
||||
"""无预设无自定义时返回默认值."""
|
||||
config = ColorGradeConfig(enabled=True)
|
||||
def test_disabled_returns_defaults(self):
|
||||
"""禁用配置也返回默认参数."""
|
||||
config = ColorGradeConfig(enabled=False)
|
||||
params = config.resolve_params()
|
||||
for key, val in DEFAULT_PARAMS.items():
|
||||
assert params[key] == val
|
||||
|
||||
def test_preset_params_applied(self):
|
||||
"""预设参数应该被应用."""
|
||||
config = ColorGradeConfig(enabled=True, preset=PRESET_FRESH)
|
||||
def test_no_preset_no_custom_returns_defaults(self):
|
||||
"""无预设无自定义返回默认值."""
|
||||
config = ColorGradeConfig(enabled=True)
|
||||
params = config.resolve_params()
|
||||
preset = PRESET_PARAMS[PRESET_FRESH]
|
||||
for key, val in preset.items():
|
||||
assert params[key] == val
|
||||
for key, val in DEFAULT_PARAMS.items():
|
||||
assert abs(params[key] - val) < 0.001
|
||||
|
||||
def test_preset_applies_params(self):
|
||||
"""预设应用参数."""
|
||||
config = ColorGradeConfig(enabled=True, preset="fresh")
|
||||
params = config.resolve_params()
|
||||
# 清新预设亮度=8
|
||||
assert params["brightness"] == 8
|
||||
assert params["saturation"] == 120
|
||||
|
||||
def test_custom_overrides_preset(self):
|
||||
"""自定义参数应该覆盖预设值."""
|
||||
"""自定义参数覆盖预设."""
|
||||
config = ColorGradeConfig(
|
||||
enabled=True,
|
||||
preset=PRESET_FRESH,
|
||||
preset="fresh",
|
||||
brightness=50, # 覆盖预设的8
|
||||
)
|
||||
params = config.resolve_params()
|
||||
assert params["brightness"] == 50
|
||||
# 其他参数还是预设值
|
||||
assert params["contrast"] == PRESET_PARAMS[PRESET_FRESH]["contrast"]
|
||||
# 其他参数仍用预设值
|
||||
assert params["saturation"] == 120
|
||||
|
||||
def test_clamp_brightness_high(self):
|
||||
"""亮度超过上限应该被钳制."""
|
||||
def test_brightness_clamped(self):
|
||||
"""亮度边界钳制."""
|
||||
config = ColorGradeConfig(enabled=True, brightness=200)
|
||||
params = config.resolve_params()
|
||||
assert params["brightness"] == 100
|
||||
assert params["brightness"] == 100.0
|
||||
|
||||
def test_clamp_brightness_low(self):
|
||||
"""亮度低于下限应该被钳制."""
|
||||
config = ColorGradeConfig(enabled=True, brightness=-200)
|
||||
def test_saturation_clamped_low(self):
|
||||
"""饱和度下限钳制."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=-10)
|
||||
params = config.resolve_params()
|
||||
assert params["brightness"] == -100
|
||||
assert params["saturation"] == 0.0
|
||||
|
||||
def test_clamp_saturation_low(self):
|
||||
"""饱和度低于0应该被钳制到0."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=-50)
|
||||
params = config.resolve_params()
|
||||
assert params["saturation"] == 0
|
||||
|
||||
def test_clamp_saturation_high(self):
|
||||
"""饱和度超过200应该被钳制."""
|
||||
def test_saturation_clamped_high(self):
|
||||
"""饱和度上限钳制."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=300)
|
||||
params = config.resolve_params()
|
||||
assert params["saturation"] == 200
|
||||
assert params["saturation"] == 200.0
|
||||
|
||||
def test_clamp_hue_high(self):
|
||||
"""色调超过180应该被钳制."""
|
||||
config = ColorGradeConfig(enabled=True, hue=270)
|
||||
def test_hue_clamped(self):
|
||||
"""色调边界钳制."""
|
||||
config = ColorGradeConfig(enabled=True, hue=200)
|
||||
params = config.resolve_params()
|
||||
assert params["hue"] == 180
|
||||
assert params["hue"] == 180.0
|
||||
|
||||
def test_clamp_hue_low(self):
|
||||
"""色调低于-180应该被钳制."""
|
||||
config = ColorGradeConfig(enabled=True, hue=-270)
|
||||
def test_hue_negative_clamped(self):
|
||||
"""负色调边界钳制."""
|
||||
config = ColorGradeConfig(enabled=True, hue=-200)
|
||||
params = config.resolve_params()
|
||||
assert params["hue"] == -180
|
||||
assert params["hue"] == -180.0
|
||||
|
||||
def test_clamp_contrast(self):
|
||||
"""对比度越界应该被钳制."""
|
||||
config = ColorGradeConfig(enabled=True, contrast=150)
|
||||
def test_returns_all_five_params(self):
|
||||
"""返回所有5个参数."""
|
||||
config = ColorGradeConfig(enabled=True)
|
||||
params = config.resolve_params()
|
||||
assert params["contrast"] == 100
|
||||
|
||||
config2 = ColorGradeConfig(enabled=True, contrast=-150)
|
||||
params2 = config2.resolve_params()
|
||||
assert params2["contrast"] == -100
|
||||
|
||||
def test_clamp_temperature(self):
|
||||
"""色温越界应该被钳制."""
|
||||
config = ColorGradeConfig(enabled=True, temperature=150)
|
||||
params = config.resolve_params()
|
||||
assert params["temperature"] == 100
|
||||
|
||||
def test_preset_with_clamping(self):
|
||||
"""预设+自定义覆盖,自定义值超范围仍需钳制."""
|
||||
config = ColorGradeConfig(
|
||||
enabled=True,
|
||||
preset=PRESET_FRESH,
|
||||
brightness=999, # 超范围
|
||||
)
|
||||
params = config.resolve_params()
|
||||
assert params["brightness"] == 100 # 被钳制
|
||||
|
||||
|
||||
# ── ColorGradeConfig.has_effect 测试 ──────────────────────────────────────────
|
||||
assert set(params.keys()) == {"brightness", "contrast", "saturation", "temperature", "hue"}
|
||||
|
||||
|
||||
class TestHasEffect:
|
||||
"""是否有实际效果判断测试."""
|
||||
"""has_effect 方法测试."""
|
||||
|
||||
def test_disabled_has_no_effect(self):
|
||||
"""disabled的配置has_effect应该返回False."""
|
||||
config = ColorGradeConfig(enabled=False)
|
||||
assert not config.has_effect()
|
||||
|
||||
def test_default_params_no_effect(self):
|
||||
"""所有参数都是默认值时应该返回False."""
|
||||
def test_default_no_effect(self):
|
||||
"""默认配置无效果."""
|
||||
config = ColorGradeConfig(enabled=True)
|
||||
assert not config.has_effect()
|
||||
assert config.has_effect() is False
|
||||
|
||||
def test_brightness_change_has_effect(self):
|
||||
"""亮度变化应该有效果."""
|
||||
def test_with_preset_has_effect(self):
|
||||
"""有预设时有效果."""
|
||||
config = ColorGradeConfig(enabled=True, preset="cinema")
|
||||
assert config.has_effect() is True
|
||||
|
||||
def test_custom_brightness_has_effect(self):
|
||||
"""自定义亮度有效果."""
|
||||
config = ColorGradeConfig(enabled=True, brightness=10)
|
||||
assert config.has_effect()
|
||||
assert config.has_effect() is True
|
||||
|
||||
def test_saturation_100_no_effect(self):
|
||||
"""饱和度100是默认值,无效果."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=100)
|
||||
assert not config.has_effect()
|
||||
def test_disabled_still_checks_params(self):
|
||||
"""禁用也根据参数判断(结果仍可能有效果但不启用)."""
|
||||
# has_effect 只看参数,不看 enabled
|
||||
config = ColorGradeConfig(enabled=False, preset="warm")
|
||||
assert config.has_effect() is True
|
||||
|
||||
def test_saturation_not_100_has_effect(self):
|
||||
"""饱和度不等于100有效果."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=99)
|
||||
assert config.has_effect()
|
||||
|
||||
def test_preset_has_effect(self):
|
||||
"""预设通常有效果."""
|
||||
for preset in PRESET_PARAMS:
|
||||
config = ColorGradeConfig(enabled=True, preset=preset)
|
||||
assert config.has_effect(), f"预设 {preset} 应该有效果"
|
||||
|
||||
def test_custom_zero_override_no_effect(self):
|
||||
"""用预设但所有自定义值都设为默认值抵消 → 应该has_effect看实际值."""
|
||||
# 黑白预设饱和度=0,如果手动覆盖饱和度=100、其他都=默认值,则可能无效果
|
||||
config = ColorGradeConfig(
|
||||
enabled=True,
|
||||
preset=PRESET_BW,
|
||||
brightness=0,
|
||||
contrast=0,
|
||||
saturation=100,
|
||||
temperature=0,
|
||||
hue=0,
|
||||
)
|
||||
assert not config.has_effect()
|
||||
def test_black_white_preset_has_effect(self):
|
||||
"""黑白预设(饱和度=0)有效果."""
|
||||
config = ColorGradeConfig(enabled=True, preset="black_white")
|
||||
assert config.has_effect() is True
|
||||
|
||||
|
||||
# ── ColorGradeEngine 参数映射测试 ─────────────────────────────────────────────
|
||||
class TestPresets:
|
||||
"""预设常量测试."""
|
||||
|
||||
def test_eight_valid_presets(self):
|
||||
"""8个有效预设."""
|
||||
assert len(VALID_PRESETS) == 8
|
||||
|
||||
class TestParameterMapping:
|
||||
"""FFmpeg参数映射测试."""
|
||||
def test_preset_params_match_valid(self):
|
||||
"""所有预设都在有效列表中."""
|
||||
for name in PRESET_PARAMS:
|
||||
assert name in VALID_PRESETS
|
||||
|
||||
def test_brightness_mapping_zero(self):
|
||||
"""亮度0 → 0.0."""
|
||||
assert ColorGradeEngine._map_brightness(0) == 0.0
|
||||
def test_each_preset_has_all_params(self):
|
||||
"""每个预设包含所有5个参数."""
|
||||
for name, params in PRESET_PARAMS.items():
|
||||
for key in ["brightness", "contrast", "saturation", "temperature", "hue"]:
|
||||
assert key in params, f"{name} missing {key}"
|
||||
|
||||
def test_brightness_mapping_max(self):
|
||||
"""亮度100 → 1.0."""
|
||||
assert ColorGradeEngine._map_brightness(100) == 1.0
|
||||
|
||||
def test_brightness_mapping_min(self):
|
||||
"""亮度-100 → -1.0."""
|
||||
assert ColorGradeEngine._map_brightness(-100) == -1.0
|
||||
|
||||
def test_contrast_mapping_zero(self):
|
||||
"""对比度0 → 1.0(原始)."""
|
||||
assert ColorGradeEngine._map_contrast(0) == 1.0
|
||||
|
||||
def test_contrast_mapping_positive(self):
|
||||
"""正对比度应该 > 1.0."""
|
||||
assert ColorGradeEngine._map_contrast(50) == 1.5
|
||||
assert ColorGradeEngine._map_contrast(100) == 2.0
|
||||
|
||||
def test_contrast_mapping_negative(self):
|
||||
"""负对比度应该 < 1.0."""
|
||||
assert ColorGradeEngine._map_contrast(-50) == 0.5
|
||||
assert ColorGradeEngine._map_contrast(-100) == 0.0
|
||||
|
||||
def test_saturation_mapping_default(self):
|
||||
"""饱和度100 → 1.0."""
|
||||
assert ColorGradeEngine._map_saturation(100) == 1.0
|
||||
|
||||
def test_saturation_mapping_zero(self):
|
||||
"""饱和度0 → 0.0(黑白)."""
|
||||
assert ColorGradeEngine._map_saturation(0) == 0.0
|
||||
|
||||
def test_saturation_mapping_double(self):
|
||||
"""饱和度200 → 2.0."""
|
||||
assert ColorGradeEngine._map_saturation(200) == 2.0
|
||||
|
||||
def test_temperature_warm(self):
|
||||
"""暖色温应该红+蓝-."""
|
||||
red, green, blue = ColorGradeEngine._map_temperature(100)
|
||||
assert red > 0
|
||||
assert blue < 0
|
||||
|
||||
def test_temperature_cool(self):
|
||||
"""冷色温应该红-蓝+."""
|
||||
red, green, blue = ColorGradeEngine._map_temperature(-100)
|
||||
assert red < 0
|
||||
assert blue > 0
|
||||
|
||||
def test_temperature_zero(self):
|
||||
"""色温0应该全0."""
|
||||
red, green, blue = ColorGradeEngine._map_temperature(0)
|
||||
assert red == 0
|
||||
assert green == 0
|
||||
assert blue == 0
|
||||
|
||||
def test_hue_mapping_passthrough(self):
|
||||
"""色调直接透传."""
|
||||
assert ColorGradeEngine._map_hue(0) == 0
|
||||
assert ColorGradeEngine._map_hue(90) == 90
|
||||
assert ColorGradeEngine._map_hue(-45) == -45
|
||||
|
||||
|
||||
# ── ColorGradeEngine.build_filter 测试 ────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBuildFilter:
|
||||
"""滤镜字符串构建测试."""
|
||||
|
||||
def test_disabled_returns_empty(self):
|
||||
"""disabled配置返回空."""
|
||||
config = ColorGradeConfig(enabled=False)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert result == ""
|
||||
|
||||
def test_no_effect_returns_empty(self):
|
||||
"""无效果的配置返回空."""
|
||||
config = ColorGradeConfig(enabled=True)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert result == ""
|
||||
|
||||
def test_brightness_only(self):
|
||||
"""只有亮度调整."""
|
||||
config = ColorGradeConfig(enabled=True, brightness=20)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "eq=" in result
|
||||
assert "brightness=" in result
|
||||
assert "contrast=" not in result
|
||||
assert "saturation=" not in result
|
||||
|
||||
def test_contrast_only(self):
|
||||
"""只有对比度调整."""
|
||||
config = ColorGradeConfig(enabled=True, contrast=30)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "eq=" in result
|
||||
assert "contrast=" in result
|
||||
|
||||
def test_saturation_only(self):
|
||||
"""只有饱和度调整."""
|
||||
config = ColorGradeConfig(enabled=True, saturation=50)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "eq=" in result
|
||||
assert "saturation=" in result
|
||||
|
||||
def test_temperature_only(self):
|
||||
"""只有色温调整."""
|
||||
config = ColorGradeConfig(enabled=True, temperature=20)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "colorbalance=" in result
|
||||
# 暖色调应该有红通道调整
|
||||
assert "rs=" in result
|
||||
|
||||
def test_hue_only(self):
|
||||
"""只有色调调整."""
|
||||
config = ColorGradeConfig(enabled=True, hue=30)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "hue=h=" in result
|
||||
|
||||
def test_with_input_output_labels(self):
|
||||
"""带输入输出标签."""
|
||||
config = ColorGradeConfig(enabled=True, brightness=10)
|
||||
result = ColorGradeEngine.build_filter(config, input_label="[0:v]", output_label="[out]")
|
||||
assert result.startswith("[0:v]")
|
||||
assert result.endswith("[out]")
|
||||
|
||||
def test_preset_fresh_filter(self):
|
||||
"""清新预设应该生成eq滤镜."""
|
||||
config = ColorGradeConfig(enabled=True, preset=PRESET_FRESH)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "eq=" in result
|
||||
# 清新预设饱和度>100,应该有saturation
|
||||
assert "saturation=" in result
|
||||
|
||||
def test_preset_bw_filter(self):
|
||||
"""黑白预设应该有saturation=0."""
|
||||
config = ColorGradeConfig(enabled=True, preset=PRESET_BW)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "saturation=0.0" in result
|
||||
|
||||
def test_combined_params(self):
|
||||
"""多个参数组合."""
|
||||
config = ColorGradeConfig(
|
||||
enabled=True,
|
||||
brightness=15,
|
||||
contrast=20,
|
||||
saturation=130,
|
||||
temperature=10,
|
||||
hue=5,
|
||||
)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
# 应该有三个滤镜用逗号连接
|
||||
assert "eq=" in result
|
||||
assert "colorbalance=" in result
|
||||
assert "hue=" in result
|
||||
# 逗号分隔
|
||||
assert "," in result
|
||||
|
||||
def test_filter_chain_order(self):
|
||||
"""滤镜顺序应该是 eq → colorbalance → hue."""
|
||||
config = ColorGradeConfig(
|
||||
enabled=True,
|
||||
brightness=10,
|
||||
temperature=10,
|
||||
hue=10,
|
||||
)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
eq_pos = result.find("eq=")
|
||||
cb_pos = result.find("colorbalance=")
|
||||
hue_pos = result.find("hue=")
|
||||
assert eq_pos < cb_pos < hue_pos
|
||||
|
||||
def test_zero_temperature_no_colorbalance(self):
|
||||
"""色温为0不应该有colorbalance滤镜."""
|
||||
config = ColorGradeConfig(enabled=True, temperature=0, brightness=10)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "colorbalance" not in result
|
||||
|
||||
def test_zero_hue_no_hue_filter(self):
|
||||
"""色调为0不应该有hue滤镜."""
|
||||
config = ColorGradeConfig(enabled=True, hue=0, brightness=10)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert "hue=" not in result
|
||||
|
||||
def test_all_presets_generate_valid_filter(self):
|
||||
"""所有预设都应该能生成有效的非空滤镜."""
|
||||
for preset_name in PRESET_PARAMS:
|
||||
config = ColorGradeConfig(enabled=True, preset=preset_name)
|
||||
result = ColorGradeEngine.build_filter(config)
|
||||
assert result, f"预设 {preset_name} 应该生成非空滤镜"
|
||||
# 不应该有语法错误(连续冒号、空参数等)
|
||||
assert "::" not in result
|
||||
assert result[0] != ":"
|
||||
assert result[-1] != ":"
|
||||
|
||||
|
||||
# ── 便捷函数测试 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestHelperFunctions:
|
||||
"""便捷函数测试."""
|
||||
|
||||
def test_get_preset_names_returns_eight(self):
|
||||
"""应该返回8个预设."""
|
||||
names = get_preset_names()
|
||||
assert len(names) == 8
|
||||
# 每个是 (key, display_name) 元组
|
||||
for key, display in names:
|
||||
assert key in PRESET_PARAMS
|
||||
assert isinstance(display, str)
|
||||
assert display
|
||||
|
||||
def test_get_preset_params_valid(self):
|
||||
"""获取有效预设的参数."""
|
||||
params = get_preset_params(PRESET_FRESH)
|
||||
assert params is not None
|
||||
assert params == PRESET_PARAMS[PRESET_FRESH]
|
||||
|
||||
def test_get_preset_params_invalid(self):
|
||||
"""获取无效预设返回None."""
|
||||
params = get_preset_params("nonexistent")
|
||||
assert params is None
|
||||
|
||||
|
||||
# ── 分段调色(不同clip不同滤镜)概念验证 ──────────────────────────────────────
|
||||
|
||||
|
||||
class TestPerClipGrading:
|
||||
"""分段调色概念验证 — 不同配置生成不同滤镜."""
|
||||
|
||||
def test_different_presets_different_filters(self):
|
||||
"""不同预设应该生成不同的滤镜字符串."""
|
||||
configs = [
|
||||
ColorGradeConfig(enabled=True, preset=PRESET_FRESH),
|
||||
ColorGradeConfig(enabled=True, preset=PRESET_VINTAGE),
|
||||
ColorGradeConfig(enabled=True, preset=PRESET_BW),
|
||||
]
|
||||
filters = [ColorGradeEngine.build_filter(c) for c in configs]
|
||||
# 三个滤镜应该各不相同
|
||||
assert len(set(filters)) == 3
|
||||
|
||||
def test_same_preset_same_filter(self):
|
||||
"""相同配置应该生成相同滤镜(确定性)."""
|
||||
config1 = ColorGradeConfig(enabled=True, preset=PRESET_CINEMA)
|
||||
config2 = ColorGradeConfig(enabled=True, preset=PRESET_CINEMA)
|
||||
assert ColorGradeEngine.build_filter(config1) == ColorGradeEngine.build_filter(config2)
|
||||
|
||||
def test_custom_override_changes_filter(self):
|
||||
"""自定义覆盖应该改变滤镜."""
|
||||
base = ColorGradeConfig(enabled=True, preset=PRESET_FILM)
|
||||
modified = ColorGradeConfig(enabled=True, preset=PRESET_FILM, brightness=50)
|
||||
assert ColorGradeEngine.build_filter(base) != ColorGradeEngine.build_filter(modified)
|
||||
|
||||
def test_clips_with_and_without_grading(self):
|
||||
"""有的clip有调色有的没有,生成结果不同."""
|
||||
with_grade = ColorGradeConfig(enabled=True, preset=PRESET_WARM)
|
||||
without_grade = ColorGradeConfig(enabled=False)
|
||||
|
||||
filter_with = ColorGradeEngine.build_filter(with_grade, "[0:v]", "[v0]")
|
||||
filter_without = ColorGradeEngine.build_filter(without_grade, "[0:v]", "[v0]")
|
||||
|
||||
assert filter_with # 有调色应该非空
|
||||
# 无调色但带标签时应该走 copy 直通(保证标签传递)
|
||||
assert "[0:v]copy[v0]" in filter_without
|
||||
def test_param_ranges_defined(self):
|
||||
"""参数范围定义完整."""
|
||||
assert set(PARAM_RANGES.keys()) == {"brightness", "contrast", "saturation", "temperature", "hue"}
|
||||
|
||||
Executable
+311
@@ -0,0 +1,311 @@
|
||||
"""拼接引擎单元测试 - 配置解析等纯逻辑."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from video_processing.concat_engine import ConcatConfig, ConcatSegment
|
||||
|
||||
|
||||
class TestConcatSegmentDefaults:
|
||||
"""ConcatSegment 默认值测试."""
|
||||
|
||||
def test_default_values(self):
|
||||
"""默认值正确."""
|
||||
seg = ConcatSegment(video_path="/a.mp4")
|
||||
assert seg.video_path == "/a.mp4"
|
||||
assert seg.start_time == 0.0
|
||||
assert seg.duration == 0.0
|
||||
assert seg.has_audio is True
|
||||
|
||||
|
||||
class TestConcatSegmentFromDict:
|
||||
"""ConcatSegment.from_dict 测试."""
|
||||
|
||||
def test_basic_path(self):
|
||||
"""基本路径."""
|
||||
seg = ConcatSegment.from_dict({"video_path": "/a.mp4"})
|
||||
assert seg.video_path == "/a.mp4"
|
||||
assert seg.start_time == 0.0
|
||||
assert seg.duration == 0.0
|
||||
|
||||
def test_custom_start_time(self):
|
||||
"""自定义开始时间."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"start_time": 5.0,
|
||||
}
|
||||
)
|
||||
assert seg.start_time == 5.0
|
||||
|
||||
def test_custom_duration(self):
|
||||
"""自定义时长."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"duration": 10.0,
|
||||
}
|
||||
)
|
||||
assert seg.duration == 10.0
|
||||
|
||||
def test_start_time_negative_clamped(self):
|
||||
"""负开始时间钳制到0."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"start_time": -5.0,
|
||||
}
|
||||
)
|
||||
assert seg.start_time == 0.0
|
||||
|
||||
def test_duration_negative_clamped(self):
|
||||
"""负时长钳制到0."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"duration": -3.0,
|
||||
}
|
||||
)
|
||||
assert seg.duration == 0.0
|
||||
|
||||
def test_invalid_start_time_falls_back(self):
|
||||
"""无效start_time回退到0."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"start_time": "invalid",
|
||||
}
|
||||
)
|
||||
assert seg.start_time == 0.0
|
||||
|
||||
def test_invalid_duration_falls_back(self):
|
||||
"""无效duration回退到0."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"duration": "not_a_number",
|
||||
}
|
||||
)
|
||||
assert seg.duration == 0.0
|
||||
|
||||
def test_no_audio(self):
|
||||
"""无音频."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/a.mp4",
|
||||
"has_audio": False,
|
||||
}
|
||||
)
|
||||
assert seg.has_audio is False
|
||||
|
||||
def test_full_config(self):
|
||||
"""完整配置."""
|
||||
seg = ConcatSegment.from_dict(
|
||||
{
|
||||
"video_path": "/video.mp4",
|
||||
"start_time": 2.5,
|
||||
"duration": 15.0,
|
||||
"has_audio": False,
|
||||
}
|
||||
)
|
||||
assert seg.video_path == "/video.mp4"
|
||||
assert seg.start_time == 2.5
|
||||
assert seg.duration == 15.0
|
||||
assert seg.has_audio is False
|
||||
|
||||
|
||||
class TestConcatConfigDefaults:
|
||||
"""ConcatConfig 默认值测试."""
|
||||
|
||||
def test_default_values(self):
|
||||
"""默认值正确."""
|
||||
config = ConcatConfig()
|
||||
assert config.segments == []
|
||||
assert config.output_width == 0
|
||||
assert config.output_height == 0
|
||||
assert config.output_fps == 0.0
|
||||
assert config.force_reencode is False
|
||||
assert config.transition == "none"
|
||||
assert config.transition_duration == 0.3
|
||||
|
||||
|
||||
class TestConcatConfigFromConfigDict:
|
||||
"""ConcatConfig.from_config_dict 测试."""
|
||||
|
||||
def test_none_returns_default(self):
|
||||
"""None返回默认配置."""
|
||||
config = ConcatConfig.from_config_dict(None)
|
||||
assert config.segments == []
|
||||
|
||||
def test_empty_dict_returns_default(self):
|
||||
"""空dict返回默认."""
|
||||
config = ConcatConfig.from_config_dict({})
|
||||
assert config.segments == []
|
||||
|
||||
def test_single_segment(self):
|
||||
"""单片段."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
}
|
||||
)
|
||||
assert len(config.segments) == 1
|
||||
assert config.segments[0].video_path == "/a.mp4"
|
||||
|
||||
def test_multiple_segments(self):
|
||||
"""多片段."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [
|
||||
{"video_path": "/a.mp4", "start_time": 1.0},
|
||||
{"video_path": "/b.mp4", "duration": 5.0},
|
||||
{"video_path": "/c.mp4"},
|
||||
],
|
||||
}
|
||||
)
|
||||
assert len(config.segments) == 3
|
||||
assert config.segments[0].start_time == 1.0
|
||||
assert config.segments[1].duration == 5.0
|
||||
|
||||
def test_skips_no_path(self):
|
||||
"""跳过无video_path的片段."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [
|
||||
{"video_path": "/a.mp4"},
|
||||
{"other": "value"},
|
||||
{"video_path": ""},
|
||||
],
|
||||
}
|
||||
)
|
||||
assert len(config.segments) == 1
|
||||
|
||||
def test_segments_not_list_ignored(self):
|
||||
"""segments不是列表忽略."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": "not_a_list",
|
||||
}
|
||||
)
|
||||
assert config.segments == []
|
||||
|
||||
def test_output_size(self):
|
||||
"""输出尺寸."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
"output_width": 1920,
|
||||
"output_height": 1080,
|
||||
}
|
||||
)
|
||||
assert config.output_width == 1920
|
||||
assert config.output_height == 1080
|
||||
|
||||
def test_negative_output_size_clamped(self):
|
||||
"""负输出尺寸钳制到0."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
"output_width": -100,
|
||||
"output_height": -50,
|
||||
}
|
||||
)
|
||||
assert config.output_width == 0
|
||||
assert config.output_height == 0
|
||||
|
||||
def test_invalid_output_size_falls_back(self):
|
||||
"""无效输出尺寸回退."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
"output_width": "wide",
|
||||
"output_fps": "sixty",
|
||||
}
|
||||
)
|
||||
assert config.output_width == 0
|
||||
assert config.output_fps == 0.0
|
||||
|
||||
def test_output_fps(self):
|
||||
"""输出帧率."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
"output_fps": 60.0,
|
||||
}
|
||||
)
|
||||
assert config.output_fps == 60.0
|
||||
|
||||
def test_force_reencode(self):
|
||||
"""强制重新编码."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}],
|
||||
"force_reencode": True,
|
||||
}
|
||||
)
|
||||
assert config.force_reencode is True
|
||||
|
||||
def test_transition_config(self):
|
||||
"""转场配置."""
|
||||
config = ConcatConfig.from_config_dict(
|
||||
{
|
||||
"segments": [{"video_path": "/a.mp4"}, {"video_path": "/b.mp4"}],
|
||||
"transition": "crossfade",
|
||||
"transition_duration": 1.0,
|
||||
}
|
||||
)
|
||||
assert config.transition == "crossfade"
|
||||
assert config.transition_duration == 1.0
|
||||
|
||||
def test_non_dict_config_returns_default(self):
|
||||
"""非dict配置返回默认."""
|
||||
config = ConcatConfig.from_config_dict("not_a_dict")
|
||||
assert config.segments == []
|
||||
|
||||
|
||||
class TestHasEffect:
|
||||
"""has_effect 属性测试."""
|
||||
|
||||
def test_no_segments_no_effect(self):
|
||||
"""无片段无效果."""
|
||||
config = ConcatConfig()
|
||||
assert config.has_effect is False
|
||||
|
||||
def test_one_segment_no_effect(self):
|
||||
"""单片段无效果(拼接至少需要2段)."""
|
||||
config = ConcatConfig(
|
||||
segments=[
|
||||
ConcatSegment(video_path="/a.mp4"),
|
||||
]
|
||||
)
|
||||
assert config.has_effect is False
|
||||
|
||||
def test_two_segments_has_effect(self):
|
||||
"""两段及以上有效果."""
|
||||
config = ConcatConfig(
|
||||
segments=[
|
||||
ConcatSegment(video_path="/a.mp4"),
|
||||
ConcatSegment(video_path="/b.mp4"),
|
||||
]
|
||||
)
|
||||
assert config.has_effect is True
|
||||
|
||||
|
||||
class TestTotalSegments:
|
||||
"""total_segments 属性测试."""
|
||||
|
||||
def test_no_segments(self):
|
||||
"""零片段."""
|
||||
config = ConcatConfig()
|
||||
assert config.total_segments == 0
|
||||
|
||||
def test_three_segments(self):
|
||||
"""三个片段."""
|
||||
config = ConcatConfig(
|
||||
segments=[
|
||||
ConcatSegment(video_path="/a.mp4"),
|
||||
ConcatSegment(video_path="/b.mp4"),
|
||||
ConcatSegment(video_path="/c.mp4"),
|
||||
]
|
||||
)
|
||||
assert config.total_segments == 3
|
||||
Executable
+510
@@ -0,0 +1,510 @@
|
||||
"""config_schemas 领域层单元测试 - 配置 schema / 枚举 / 标准化函数"""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from packages.domain.config_schemas import (
|
||||
DEFAULT_EDIT_PLAN_CONFIG,
|
||||
DEFAULT_EDIT_TEMPLATE_CONFIG,
|
||||
BGMConfig,
|
||||
BGMSource,
|
||||
CoverConfig,
|
||||
CoverType,
|
||||
EditPlanConfigSchema,
|
||||
EditTemplateConfigSchema,
|
||||
ExportConfig,
|
||||
FilterConfig,
|
||||
ShadowConfig,
|
||||
StrokeConfig,
|
||||
SubtitleConfig,
|
||||
TextAnimation,
|
||||
TextPosition,
|
||||
TitleConfig,
|
||||
normalize_plan_config,
|
||||
normalize_template_config,
|
||||
)
|
||||
|
||||
|
||||
class TestEnums:
|
||||
"""枚举类型测试"""
|
||||
|
||||
def test_cover_type_values(self):
|
||||
assert CoverType.AI_FRAME == "ai_frame"
|
||||
assert CoverType.MANUAL == "manual"
|
||||
assert CoverType.UPLOAD == "upload"
|
||||
assert CoverType.AI_REGENERATE == "ai_regenerate"
|
||||
|
||||
def test_text_position_values(self):
|
||||
assert TextPosition.TOP == "top"
|
||||
assert TextPosition.CENTER == "center"
|
||||
assert TextPosition.BOTTOM == "bottom"
|
||||
|
||||
def test_text_animation_values(self):
|
||||
assert TextAnimation.NONE == "none"
|
||||
assert TextAnimation.FADE_IN == "fade_in"
|
||||
assert TextAnimation.SLIDE_UP == "slide_up"
|
||||
assert TextAnimation.SLIDE_DOWN == "slide_down"
|
||||
assert TextAnimation.SCALE == "scale"
|
||||
|
||||
def test_bgm_source_values(self):
|
||||
assert BGMSource.LIBRARY == "library"
|
||||
assert BGMSource.UPLOAD == "upload"
|
||||
assert BGMSource.AI_RECOMMEND == "ai_recommend"
|
||||
|
||||
def test_enums_are_str_enum(self):
|
||||
"""枚举都是 str 类型"""
|
||||
assert isinstance(CoverType.AI_FRAME, str)
|
||||
assert isinstance(TextPosition.TOP, str)
|
||||
assert isinstance(TextAnimation.FADE_IN, str)
|
||||
assert isinstance(BGMSource.LIBRARY, str)
|
||||
|
||||
|
||||
class TestStrokeConfig:
|
||||
"""StrokeConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = StrokeConfig()
|
||||
assert config.enabled is False
|
||||
assert config.color == "#000000"
|
||||
assert config.width == 1
|
||||
|
||||
def test_width_min(self):
|
||||
config = StrokeConfig(width=1)
|
||||
assert config.width == 1
|
||||
|
||||
def test_width_max(self):
|
||||
config = StrokeConfig(width=10)
|
||||
assert config.width == 10
|
||||
|
||||
def test_width_below_min_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
StrokeConfig(width=0)
|
||||
|
||||
def test_width_above_max_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
StrokeConfig(width=11)
|
||||
|
||||
|
||||
class TestShadowConfig:
|
||||
"""ShadowConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = ShadowConfig()
|
||||
assert config.enabled is False
|
||||
assert config.blur == 4
|
||||
assert config.offset_x == 2
|
||||
assert config.offset_y == 2
|
||||
|
||||
def test_blur_min(self):
|
||||
config = ShadowConfig(blur=0)
|
||||
assert config.blur == 0
|
||||
|
||||
def test_blur_max(self):
|
||||
config = ShadowConfig(blur=20)
|
||||
assert config.blur == 20
|
||||
|
||||
def test_blur_below_min_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
ShadowConfig(blur=-1)
|
||||
|
||||
def test_blur_above_max_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
ShadowConfig(blur=21)
|
||||
|
||||
|
||||
class TestCoverConfig:
|
||||
"""CoverConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = CoverConfig()
|
||||
assert config.type == CoverType.AI_FRAME
|
||||
assert config.image_url == ""
|
||||
assert config.frame_time is None
|
||||
|
||||
def test_frame_time_ge_zero(self):
|
||||
config = CoverConfig(frame_time=0.0)
|
||||
assert config.frame_time == 0.0
|
||||
|
||||
def test_frame_time_negative_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
CoverConfig(frame_time=-1.0)
|
||||
|
||||
def test_custom_values(self):
|
||||
config = CoverConfig(
|
||||
type=CoverType.MANUAL,
|
||||
image_url="http://example.com/cover.jpg",
|
||||
frame_time=5.5,
|
||||
)
|
||||
assert config.type == CoverType.MANUAL
|
||||
assert config.image_url == "http://example.com/cover.jpg"
|
||||
assert config.frame_time == 5.5
|
||||
|
||||
|
||||
class TestTitleConfig:
|
||||
"""TitleConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = TitleConfig()
|
||||
assert config.enabled is True
|
||||
assert config.ai_auto is True
|
||||
assert config.text == ""
|
||||
assert config.position == TextPosition.TOP
|
||||
assert config.font == "思源黑体"
|
||||
assert config.color == "#ffffff"
|
||||
assert config.size == 48
|
||||
assert config.bold is True
|
||||
assert config.italic is False
|
||||
assert isinstance(config.stroke, StrokeConfig)
|
||||
assert isinstance(config.shadow, ShadowConfig)
|
||||
|
||||
def test_size_min(self):
|
||||
config = TitleConfig(size=12)
|
||||
assert config.size == 12
|
||||
|
||||
def test_size_max(self):
|
||||
config = TitleConfig(size=120)
|
||||
assert config.size == 120
|
||||
|
||||
def test_size_below_min_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
TitleConfig(size=11)
|
||||
|
||||
def test_size_above_max_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
TitleConfig(size=121)
|
||||
|
||||
|
||||
class TestSubtitleConfig:
|
||||
"""SubtitleConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = SubtitleConfig()
|
||||
assert config.enabled is True
|
||||
assert config.position == TextPosition.BOTTOM
|
||||
assert config.font == "思源黑体"
|
||||
assert config.color == "#ffffff"
|
||||
assert config.size == 24
|
||||
assert config.animation == TextAnimation.FADE_IN
|
||||
assert config.auto_generated is False
|
||||
assert config.language == ""
|
||||
assert config.max_chars_per_line == 20
|
||||
assert config.min_chars_per_segment == 8
|
||||
|
||||
def test_size_min(self):
|
||||
config = SubtitleConfig(size=12)
|
||||
assert config.size == 12
|
||||
|
||||
def test_size_max(self):
|
||||
config = SubtitleConfig(size=60)
|
||||
assert config.size == 60
|
||||
|
||||
def test_size_out_of_range_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
SubtitleConfig(size=61)
|
||||
|
||||
def test_max_chars_per_line_range(self):
|
||||
config = SubtitleConfig(max_chars_per_line=40)
|
||||
assert config.max_chars_per_line == 40
|
||||
with pytest.raises(ValidationError):
|
||||
SubtitleConfig(max_chars_per_line=7)
|
||||
with pytest.raises(ValidationError):
|
||||
SubtitleConfig(max_chars_per_line=41)
|
||||
|
||||
def test_min_chars_per_segment_range(self):
|
||||
config = SubtitleConfig(min_chars_per_segment=20)
|
||||
assert config.min_chars_per_segment == 20
|
||||
with pytest.raises(ValidationError):
|
||||
SubtitleConfig(min_chars_per_segment=1)
|
||||
with pytest.raises(ValidationError):
|
||||
SubtitleConfig(min_chars_per_segment=21)
|
||||
|
||||
|
||||
class TestBGMConfig:
|
||||
"""BGMConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = BGMConfig()
|
||||
assert config.enabled is False
|
||||
assert config.source == BGMSource.LIBRARY
|
||||
assert config.asset_id == ""
|
||||
assert config.preset_id == ""
|
||||
assert config.audio_url == ""
|
||||
assert config.volume == 0.3
|
||||
assert config.fade_in == 0.0
|
||||
assert config.fade_out == 0.0
|
||||
assert config.loop_enabled is True
|
||||
assert config.sidechain_enabled is False
|
||||
assert config.sidechain_ratio == 0.3
|
||||
assert config.sidechain_attack == 0.02
|
||||
assert config.sidechain_release == 0.5
|
||||
assert config.sidechain_threshold == -25.0
|
||||
|
||||
def test_volume_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(volume=-0.1)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(volume=1.1)
|
||||
|
||||
def test_fade_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(fade_in=31.0)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(fade_out=31.0)
|
||||
|
||||
def test_sidechain_ratio_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_ratio=1.1)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_ratio=-0.1)
|
||||
|
||||
def test_sidechain_attack_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_attack=0.0001)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_attack=1.1)
|
||||
|
||||
def test_sidechain_release_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_release=0.001)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_release=5.1)
|
||||
|
||||
def test_sidechain_threshold_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_threshold=-61.0)
|
||||
with pytest.raises(ValidationError):
|
||||
BGMConfig(sidechain_threshold=1.0)
|
||||
|
||||
|
||||
class TestExportConfig:
|
||||
"""ExportConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = ExportConfig()
|
||||
assert config.resolution == "1080x1920"
|
||||
assert config.fps == 30
|
||||
assert config.video_bitrate == 8000
|
||||
assert config.audio_bitrate == 128
|
||||
assert config.format == "mp4"
|
||||
assert config.quality_preset == "balanced"
|
||||
assert config.watermark_enabled is False
|
||||
assert config.watermark_text == ""
|
||||
|
||||
def test_fps_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(fps=14)
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(fps=61)
|
||||
|
||||
def test_video_bitrate_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(video_bitrate=999)
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(video_bitrate=20001)
|
||||
|
||||
def test_audio_bitrate_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(audio_bitrate=63)
|
||||
with pytest.raises(ValidationError):
|
||||
ExportConfig(audio_bitrate=321)
|
||||
|
||||
|
||||
class TestFilterConfig:
|
||||
"""FilterConfig 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = FilterConfig()
|
||||
assert config.enabled is False
|
||||
assert config.preset_id == "filter_none"
|
||||
assert config.intensity == 100
|
||||
assert config.brightness == 0.0
|
||||
assert config.contrast == 1.0
|
||||
assert config.saturation == 1.0
|
||||
assert config.warmth == 0.0
|
||||
|
||||
def test_intensity_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(intensity=-1)
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(intensity=101)
|
||||
|
||||
def test_brightness_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(brightness=-1.1)
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(brightness=1.1)
|
||||
|
||||
def test_contrast_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(contrast=-0.1)
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(contrast=2.1)
|
||||
|
||||
def test_saturation_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(saturation=-0.1)
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(saturation=3.1)
|
||||
|
||||
def test_warmth_range(self):
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(warmth=-1.1)
|
||||
with pytest.raises(ValidationError):
|
||||
FilterConfig(warmth=1.1)
|
||||
|
||||
|
||||
class TestEditPlanConfigSchema:
|
||||
"""EditPlanConfigSchema 完整配置测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = EditPlanConfigSchema()
|
||||
assert isinstance(config.cover, CoverConfig)
|
||||
assert isinstance(config.title, TitleConfig)
|
||||
assert isinstance(config.subtitle, SubtitleConfig)
|
||||
assert isinstance(config.bgm, BGMConfig)
|
||||
assert isinstance(config.export, ExportConfig)
|
||||
assert isinstance(config.filter, FilterConfig)
|
||||
assert config.editing_mode == "one_take"
|
||||
|
||||
def test_partial_update(self):
|
||||
"""部分字段更新,其他保持默认"""
|
||||
config = EditPlanConfigSchema(
|
||||
title={"text": "自定义标题", "size": 36},
|
||||
bgm={"enabled": True, "volume": 0.5},
|
||||
)
|
||||
assert config.title.text == "自定义标题"
|
||||
assert config.title.size == 36
|
||||
assert config.title.font == "思源黑体" # 其他字段默认
|
||||
assert config.bgm.enabled is True
|
||||
assert config.bgm.volume == 0.5
|
||||
assert config.cover.type == CoverType.AI_FRAME # 未设置的保持默认
|
||||
|
||||
|
||||
class TestEditTemplateConfigSchema:
|
||||
"""EditTemplateConfigSchema 测试"""
|
||||
|
||||
def test_defaults(self):
|
||||
config = EditTemplateConfigSchema()
|
||||
assert isinstance(config.cover, CoverConfig)
|
||||
assert config.editing_mode == "one_take"
|
||||
assert config.transition_enabled is True
|
||||
|
||||
def test_custom_transition_enabled(self):
|
||||
config = EditTemplateConfigSchema(transition_enabled=False)
|
||||
assert config.transition_enabled is False
|
||||
|
||||
|
||||
class TestDefaultConfigs:
|
||||
"""默认配置常量测试"""
|
||||
|
||||
def test_plan_config_structure(self):
|
||||
assert "cover" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "title" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "subtitle" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "bgm" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "export" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "filter" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
assert "editing_mode" in DEFAULT_EDIT_PLAN_CONFIG
|
||||
|
||||
def test_template_config_has_transition_enabled(self):
|
||||
assert "transition_enabled" in DEFAULT_EDIT_TEMPLATE_CONFIG
|
||||
assert DEFAULT_EDIT_TEMPLATE_CONFIG["transition_enabled"] is True
|
||||
|
||||
def test_template_inherits_from_plan(self):
|
||||
"""模板配置继承计划配置的所有字段"""
|
||||
for key in DEFAULT_EDIT_PLAN_CONFIG:
|
||||
assert key in DEFAULT_EDIT_TEMPLATE_CONFIG
|
||||
|
||||
|
||||
class TestNormalizePlanConfig:
|
||||
"""normalize_plan_config 工具函数测试"""
|
||||
|
||||
def test_none_returns_default_copy(self):
|
||||
result = normalize_plan_config(None)
|
||||
assert result == DEFAULT_EDIT_PLAN_CONFIG
|
||||
# 确保是深拷贝
|
||||
result["title"]["text"] = "modified"
|
||||
assert DEFAULT_EDIT_PLAN_CONFIG["title"]["text"] == ""
|
||||
|
||||
def test_empty_dict_returns_default(self):
|
||||
result = normalize_plan_config({})
|
||||
assert result == DEFAULT_EDIT_PLAN_CONFIG
|
||||
|
||||
def test_updates_cover_section(self):
|
||||
result = normalize_plan_config({"cover": {"type": "manual", "frame_time": 5.0}})
|
||||
assert result["cover"]["type"] == "manual"
|
||||
assert result["cover"]["frame_time"] == 5.0
|
||||
assert result["cover"]["image_url"] == "" # 默认保留
|
||||
|
||||
def test_updates_title_section(self):
|
||||
result = normalize_plan_config({"title": {"text": "hello", "size": 32}})
|
||||
assert result["title"]["text"] == "hello"
|
||||
assert result["title"]["size"] == 32
|
||||
assert result["title"]["font"] == "思源黑体"
|
||||
|
||||
def test_updates_bgm_section(self):
|
||||
result = normalize_plan_config({"bgm": {"enabled": True, "volume": 0.8}})
|
||||
assert result["bgm"]["enabled"] is True
|
||||
assert result["bgm"]["volume"] == 0.8
|
||||
|
||||
def test_updates_editing_mode(self):
|
||||
result = normalize_plan_config({"editing_mode": "smart"})
|
||||
assert result["editing_mode"] == "smart"
|
||||
|
||||
def test_preserves_extra_fields(self):
|
||||
"""非标准字段被保留"""
|
||||
result = normalize_plan_config({"custom_field": "value", "generation_task_id": "task-1"})
|
||||
assert result["custom_field"] == "value"
|
||||
assert result["generation_task_id"] == "task-1"
|
||||
|
||||
def test_ignores_non_dict_section(self):
|
||||
"""section 不是 dict 时忽略"""
|
||||
result = normalize_plan_config({"cover": "not_a_dict"})
|
||||
assert result["cover"] == DEFAULT_EDIT_PLAN_CONFIG["cover"]
|
||||
|
||||
def test_ignores_non_str_editing_mode(self):
|
||||
result = normalize_plan_config({"editing_mode": 123})
|
||||
assert result["editing_mode"] == "one_take"
|
||||
|
||||
def test_deep_copy_independence(self):
|
||||
"""修改结果不影响默认值"""
|
||||
result = normalize_plan_config({})
|
||||
result["title"]["size"] = 999
|
||||
assert DEFAULT_EDIT_PLAN_CONFIG["title"]["size"] == 48
|
||||
|
||||
|
||||
class TestNormalizeTemplateConfig:
|
||||
"""normalize_template_config 工具函数测试"""
|
||||
|
||||
def test_none_returns_default_copy(self):
|
||||
result = normalize_template_config(None)
|
||||
assert result == DEFAULT_EDIT_TEMPLATE_CONFIG
|
||||
|
||||
def test_updates_transition_enabled(self):
|
||||
result = normalize_template_config({"transition_enabled": False})
|
||||
assert result["transition_enabled"] is False
|
||||
|
||||
def test_ignores_non_bool_transition_enabled(self):
|
||||
result = normalize_template_config({"transition_enabled": "yes"})
|
||||
assert result["transition_enabled"] is True
|
||||
|
||||
def test_updates_sections(self):
|
||||
result = normalize_template_config(
|
||||
{
|
||||
"title": {"text": "模板标题"},
|
||||
"bgm": {"enabled": True},
|
||||
}
|
||||
)
|
||||
assert result["title"]["text"] == "模板标题"
|
||||
assert result["bgm"]["enabled"] is True
|
||||
|
||||
def test_preserves_extra_fields(self):
|
||||
result = normalize_template_config({"custom": "value"})
|
||||
assert result["custom"] == "value"
|
||||
|
||||
def test_deep_copy_independence(self):
|
||||
result = normalize_template_config({})
|
||||
result["title"]["font"] = "CustomFont"
|
||||
assert DEFAULT_EDIT_TEMPLATE_CONFIG["title"]["font"] == "思源黑体"
|
||||
+595
@@ -0,0 +1,595 @@
|
||||
"""domain 层剩余小模块单测 - bgm_utils/exceptions/editing_mode/recipe/template/template_version/template_clip_config/preset_bgm/preset_voices/title_library/voice_library"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.bgm_utils import merge_bgm_config
|
||||
from packages.domain.editing_mode import EditingMode
|
||||
from packages.domain.exceptions import (
|
||||
DomainError,
|
||||
NotFoundError,
|
||||
QuotaExceededError,
|
||||
ValidationError,
|
||||
)
|
||||
from packages.domain.preset_bgm import (
|
||||
PRESET_BGM_LIBRARY,
|
||||
PresetBGM,
|
||||
get_preset_bgm,
|
||||
list_preset_bgm_by_style,
|
||||
search_preset_bgm,
|
||||
)
|
||||
from packages.domain.preset_voices import (
|
||||
PRESET_VOICES,
|
||||
PresetVoice,
|
||||
get_preset_voice_by_id,
|
||||
get_preset_voices,
|
||||
is_preset_voice,
|
||||
)
|
||||
from packages.domain.recipe import Recipe, RecipeItem
|
||||
from packages.domain.template import Template, TemplateCategory, TemplateSegment
|
||||
from packages.domain.template_clip_config import (
|
||||
ClipType,
|
||||
TemplateClipConfig,
|
||||
TransitionEffect,
|
||||
)
|
||||
from packages.domain.template_version import EditTemplateVersion
|
||||
from packages.domain.title_library import TitleLibraryItem
|
||||
from packages.domain.voice_library import VoiceLibraryItem
|
||||
|
||||
# ── EditingMode ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestEditingMode:
|
||||
"""EditingMode 枚举测试"""
|
||||
|
||||
def test_all_modes_exist(self):
|
||||
assert EditingMode.ONE_TAKE == "one_take"
|
||||
assert EditingMode.PIP == "pip"
|
||||
assert EditingMode.VOICE_OVER == "voice_over"
|
||||
assert EditingMode.VOICE_PIP == "voice_pip"
|
||||
|
||||
def test_str_enum(self):
|
||||
assert isinstance(EditingMode.ONE_TAKE, str)
|
||||
|
||||
def test_four_modes(self):
|
||||
assert len(EditingMode) == 4
|
||||
|
||||
|
||||
# ── Exceptions ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestDomainExceptions:
|
||||
"""异常类测试"""
|
||||
|
||||
def test_domain_error_base(self):
|
||||
err = DomainError("test")
|
||||
assert isinstance(err, Exception)
|
||||
assert str(err) == "test"
|
||||
|
||||
def test_not_found_error(self):
|
||||
err = NotFoundError("not found")
|
||||
assert isinstance(err, DomainError)
|
||||
assert str(err) == "not found"
|
||||
|
||||
def test_validation_error(self):
|
||||
err = ValidationError("invalid")
|
||||
assert isinstance(err, DomainError)
|
||||
assert str(err) == "invalid"
|
||||
|
||||
def test_quota_exceeded_error(self):
|
||||
err = QuotaExceededError(dimension="storage", limit=100, used=150)
|
||||
assert isinstance(err, DomainError)
|
||||
assert err.dimension == "storage"
|
||||
assert err.limit == 100
|
||||
assert err.used == 150
|
||||
assert "storage" in str(err)
|
||||
assert "150/100" in str(err)
|
||||
|
||||
def test_not_found_is_domain_error(self):
|
||||
assert issubclass(NotFoundError, DomainError)
|
||||
|
||||
def test_validation_is_domain_error(self):
|
||||
assert issubclass(ValidationError, DomainError)
|
||||
|
||||
def test_quota_exceeded_is_domain_error(self):
|
||||
assert issubclass(QuotaExceededError, DomainError)
|
||||
|
||||
|
||||
# ── BGM Utils ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestMergeBgmConfig:
|
||||
"""merge_bgm_config 函数测试"""
|
||||
|
||||
def test_user_empty_returns_template_copy(self):
|
||||
template = {"enabled": True, "volume": 0.5, "source": "library"}
|
||||
result = merge_bgm_config(template, {})
|
||||
assert result == template
|
||||
# 确保是拷贝不是引用
|
||||
result["volume"] = 0.9
|
||||
assert template["volume"] == 0.5
|
||||
|
||||
def test_template_empty_returns_user_copy(self):
|
||||
user = {"enabled": False, "volume": 0.3}
|
||||
result = merge_bgm_config({}, user)
|
||||
assert result == user
|
||||
|
||||
def test_user_none_returns_template(self):
|
||||
template = {"enabled": True, "volume": 0.5}
|
||||
result = merge_bgm_config(template, None) # type: ignore
|
||||
assert result == template
|
||||
|
||||
def test_template_none_returns_user(self):
|
||||
user = {"enabled": True, "volume": 0.5}
|
||||
result = merge_bgm_config(None, user) # type: ignore
|
||||
assert result == user
|
||||
|
||||
def test_user_overrides_template(self):
|
||||
template = {"volume": 0.3, "source": "library", "asset_id": "tpl-1"}
|
||||
user = {"volume": 0.8, "asset_id": "user-1"}
|
||||
result = merge_bgm_config(template, user)
|
||||
assert result["volume"] == 0.8
|
||||
assert result["asset_id"] == "user-1"
|
||||
assert result["source"] == "library" # 模板保留
|
||||
|
||||
def test_enabled_special_handling_user_not_set(self):
|
||||
"""用户没传 enabled 时保留模板的 enabled"""
|
||||
template = {"enabled": True, "volume": 0.5}
|
||||
user = {"volume": 0.8}
|
||||
result = merge_bgm_config(template, user)
|
||||
assert result["enabled"] is True # 保留模板值
|
||||
|
||||
def test_enabled_user_explicit_false(self):
|
||||
"""用户显式传了 enabled=False 则覆盖"""
|
||||
template = {"enabled": True, "volume": 0.5}
|
||||
user = {"enabled": False}
|
||||
result = merge_bgm_config(template, user)
|
||||
assert result["enabled"] is False
|
||||
|
||||
def test_enabled_user_explicit_true(self):
|
||||
"""用户显式传了 enabled=True 则覆盖"""
|
||||
template = {"enabled": False, "volume": 0.5}
|
||||
user = {"enabled": True}
|
||||
result = merge_bgm_config(template, user)
|
||||
assert result["enabled"] is True
|
||||
|
||||
def test_full_merge(self):
|
||||
"""完整合并场景"""
|
||||
template = {
|
||||
"enabled": True,
|
||||
"source": "library",
|
||||
"volume": 0.3,
|
||||
"fade_in": 0.0,
|
||||
"fade_out": 0.0,
|
||||
"loop_enabled": True,
|
||||
}
|
||||
user = {
|
||||
"volume": 0.7,
|
||||
"asset_id": "my-bgm",
|
||||
"fade_in": 1.0,
|
||||
}
|
||||
result = merge_bgm_config(template, user)
|
||||
assert result["enabled"] is True # 保留模板
|
||||
assert result["volume"] == 0.7 # 用户覆盖
|
||||
assert result["source"] == "library" # 模板保留
|
||||
assert result["asset_id"] == "my-bgm" # 用户新增
|
||||
assert result["fade_in"] == 1.0 # 用户覆盖
|
||||
assert result["fade_out"] == 0.0 # 模板保留
|
||||
assert result["loop_enabled"] is True # 模板保留
|
||||
|
||||
|
||||
# ── Recipe ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRecipe:
|
||||
"""Recipe / RecipeItem 测试"""
|
||||
|
||||
def test_recipe_item_create(self):
|
||||
item = RecipeItem(id="item-1", recipe_id="r1", item_type="asset", item_id="a1")
|
||||
assert item.id == "item-1"
|
||||
assert item.recipe_id == "r1"
|
||||
assert item.item_type == "asset"
|
||||
assert item.item_id == "a1"
|
||||
assert item.position == 0
|
||||
assert item.metadata_ == {}
|
||||
|
||||
def test_recipe_create(self):
|
||||
recipe = Recipe(id="r1", user_id="u1", name="我的配方")
|
||||
assert recipe.id == "r1"
|
||||
assert recipe.user_id == "u1"
|
||||
assert recipe.name == "我的配方"
|
||||
assert recipe.description == ""
|
||||
assert recipe.items == []
|
||||
assert recipe.is_active is True
|
||||
assert recipe.generation_params == {}
|
||||
assert recipe.created_at is not None
|
||||
|
||||
def test_recipe_with_items(self):
|
||||
items = [
|
||||
RecipeItem(id="i1", recipe_id="r1", item_type="asset", item_id="a1", position=0),
|
||||
RecipeItem(id="i2", recipe_id="r1", item_type="title", item_id="t1", position=1),
|
||||
]
|
||||
recipe = Recipe(id="r1", user_id="u1", name="test", items=items)
|
||||
assert len(recipe.items) == 2
|
||||
assert recipe.items[0].item_type == "asset"
|
||||
assert recipe.items[1].position == 1
|
||||
|
||||
def test_recipe_items_independent_list(self):
|
||||
"""不同 recipe 的 items 是独立列表"""
|
||||
r1 = Recipe(id="r1", user_id="u1", name="r1")
|
||||
r2 = Recipe(id="r2", user_id="u1", name="r2")
|
||||
assert r1.items is not r2.items
|
||||
|
||||
|
||||
# ── Template ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestTemplate:
|
||||
"""Template 相关实体测试"""
|
||||
|
||||
def test_template_segment(self):
|
||||
seg = TemplateSegment(
|
||||
id="seg-1",
|
||||
template_id="t1",
|
||||
segment_order=0,
|
||||
duration_min=3.0,
|
||||
duration_max=5.0,
|
||||
)
|
||||
assert seg.id == "seg-1"
|
||||
assert seg.template_id == "t1"
|
||||
assert seg.segment_order == 0
|
||||
assert seg.duration_min == 3.0
|
||||
assert seg.duration_max == 5.0
|
||||
assert seg.material_type is None
|
||||
assert seg.created_at is not None
|
||||
|
||||
def test_template_create(self):
|
||||
tpl = Template(
|
||||
id="t1",
|
||||
user_id="u1",
|
||||
name="口播模板",
|
||||
mode="voice_over",
|
||||
)
|
||||
assert tpl.id == "t1"
|
||||
assert tpl.user_id == "u1"
|
||||
assert tpl.name == "口播模板"
|
||||
assert tpl.mode == "voice_over"
|
||||
assert tpl.category == ""
|
||||
assert tpl.tags == []
|
||||
assert tpl.segments == []
|
||||
assert tpl.is_active is True
|
||||
assert tpl.estimated_duration == 0.0
|
||||
|
||||
def test_template_with_segments(self):
|
||||
segs = [
|
||||
TemplateSegment(id="s1", template_id="t1", segment_order=0, duration_min=2, duration_max=4),
|
||||
TemplateSegment(id="s2", template_id="t1", segment_order=1, duration_min=5, duration_max=8),
|
||||
]
|
||||
tpl = Template(id="t1", user_id="u1", name="test", mode="one_take", segments=segs)
|
||||
assert len(tpl.segments) == 2
|
||||
assert tpl.segments[0].segment_order == 0
|
||||
|
||||
def test_template_category(self):
|
||||
cat = TemplateCategory(id="cat-1", user_id="u1", name="热门")
|
||||
assert cat.id == "cat-1"
|
||||
assert cat.user_id == "u1"
|
||||
assert cat.name == "热门"
|
||||
assert cat.created_at is not None
|
||||
|
||||
|
||||
# ── TemplateVersion ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestEditTemplateVersion:
|
||||
"""EditTemplateVersion 测试"""
|
||||
|
||||
def test_create_basic(self):
|
||||
v = EditTemplateVersion.create(template_id="t1", version=1)
|
||||
assert v.id
|
||||
assert len(v.id) == 32
|
||||
assert v.template_id == "t1"
|
||||
assert v.version == 1
|
||||
assert v.name == ""
|
||||
assert v.editing_mode == "one_take"
|
||||
assert v.config == {}
|
||||
assert v.clip_configs == []
|
||||
assert v.change_note == ""
|
||||
assert v.published_by == ""
|
||||
|
||||
def test_create_with_details(self):
|
||||
config = {"title": {"size": 36}}
|
||||
clips = [{"clip_type": "intro"}, {"clip_type": "outro"}]
|
||||
v = EditTemplateVersion.create(
|
||||
template_id="t1",
|
||||
version=2,
|
||||
name="V2 优化版",
|
||||
editing_mode="voice_over",
|
||||
config=config,
|
||||
clip_configs=clips,
|
||||
change_note="优化了节奏",
|
||||
published_by="user-1",
|
||||
)
|
||||
assert v.version == 2
|
||||
assert v.name == "V2 优化版"
|
||||
assert v.editing_mode == "voice_over"
|
||||
assert v.config == config
|
||||
assert v.clip_configs == clips
|
||||
assert v.change_note == "优化了节奏"
|
||||
assert v.published_by == "user-1"
|
||||
|
||||
def test_create_none_config_defaults_empty(self):
|
||||
v = EditTemplateVersion.create(template_id="t1", version=1, config=None)
|
||||
assert v.config == {}
|
||||
|
||||
def test_create_none_clip_configs_defaults_empty(self):
|
||||
v = EditTemplateVersion.create(template_id="t1", version=1, clip_configs=None)
|
||||
assert v.clip_configs == []
|
||||
|
||||
|
||||
# ── TemplateClipConfig ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestTemplateClipConfig:
|
||||
"""TemplateClipConfig + 枚举测试"""
|
||||
|
||||
def test_clip_type_values(self):
|
||||
assert ClipType.INTRO == "intro"
|
||||
assert ClipType.MAIN == "main"
|
||||
assert ClipType.TRANSITION == "transition"
|
||||
assert ClipType.OUTRO == "outro"
|
||||
assert ClipType.TITLE == "title"
|
||||
assert ClipType.SUBTITLE == "subtitle"
|
||||
|
||||
def test_clip_type_count(self):
|
||||
assert len(ClipType) == 6
|
||||
|
||||
def test_transition_effect_values(self):
|
||||
assert TransitionEffect.CUT == "cut"
|
||||
assert TransitionEffect.FADE == "fade"
|
||||
assert TransitionEffect.SLIDE_LEFT == "slide_left"
|
||||
assert TransitionEffect.SLIDE_RIGHT == "slide_right"
|
||||
assert TransitionEffect.DISSOLVE == "dissolve"
|
||||
assert TransitionEffect.WIPE == "wipe"
|
||||
|
||||
def test_transition_effect_count(self):
|
||||
assert len(TransitionEffect) == 6
|
||||
|
||||
def test_template_clip_config(self):
|
||||
clip = TemplateClipConfig(
|
||||
id="clip-1",
|
||||
template_id="t1",
|
||||
clip_type=ClipType.MAIN,
|
||||
order=1,
|
||||
min_duration=2.0,
|
||||
max_duration=5.0,
|
||||
)
|
||||
assert clip.id == "clip-1"
|
||||
assert clip.template_id == "t1"
|
||||
assert clip.clip_type == ClipType.MAIN
|
||||
assert clip.order == 1
|
||||
assert clip.min_duration == 2.0
|
||||
assert clip.max_duration == 5.0
|
||||
|
||||
def test_str_enum(self):
|
||||
assert isinstance(ClipType.INTRO, str)
|
||||
assert isinstance(TransitionEffect.FADE, str)
|
||||
|
||||
|
||||
# ── PresetBGM ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestPresetBGM:
|
||||
"""PresetBGM + 查询函数测试"""
|
||||
|
||||
def test_preset_bgm_create(self):
|
||||
bgm = PresetBGM(
|
||||
id="bgm_test_001",
|
||||
name="测试音乐",
|
||||
style="upbeat",
|
||||
duration=120.0,
|
||||
)
|
||||
assert bgm.id == "bgm_test_001"
|
||||
assert bgm.name == "测试音乐"
|
||||
assert bgm.style == "upbeat"
|
||||
assert bgm.duration == 120.0
|
||||
assert bgm.artist == ""
|
||||
assert bgm.tags == []
|
||||
assert bgm.audio_url == ""
|
||||
|
||||
def test_preset_bgm_frozen(self):
|
||||
bgm = PresetBGM(id="t1", name="t", style="x", duration=10.0)
|
||||
with pytest.raises(Exception):
|
||||
bgm.name = "改名"
|
||||
|
||||
def test_library_not_empty(self):
|
||||
assert len(PRESET_BGM_LIBRARY) > 0
|
||||
|
||||
def test_all_presets_have_required_fields(self):
|
||||
for bgm in PRESET_BGM_LIBRARY:
|
||||
assert bgm.id
|
||||
assert bgm.name
|
||||
assert bgm.style
|
||||
assert bgm.duration > 0
|
||||
|
||||
def test_get_preset_bgm_existing(self):
|
||||
first = PRESET_BGM_LIBRARY[0]
|
||||
result = get_preset_bgm(first.id)
|
||||
assert result is not None
|
||||
assert result.id == first.id
|
||||
|
||||
def test_get_preset_bgm_nonexistent(self):
|
||||
assert get_preset_bgm("nonexistent_bgm") is None
|
||||
|
||||
def test_list_preset_bgm_by_style(self):
|
||||
upbeat = list_preset_bgm_by_style("upbeat")
|
||||
assert len(upbeat) > 0
|
||||
assert all(b.style == "upbeat" for b in upbeat)
|
||||
|
||||
def test_list_preset_bgm_by_style_empty(self):
|
||||
result = list_preset_bgm_by_style("nonexistent_style")
|
||||
assert result == []
|
||||
|
||||
def test_search_preset_bgm_by_name(self):
|
||||
result = search_preset_bgm("阳光")
|
||||
assert len(result) >= 1
|
||||
assert any("阳光" in b.name for b in result)
|
||||
|
||||
def test_search_preset_bgm_by_tag(self):
|
||||
result = search_preset_bgm("轻快")
|
||||
assert len(result) >= 1
|
||||
assert any(any("轻快" in t for t in b.tags) for b in result)
|
||||
|
||||
def test_search_preset_bgm_empty_result(self):
|
||||
result = search_preset_bgm("xyz_not_exist_keyword")
|
||||
assert result == []
|
||||
|
||||
|
||||
# ── PresetVoices ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestPresetVoices:
|
||||
"""PresetVoice + 查询函数测试"""
|
||||
|
||||
def test_preset_voice_create(self):
|
||||
v = PresetVoice(
|
||||
voice_id="test_voice",
|
||||
name="测试音色",
|
||||
description="测试用",
|
||||
gender="female",
|
||||
)
|
||||
assert v.voice_id == "test_voice"
|
||||
assert v.name == "测试音色"
|
||||
assert v.gender == "female"
|
||||
assert v.language == "zh-CN"
|
||||
assert v.preview_url == ""
|
||||
assert v.tags is None
|
||||
|
||||
def test_preset_voice_to_dict(self):
|
||||
v = PresetVoice(
|
||||
voice_id="v1",
|
||||
name="音色1",
|
||||
description="desc",
|
||||
gender="male",
|
||||
language="zh-CN",
|
||||
tags=["温柔", "男声"],
|
||||
)
|
||||
d = v.to_dict()
|
||||
assert d["voice_id"] == "v1"
|
||||
assert d["name"] == "音色1"
|
||||
assert d["description"] == "desc"
|
||||
assert d["gender"] == "male"
|
||||
assert d["language"] == "zh-CN"
|
||||
assert d["tags"] == ["温柔", "男声"]
|
||||
|
||||
def test_preset_voice_to_dict_no_tags(self):
|
||||
v = PresetVoice(voice_id="v1", name="t", description="d", gender="female")
|
||||
d = v.to_dict()
|
||||
assert d["tags"] == []
|
||||
|
||||
def test_preset_voice_frozen(self):
|
||||
v = PresetVoice(voice_id="v1", name="t", description="d", gender="female")
|
||||
with pytest.raises(Exception):
|
||||
v.name = "改名"
|
||||
|
||||
def test_preset_voices_list_not_empty(self):
|
||||
assert len(PRESET_VOICES) > 0
|
||||
|
||||
def test_get_preset_voices(self):
|
||||
voices = get_preset_voices()
|
||||
assert len(voices) == len(PRESET_VOICES)
|
||||
assert all(isinstance(v, PresetVoice) for v in voices)
|
||||
|
||||
def test_get_preset_voice_by_id_existing(self):
|
||||
first = PRESET_VOICES[0]
|
||||
result = get_preset_voice_by_id(first.voice_id)
|
||||
assert result is not None
|
||||
assert result.voice_id == first.voice_id
|
||||
|
||||
def test_get_preset_voice_by_id_nonexistent(self):
|
||||
assert get_preset_voice_by_id("nonexistent_voice") is None
|
||||
|
||||
def test_is_preset_voice_true(self):
|
||||
first = PRESET_VOICES[0]
|
||||
assert is_preset_voice(first.voice_id) is True
|
||||
|
||||
def test_is_preset_voice_false(self):
|
||||
assert is_preset_voice("fake_voice_id") is False
|
||||
|
||||
|
||||
# ── TitleLibrary ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestTitleLibraryItem:
|
||||
"""TitleLibraryItem 测试"""
|
||||
|
||||
def test_create_basic(self):
|
||||
item = TitleLibraryItem(id="t1", user_id="u1", name="标题1", text="这是标题文案")
|
||||
assert item.id == "t1"
|
||||
assert item.user_id == "u1"
|
||||
assert item.name == "标题1"
|
||||
assert item.text == "这是标题文案"
|
||||
assert item.category == "default"
|
||||
assert item.tags == []
|
||||
assert item.usage_count == 0
|
||||
assert item.is_active is True
|
||||
assert item.created_at is not None
|
||||
|
||||
def test_create_with_details(self):
|
||||
item = TitleLibraryItem(
|
||||
id="t1",
|
||||
user_id="u1",
|
||||
name="爆款标题",
|
||||
text="三个方法教你...",
|
||||
category="爆款",
|
||||
description="高点击率",
|
||||
tags=["热门", "干货"],
|
||||
usage_count=100,
|
||||
)
|
||||
assert item.category == "爆款"
|
||||
assert item.description == "高点击率"
|
||||
assert item.tags == ["热门", "干货"]
|
||||
assert item.usage_count == 100
|
||||
|
||||
|
||||
# ── VoiceLibrary ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestVoiceLibraryItem:
|
||||
"""VoiceLibraryItem 测试"""
|
||||
|
||||
def test_create_basic(self):
|
||||
item = VoiceLibraryItem(id="v1", user_id="u1", name="我的配音")
|
||||
assert item.id == "v1"
|
||||
assert item.user_id == "u1"
|
||||
assert item.name == "我的配音"
|
||||
assert item.text == ""
|
||||
assert item.voice_provider == ""
|
||||
assert item.duration == 0
|
||||
assert item.status == "completed"
|
||||
assert item.project_id is None
|
||||
assert item.tags == []
|
||||
assert item.created_at is not None
|
||||
|
||||
def test_create_with_details(self):
|
||||
item = VoiceLibraryItem(
|
||||
id="v1",
|
||||
user_id="u1",
|
||||
name="产品介绍",
|
||||
text="大家好,今天给大家介绍...",
|
||||
voice_provider="cosyvoice",
|
||||
voice_id="voice_001",
|
||||
voice_name="温柔女声",
|
||||
audio_url="http://cdn/audio.mp3",
|
||||
duration=30.5,
|
||||
file_size=102400,
|
||||
status="processing",
|
||||
project_id="proj-1",
|
||||
tags=["产品", "介绍"],
|
||||
)
|
||||
assert item.voice_provider == "cosyvoice"
|
||||
assert item.voice_id == "voice_001"
|
||||
assert item.audio_url == "http://cdn/audio.mp3"
|
||||
assert item.duration == 30.5
|
||||
assert item.file_size == 102400
|
||||
assert item.status == "processing"
|
||||
assert item.project_id == "proj-1"
|
||||
assert item.tags == ["产品", "介绍"]
|
||||
Executable
+305
@@ -0,0 +1,305 @@
|
||||
"""Duplication 查重记录领域实体单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.duplication import DuplicateSegment, DuplicationRecord
|
||||
|
||||
|
||||
class TestDuplicateSegmentCreate:
|
||||
def test_create_normal(self):
|
||||
seg = DuplicateSegment.create(
|
||||
source_start=10.0,
|
||||
source_end=20.0,
|
||||
matched_video_id="vid123",
|
||||
matched_video_name="测试视频",
|
||||
matched_start=5.0,
|
||||
matched_end=15.0,
|
||||
similarity=85.5,
|
||||
)
|
||||
assert seg.id
|
||||
assert seg.source_start == 10.0
|
||||
assert seg.source_end == 20.0
|
||||
assert seg.matched_video_id == "vid123"
|
||||
assert seg.matched_video_name == "测试视频"
|
||||
assert seg.matched_start == 5.0
|
||||
assert seg.matched_end == 15.0
|
||||
assert seg.similarity == 85.5
|
||||
|
||||
def test_create_negative_source_start_raises(self):
|
||||
with pytest.raises(ValueError, match="invalid source segment range"):
|
||||
DuplicateSegment.create(
|
||||
source_start=-1.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=10.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
|
||||
def test_create_zero_duration_source_raises(self):
|
||||
with pytest.raises(ValueError, match="invalid source segment range"):
|
||||
DuplicateSegment.create(
|
||||
source_start=10.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=10.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
|
||||
def test_create_reversed_source_range_raises(self):
|
||||
with pytest.raises(ValueError, match="invalid source segment range"):
|
||||
DuplicateSegment.create(
|
||||
source_start=20.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=10.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
|
||||
def test_create_negative_matched_start_raises(self):
|
||||
with pytest.raises(ValueError, match="invalid matched segment range"):
|
||||
DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=-1.0,
|
||||
matched_end=10.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
|
||||
def test_create_zero_duration_matched_raises(self):
|
||||
with pytest.raises(ValueError, match="invalid matched segment range"):
|
||||
DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=5.0,
|
||||
matched_end=5.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
|
||||
def test_create_similarity_negative_raises(self):
|
||||
with pytest.raises(ValueError, match="similarity must be between 0 and 100"):
|
||||
DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=10.0,
|
||||
similarity=-1.0,
|
||||
)
|
||||
|
||||
def test_create_similarity_over_100_raises(self):
|
||||
with pytest.raises(ValueError, match="similarity must be between 0 and 100"):
|
||||
DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=10.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=10.0,
|
||||
similarity=101.0,
|
||||
)
|
||||
|
||||
def test_create_similarity_boundary_values(self):
|
||||
# 0 和 100 都是合法的
|
||||
seg0 = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=0.0,
|
||||
)
|
||||
assert seg0.similarity == 0.0
|
||||
|
||||
seg100 = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=100.0,
|
||||
)
|
||||
assert seg100.similarity == 100.0
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
seg1 = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
seg2 = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
assert seg1.id != seg2.id
|
||||
|
||||
|
||||
class TestDuplicationRecordCreate:
|
||||
def test_create_normal(self):
|
||||
record = DuplicationRecord.create(
|
||||
user_id="user1",
|
||||
filename="test.mp4",
|
||||
file_size=1024000,
|
||||
storage_key="videos/test.mp4",
|
||||
duration_seconds=30.5,
|
||||
)
|
||||
assert record.id
|
||||
assert record.user_id == "user1"
|
||||
assert record.filename == "test.mp4"
|
||||
assert record.file_size == 1024000
|
||||
assert record.storage_key == "videos/test.mp4"
|
||||
assert record.duration_seconds == 30.5
|
||||
assert record.status == "pending"
|
||||
assert record.duplicate_rate is None
|
||||
assert record.duplicate_count == 0
|
||||
assert record.segments == []
|
||||
assert record.error_message == ""
|
||||
|
||||
def test_create_strips_whitespace(self):
|
||||
record = DuplicationRecord.create(
|
||||
user_id=" user1 ",
|
||||
filename=" test.mp4 ",
|
||||
file_size=100,
|
||||
storage_key="key1",
|
||||
)
|
||||
assert record.user_id == "user1"
|
||||
assert record.filename == "test.mp4"
|
||||
|
||||
def test_create_empty_user_id_raises(self):
|
||||
with pytest.raises(ValueError, match="user_id cannot be empty"):
|
||||
DuplicationRecord.create(
|
||||
user_id="",
|
||||
filename="test.mp4",
|
||||
file_size=100,
|
||||
storage_key="key1",
|
||||
)
|
||||
|
||||
def test_create_empty_filename_raises(self):
|
||||
with pytest.raises(ValueError, match="filename cannot be empty"):
|
||||
DuplicationRecord.create(
|
||||
user_id="u1",
|
||||
filename="",
|
||||
file_size=100,
|
||||
storage_key="key1",
|
||||
)
|
||||
|
||||
def test_create_zero_file_size_raises(self):
|
||||
with pytest.raises(ValueError, match="file_size must be positive"):
|
||||
DuplicationRecord.create(
|
||||
user_id="u1",
|
||||
filename="test.mp4",
|
||||
file_size=0,
|
||||
storage_key="key1",
|
||||
)
|
||||
|
||||
def test_create_negative_file_size_raises(self):
|
||||
with pytest.raises(ValueError, match="file_size must be positive"):
|
||||
DuplicationRecord.create(
|
||||
user_id="u1",
|
||||
filename="test.mp4",
|
||||
file_size=-100,
|
||||
storage_key="key1",
|
||||
)
|
||||
|
||||
|
||||
class TestDuplicationRecordStatus:
|
||||
def test_mark_processing(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
record.mark_processing()
|
||||
assert record.status == "processing"
|
||||
|
||||
def test_mark_completed(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
seg = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=5.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=5.0,
|
||||
similarity=90.0,
|
||||
)
|
||||
record.mark_completed(duplicate_rate=25.5, duplicate_count=3, segments=[seg])
|
||||
assert record.status == "completed"
|
||||
assert record.duplicate_rate == 25.5
|
||||
assert record.duplicate_count == 3
|
||||
assert len(record.segments) == 1
|
||||
|
||||
def test_mark_completed_invalid_rate_raises(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
with pytest.raises(ValueError, match="duplicate_rate must be between 0 and 100"):
|
||||
record.mark_completed(duplicate_rate=-1, duplicate_count=0, segments=[])
|
||||
with pytest.raises(ValueError, match="duplicate_rate must be between 0 and 100"):
|
||||
record.mark_completed(duplicate_rate=101, duplicate_count=0, segments=[])
|
||||
|
||||
def test_mark_failed(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
record.mark_failed("网络超时")
|
||||
assert record.status == "failed"
|
||||
assert record.error_message == "网络超时"
|
||||
|
||||
def test_can_retry_only_failed(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
assert record.can_retry() is False # pending
|
||||
|
||||
record.mark_processing()
|
||||
assert record.can_retry() is False # processing
|
||||
|
||||
record.mark_failed("error")
|
||||
assert record.can_retry() is True # failed
|
||||
|
||||
seg = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
record2 = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
record2.mark_completed(10.0, 1, [seg])
|
||||
assert record2.can_retry() is False # completed
|
||||
|
||||
def test_reset_for_retry(self):
|
||||
record = DuplicationRecord.create(user_id="u1", filename="t.mp4", file_size=100, storage_key="k1")
|
||||
seg = DuplicateSegment.create(
|
||||
source_start=0.0,
|
||||
source_end=1.0,
|
||||
matched_video_id="v1",
|
||||
matched_video_name="v",
|
||||
matched_start=0.0,
|
||||
matched_end=1.0,
|
||||
similarity=50.0,
|
||||
)
|
||||
record.mark_completed(50.0, 2, [seg])
|
||||
record.video_fingerprint = {"hash": "abc"}
|
||||
|
||||
record.reset_for_retry()
|
||||
assert record.status == "pending"
|
||||
assert record.duplicate_rate is None
|
||||
assert record.duplicate_count == 0
|
||||
assert record.error_message == ""
|
||||
assert record.segments == []
|
||||
assert record.video_fingerprint is None
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
"""EditPlan 剪辑计划领域实体单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.edit_plan import EditPlan, EditPlanStatus
|
||||
|
||||
|
||||
class TestEditPlanStatus:
|
||||
def test_values(self):
|
||||
assert EditPlanStatus.DRAFT.value == "draft"
|
||||
assert EditPlanStatus.EDITING.value == "editing"
|
||||
assert EditPlanStatus.RENDERING.value == "rendering"
|
||||
assert EditPlanStatus.COMPLETED.value == "completed"
|
||||
assert EditPlanStatus.FAILED.value == "failed"
|
||||
|
||||
def test_is_str(self):
|
||||
assert isinstance(EditPlanStatus.DRAFT, str)
|
||||
|
||||
|
||||
class TestEditPlanCreate:
|
||||
def test_create_normal(self):
|
||||
plan = EditPlan.create(template_id="tmpl1", name="我的剪辑计划")
|
||||
assert plan.id
|
||||
assert plan.template_id == "tmpl1"
|
||||
assert plan.name == "我的剪辑计划"
|
||||
assert plan.status == EditPlanStatus.DRAFT
|
||||
assert plan.total_duration == 0.0
|
||||
assert plan.config == {}
|
||||
|
||||
def test_create_strips_whitespace(self):
|
||||
plan = EditPlan.create(
|
||||
template_id=" tmpl1 ",
|
||||
name=" 我的计划 ",
|
||||
source_edit_plan_id=" src1 ",
|
||||
project_id=" proj1 ",
|
||||
created_by_user_id=" user1 ",
|
||||
)
|
||||
assert plan.template_id == "tmpl1"
|
||||
assert plan.name == "我的计划"
|
||||
assert plan.source_edit_plan_id == "src1"
|
||||
assert plan.project_id == "proj1"
|
||||
assert plan.created_by_user_id == "user1"
|
||||
|
||||
def test_create_empty_name_raises(self):
|
||||
with pytest.raises(ValueError, match="计划名称不能为空"):
|
||||
EditPlan.create(template_id="tmpl1", name="")
|
||||
|
||||
def test_create_whitespace_name_raises(self):
|
||||
with pytest.raises(ValueError, match="计划名称不能为空"):
|
||||
EditPlan.create(template_id="tmpl1", name=" ")
|
||||
|
||||
def test_create_empty_template_id_raises(self):
|
||||
with pytest.raises(ValueError, match="template_id 不能为空"):
|
||||
EditPlan.create(template_id="", name="计划")
|
||||
|
||||
def test_create_whitespace_template_id_raises(self):
|
||||
with pytest.raises(ValueError, match="template_id 不能为空"):
|
||||
EditPlan.create(template_id=" ", name="计划")
|
||||
|
||||
def test_create_with_config(self):
|
||||
config = {"resolution": "1080p", "fps": 30}
|
||||
plan = EditPlan.create(
|
||||
template_id="tmpl1",
|
||||
name="计划",
|
||||
config=config,
|
||||
total_duration=30.5,
|
||||
)
|
||||
assert plan.config == config
|
||||
assert plan.total_duration == 30.5
|
||||
|
||||
def test_create_none_config_defaults_to_empty(self):
|
||||
plan = EditPlan.create(template_id="tmpl1", name="计划", config=None)
|
||||
assert plan.config == {}
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
p1 = EditPlan.create(template_id="t1", name="p1")
|
||||
p2 = EditPlan.create(template_id="t1", name="p2")
|
||||
assert p1.id != p2.id
|
||||
Executable
+177
@@ -0,0 +1,177 @@
|
||||
"""EditPlanClip 剪辑计划片段领域实体单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.edit_plan_clip import EditPlanClip, EditPlanClipStatus
|
||||
|
||||
|
||||
class TestEditPlanClipStatus:
|
||||
def test_values(self):
|
||||
assert EditPlanClipStatus.PENDING.value == "pending"
|
||||
assert EditPlanClipStatus.READY.value == "ready"
|
||||
assert EditPlanClipStatus.RENDERED.value == "rendered"
|
||||
assert EditPlanClipStatus.FAILED.value == "failed"
|
||||
|
||||
|
||||
class TestEditPlanClipCreate:
|
||||
def test_create_normal(self):
|
||||
clip = EditPlanClip.create(
|
||||
plan_id="plan1",
|
||||
clip_type="video",
|
||||
order=1,
|
||||
start_time=0.0,
|
||||
duration=5.0,
|
||||
)
|
||||
assert clip.id
|
||||
assert clip.plan_id == "plan1"
|
||||
assert clip.clip_type == "video"
|
||||
assert clip.order == 1
|
||||
assert clip.status == EditPlanClipStatus.PENDING
|
||||
assert clip.start_time == 0.0
|
||||
assert clip.duration == 5.0
|
||||
assert clip.playback_speed == 1.0
|
||||
assert clip.config == {}
|
||||
|
||||
def test_create_empty_plan_id_raises(self):
|
||||
with pytest.raises(ValueError, match="plan_id 不能为空"):
|
||||
EditPlanClip.create(plan_id="", clip_type="video", order=1)
|
||||
|
||||
def test_create_empty_clip_type_raises(self):
|
||||
with pytest.raises(ValueError, match="clip_type 不能为空"):
|
||||
EditPlanClip.create(plan_id="p1", clip_type="", order=1)
|
||||
|
||||
def test_create_negative_start_time_raises(self):
|
||||
with pytest.raises(ValueError, match="start_time 不能为负数"):
|
||||
EditPlanClip.create(plan_id="p1", clip_type="v", order=1, start_time=-1.0)
|
||||
|
||||
def test_create_negative_duration_raises(self):
|
||||
with pytest.raises(ValueError, match="duration 不能为负数"):
|
||||
EditPlanClip.create(plan_id="p1", clip_type="v", order=1, duration=-1.0)
|
||||
|
||||
def test_create_strips_strings(self):
|
||||
clip = EditPlanClip.create(
|
||||
plan_id=" plan1 ",
|
||||
clip_type=" video ",
|
||||
order=1,
|
||||
template_clip_config_id=" cfg1 ",
|
||||
asset_id=" a1 ",
|
||||
text_content=" 你好 ",
|
||||
transition_effect=" fade ",
|
||||
)
|
||||
assert clip.plan_id == "plan1"
|
||||
assert clip.clip_type == "video"
|
||||
assert clip.template_clip_config_id == "cfg1"
|
||||
assert clip.asset_id == "a1"
|
||||
assert clip.text_content == "你好"
|
||||
assert clip.transition_effect == "fade"
|
||||
|
||||
def test_create_empty_transition_effect_defaults_to_cut(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, transition_effect="")
|
||||
assert clip.transition_effect == "cut"
|
||||
|
||||
def test_create_playback_speed_zero_defaults_to_1(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, playback_speed=0)
|
||||
assert clip.playback_speed == 1.0
|
||||
|
||||
def test_create_playback_speed_negative_defaults_to_1(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, playback_speed=-1.0)
|
||||
assert clip.playback_speed == 1.0
|
||||
|
||||
def test_create_playback_speed_below_min_clamped(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, playback_speed=0.1)
|
||||
assert clip.playback_speed == 0.25
|
||||
|
||||
def test_create_playback_speed_above_max_clamped(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, playback_speed=5.0)
|
||||
assert clip.playback_speed == 4.0
|
||||
|
||||
def test_create_playback_speed_within_range(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, playback_speed=1.5)
|
||||
assert clip.playback_speed == 1.5
|
||||
|
||||
def test_create_transition_duration_negative_clamped(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, transition_duration=-0.5)
|
||||
assert clip.transition_duration == 0.0
|
||||
|
||||
def test_create_none_config_defaults_to_empty(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, config=None)
|
||||
assert clip.config == {}
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
c1 = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
c2 = EditPlanClip.create(plan_id="p1", clip_type="v", order=2)
|
||||
assert c1.id != c2.id
|
||||
|
||||
|
||||
class TestEditPlanClipStateTransitions:
|
||||
def test_pending_to_ready(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.mark_ready()
|
||||
assert clip.status == EditPlanClipStatus.READY
|
||||
|
||||
def test_ready_to_rendered(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.mark_ready()
|
||||
clip.mark_rendered()
|
||||
assert clip.status == EditPlanClipStatus.RENDERED
|
||||
|
||||
def test_ready_to_failed(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.mark_ready()
|
||||
clip.mark_failed()
|
||||
assert clip.status == EditPlanClipStatus.FAILED
|
||||
|
||||
def test_ready_mark_ready_raises(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.mark_ready()
|
||||
with pytest.raises(ValueError, match="只有 pending 状态的片段可以标记就绪"):
|
||||
clip.mark_ready()
|
||||
|
||||
def test_pending_mark_rendered_raises(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
with pytest.raises(ValueError, match="只有 ready 状态的片段可以标记已渲染"):
|
||||
clip.mark_rendered()
|
||||
|
||||
def test_pending_mark_failed_raises(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
with pytest.raises(ValueError, match="只有 ready 状态的片段可以标记失败"):
|
||||
clip.mark_failed()
|
||||
|
||||
|
||||
class TestEditPlanClipProperties:
|
||||
def test_end_time(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, start_time=10.0, duration=5.0)
|
||||
assert clip.end_time == 15.0
|
||||
|
||||
def test_end_time_zero_duration(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, start_time=5.0, duration=0.0)
|
||||
assert clip.end_time == 5.0
|
||||
|
||||
def test_has_asset_true(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, asset_id="a1")
|
||||
assert clip.has_asset is True
|
||||
|
||||
def test_has_asset_false(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
assert clip.has_asset is False
|
||||
|
||||
def test_has_asset_empty_string(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1, asset_id="")
|
||||
assert clip.has_asset is False
|
||||
|
||||
|
||||
class TestEditPlanClipAssignAsset:
|
||||
def test_assign_asset(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.assign_asset("asset1")
|
||||
assert clip.asset_id == "asset1"
|
||||
|
||||
def test_assign_asset_strips(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
clip.assign_asset(" asset1 ")
|
||||
assert clip.asset_id == "asset1"
|
||||
|
||||
def test_assign_asset_empty_raises(self):
|
||||
clip = EditPlanClip.create(plan_id="p1", clip_type="v", order=1)
|
||||
with pytest.raises(ValueError, match="asset_id 不能为空"):
|
||||
clip.assign_asset("")
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
"""EditTemplate 剪辑模板领域实体单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.edit_template import EditTemplate, EditTemplateStatus
|
||||
from packages.domain.editing_mode import EditingMode
|
||||
|
||||
|
||||
class TestEditTemplateStatus:
|
||||
def test_values(self):
|
||||
assert EditTemplateStatus.ACTIVE.value == "active"
|
||||
assert EditTemplateStatus.INACTIVE.value == "inactive"
|
||||
|
||||
|
||||
class TestEditTemplateCreate:
|
||||
def test_create_default(self):
|
||||
tpl = EditTemplate.create(name="测试模板")
|
||||
assert tpl.id
|
||||
assert tpl.name == "测试模板"
|
||||
assert tpl.editing_mode == EditingMode.ONE_TAKE.value
|
||||
assert tpl.status == EditTemplateStatus.ACTIVE
|
||||
assert tpl.version == 1
|
||||
assert tpl.config == {}
|
||||
assert tpl.description == ""
|
||||
assert tpl.sort_weight == 0
|
||||
|
||||
def test_create_strips_name(self):
|
||||
tpl = EditTemplate.create(name=" 我的模板 ")
|
||||
assert tpl.name == "我的模板"
|
||||
|
||||
def test_create_empty_name_raises(self):
|
||||
with pytest.raises(ValueError, match="模板名称不能为空"):
|
||||
EditTemplate.create(name="")
|
||||
|
||||
def test_create_whitespace_name_raises(self):
|
||||
with pytest.raises(ValueError, match="模板名称不能为空"):
|
||||
EditTemplate.create(name=" ")
|
||||
|
||||
def test_create_valid_editing_modes(self):
|
||||
for mode in EditingMode:
|
||||
tpl = EditTemplate.create(name=f"模板_{mode.value}", editing_mode=mode.value)
|
||||
assert tpl.editing_mode == mode.value
|
||||
|
||||
def test_create_invalid_editing_mode_raises(self):
|
||||
with pytest.raises(ValueError, match="无效的 editing_mode"):
|
||||
EditTemplate.create(name="模板", editing_mode="invalid_mode")
|
||||
|
||||
def test_create_empty_editing_mode_defaults_to_one_take(self):
|
||||
tpl = EditTemplate.create(name="模板", editing_mode="")
|
||||
assert tpl.editing_mode == EditingMode.ONE_TAKE.value
|
||||
|
||||
def test_create_with_config(self):
|
||||
config = {"key": "value"}
|
||||
tpl = EditTemplate.create(name="模板", config=config)
|
||||
assert tpl.config == config
|
||||
|
||||
def test_create_none_config_defaults_to_empty(self):
|
||||
tpl = EditTemplate.create(name="模板", config=None)
|
||||
assert tpl.config == {}
|
||||
|
||||
def test_create_with_custom_status(self):
|
||||
tpl = EditTemplate.create(name="模板", status=EditTemplateStatus.INACTIVE)
|
||||
assert tpl.status == EditTemplateStatus.INACTIVE
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
t1 = EditTemplate.create(name="t1")
|
||||
t2 = EditTemplate.create(name="t2")
|
||||
assert t1.id != t2.id
|
||||
+424
-564
File diff suppressed because it is too large
Load Diff
@@ -1,121 +1,134 @@
|
||||
"""
|
||||
Feature Flags 基础设施层单元测试
|
||||
Feature Flags 基础设施测试.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.infrastructure.feature_flags import (
|
||||
FeatureFlag,
|
||||
FeatureFlags,
|
||||
FeatureScope,
|
||||
feature_flags,
|
||||
)
|
||||
|
||||
|
||||
class TestFeatureFlag:
|
||||
"""FeatureFlag 单个开关测试"""
|
||||
class TestFeatureFlagDefaults:
|
||||
"""FeatureFlag 默认值."""
|
||||
|
||||
def test_default_values(self):
|
||||
"""测试默认值"""
|
||||
flag = FeatureFlag(name="test_flag")
|
||||
assert flag.name == "test_flag"
|
||||
assert flag.description == ""
|
||||
def test_default_enabled(self):
|
||||
flag = FeatureFlag(name="test")
|
||||
assert flag.global_enabled is True
|
||||
assert flag.plan_overrides == {}
|
||||
assert flag.user_overrides == {}
|
||||
assert flag.description == ""
|
||||
|
||||
def test_is_enabled_global_true(self):
|
||||
"""测试全局启用"""
|
||||
def test_custom_description(self):
|
||||
flag = FeatureFlag(name="test", description="测试功能")
|
||||
assert flag.description == "测试功能"
|
||||
|
||||
def test_global_disabled(self):
|
||||
flag = FeatureFlag(name="test", global_enabled=False)
|
||||
assert flag.global_enabled is False
|
||||
|
||||
|
||||
class TestFeatureFlagIsEnabled:
|
||||
"""is_enabled 优先级逻辑."""
|
||||
|
||||
def test_global_enabled_no_user_no_plan(self):
|
||||
flag = FeatureFlag(name="test", global_enabled=True)
|
||||
assert flag.is_enabled() is True
|
||||
|
||||
def test_is_enabled_global_false(self):
|
||||
"""测试全局禁用"""
|
||||
def test_global_disabled_no_user_no_plan(self):
|
||||
flag = FeatureFlag(name="test", global_enabled=False)
|
||||
assert flag.is_enabled() is False
|
||||
|
||||
def test_is_enabled_plan_override(self):
|
||||
"""测试套餐级别覆盖"""
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False, "premium": True},
|
||||
)
|
||||
# free 套餐被覆盖为 False
|
||||
assert flag.is_enabled(user_plan="free") is False
|
||||
# premium 套餐覆盖为 True
|
||||
assert flag.is_enabled(user_plan="premium") is True
|
||||
# 没有覆盖的套餐用全局值
|
||||
assert flag.is_enabled(user_plan="basic") is True
|
||||
|
||||
def test_is_enabled_user_override_priority(self):
|
||||
"""测试用户白名单优先级最高"""
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=False,
|
||||
plan_overrides={"premium": True},
|
||||
user_overrides={"user-1": True, "user-2": False},
|
||||
)
|
||||
# 用户白名单 True → 全局禁用也能启用
|
||||
assert flag.is_enabled(user_plan="free", user_id="user-1") is True
|
||||
# 用户白名单 False → premium 套餐也禁用
|
||||
assert flag.is_enabled(user_plan="premium", user_id="user-2") is False
|
||||
# 没有用户白名单 → 走套餐级别
|
||||
assert flag.is_enabled(user_plan="premium", user_id="user-3") is True
|
||||
|
||||
def test_is_enabled_no_params(self):
|
||||
"""测试不传任何参数时使用全局值"""
|
||||
flag = FeatureFlag(name="test", global_enabled=True)
|
||||
assert flag.is_enabled() is True
|
||||
|
||||
def test_is_enabled_empty_strings_treated_as_none(self):
|
||||
"""测试空字符串 user_id/user_plan 不触发覆盖"""
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
user_overrides={"": True}, # 空字符串key
|
||||
)
|
||||
# 空字符串 user_id 被当作 falsy,不走用户白名单分支
|
||||
assert flag.is_enabled(user_id="", user_plan="") is True
|
||||
|
||||
def test_plan_override_does_not_affect_other_plans(self):
|
||||
"""测试套餐覆盖不影响其他套餐"""
|
||||
def test_plan_override_free_disabled(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
)
|
||||
assert flag.is_enabled(user_plan="free") is False
|
||||
assert flag.is_enabled(user_plan="basic") is True
|
||||
assert flag.is_enabled(user_plan="premium") is True
|
||||
assert flag.is_enabled(user_plan="premium") is True # 走全局
|
||||
|
||||
def test_user_override_can_enable_for_disabled_plan(self):
|
||||
"""测试用户白名单可以为被禁用的套餐用户单独启用"""
|
||||
def test_plan_override_premium_enabled(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=False,
|
||||
plan_overrides={"premium": True},
|
||||
user_overrides={"special-user": True},
|
||||
)
|
||||
# free 套餐用户 + 白名单 → 启用
|
||||
assert flag.is_enabled(user_plan="free", user_id="special-user") is True
|
||||
assert flag.is_enabled(user_plan="premium") is True
|
||||
assert flag.is_enabled(user_plan="free") is False # 走全局
|
||||
|
||||
def test_user_override_can_disable_for_enabled_plan(self):
|
||||
"""测试用户白名单可以为启用套餐的用户单独禁用"""
|
||||
def test_user_override_highest_priority(self):
|
||||
"""用户白名单优先级最高"""
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=False,
|
||||
plan_overrides={"premium": True},
|
||||
user_overrides={"user_1": True},
|
||||
)
|
||||
# free 套餐全局禁用,但用户在白名单 → 启用
|
||||
assert flag.is_enabled(user_plan="free", user_id="user_1") is True
|
||||
|
||||
def test_user_override_disable_overrides_plan(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
user_overrides={"bad-user": False},
|
||||
plan_overrides={"premium": True},
|
||||
user_overrides={"user_1": False},
|
||||
)
|
||||
assert flag.is_enabled(user_id="bad-user") is False
|
||||
# premium 套餐应该启用,但用户在禁用名单 → 禁用
|
||||
assert flag.is_enabled(user_plan="premium", user_id="user_1") is False
|
||||
|
||||
def test_user_not_in_overrides_falls_to_plan(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
user_overrides={"user_x": True},
|
||||
)
|
||||
assert flag.is_enabled(user_plan="free", user_id="user_other") is False
|
||||
|
||||
def test_none_user_id_skipped(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
user_overrides={"None": False},
|
||||
)
|
||||
assert flag.is_enabled(user_plan="premium", user_id=None) is True
|
||||
|
||||
def test_none_plan_skipped(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
)
|
||||
assert flag.is_enabled(user_plan=None) is True
|
||||
|
||||
def test_empty_user_id_skipped(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
)
|
||||
assert flag.is_enabled(user_plan="premium", user_id="") is True
|
||||
|
||||
def test_empty_plan_skipped(self):
|
||||
flag = FeatureFlag(
|
||||
name="test",
|
||||
global_enabled=True,
|
||||
plan_overrides={"free": False},
|
||||
)
|
||||
assert flag.is_enabled(user_plan="") is True
|
||||
|
||||
|
||||
class TestFeatureScope:
|
||||
"""FeatureScope 常量测试"""
|
||||
"""FeatureScope 常量."""
|
||||
|
||||
def test_scope_constants(self):
|
||||
"""测试所有常量存在"""
|
||||
def test_constants_exist(self):
|
||||
assert FeatureScope.AI_VOICE_GENERATION == "ai_voice_generation"
|
||||
assert FeatureScope.DEDUPLICATION_REPORT == "deduplication_report"
|
||||
assert FeatureScope.BATCH_EXPORT == "batch_export"
|
||||
@@ -123,225 +136,108 @@ class TestFeatureScope:
|
||||
assert FeatureScope.RECIPE_REUSE == "recipe_reuse"
|
||||
|
||||
|
||||
class TestFeatureFlags:
|
||||
"""FeatureFlags 管理器测试"""
|
||||
class TestFeatureFlagsManager:
|
||||
"""FeatureFlags 管理器."""
|
||||
|
||||
@pytest.fixture
|
||||
def flags(self):
|
||||
"""创建新的 FeatureFlags 实例(不影响全局单例)"""
|
||||
def ff(self):
|
||||
return FeatureFlags()
|
||||
|
||||
# ===== 初始化 =====
|
||||
def test_default_flags_registered(self, ff):
|
||||
flags = ff.list_flags()
|
||||
assert len(flags) >= 5
|
||||
assert FeatureScope.AI_VOICE_GENERATION in flags
|
||||
assert FeatureScope.DEDUPLICATION_REPORT in flags
|
||||
assert FeatureScope.BATCH_EXPORT in flags
|
||||
assert FeatureScope.MULTI_PLATFORM_OUTPUT in flags
|
||||
assert FeatureScope.RECIPE_REUSE in flags
|
||||
|
||||
def test_default_flags_exist(self, flags):
|
||||
"""测试默认 flags 已注册"""
|
||||
all_flags = flags.list_flags()
|
||||
assert FeatureScope.AI_VOICE_GENERATION in all_flags
|
||||
assert FeatureScope.DEDUPLICATION_REPORT in all_flags
|
||||
assert FeatureScope.BATCH_EXPORT in all_flags
|
||||
assert FeatureScope.MULTI_PLATFORM_OUTPUT in all_flags
|
||||
assert FeatureScope.RECIPE_REUSE in all_flags
|
||||
|
||||
def test_default_ai_voice_generation(self, flags):
|
||||
"""测试 AI 配音功能默认配置"""
|
||||
# free 套餐不可用
|
||||
assert flags.is_enabled("ai_voice_generation", user_plan="free") is False
|
||||
# basic 套餐可用
|
||||
assert flags.is_enabled("ai_voice_generation", user_plan="basic") is True
|
||||
# premium 套餐可用
|
||||
assert flags.is_enabled("ai_voice_generation", user_plan="premium") is True
|
||||
|
||||
def test_default_deduplication_report(self, flags):
|
||||
"""测试去重报告默认配置(仅 premium)"""
|
||||
assert flags.is_enabled("deduplication_report", user_plan="free") is False
|
||||
assert flags.is_enabled("deduplication_report", user_plan="basic") is False
|
||||
assert flags.is_enabled("deduplication_report", user_plan="premium") is True
|
||||
|
||||
def test_default_multi_platform_output(self, flags):
|
||||
"""测试多平台输出默认配置(仅 premium)"""
|
||||
assert flags.is_enabled("multi_platform_output", user_plan="free") is False
|
||||
assert flags.is_enabled("multi_platform_output", user_plan="basic") is False
|
||||
assert flags.is_enabled("multi_platform_output", user_plan="premium") is True
|
||||
|
||||
def test_default_batch_export(self, flags):
|
||||
"""测试批量导出默认配置"""
|
||||
assert flags.is_enabled("batch_export", user_plan="free") is False
|
||||
assert flags.is_enabled("batch_export", user_plan="basic") is True
|
||||
assert flags.is_enabled("batch_export", user_plan="premium") is True
|
||||
|
||||
def test_default_recipe_reuse(self, flags):
|
||||
"""测试配方复用默认配置"""
|
||||
assert flags.is_enabled("recipe_reuse", user_plan="free") is False
|
||||
assert flags.is_enabled("recipe_reuse", user_plan="basic") is True
|
||||
assert flags.is_enabled("recipe_reuse", user_plan="premium") is True
|
||||
|
||||
# ===== 注册新 flag =====
|
||||
|
||||
def test_register_new_flag(self, flags):
|
||||
"""测试注册新的 feature flag"""
|
||||
new_flag = FeatureFlag(name="new_feature", description="新功能", global_enabled=False)
|
||||
flags.register(new_flag)
|
||||
|
||||
assert flags.get("new_feature") is not None
|
||||
assert flags.get("new_feature").description == "新功能"
|
||||
assert flags.is_enabled("new_feature") is False
|
||||
|
||||
def test_register_overwrites_existing(self, flags):
|
||||
"""测试注册同名 flag 会覆盖"""
|
||||
flag1 = FeatureFlag(name="test", global_enabled=True, description="v1")
|
||||
flags.register(flag1)
|
||||
assert flags.get("test").description == "v1"
|
||||
|
||||
flag2 = FeatureFlag(name="test", global_enabled=False, description="v2")
|
||||
flags.register(flag2)
|
||||
assert flags.get("test").description == "v2"
|
||||
assert flags.is_enabled("test") is False
|
||||
|
||||
# ===== get 方法 =====
|
||||
|
||||
def test_get_existing_flag(self, flags):
|
||||
"""测试获取存在的 flag"""
|
||||
flag = flags.get("ai_voice_generation")
|
||||
def test_get_existing_flag(self, ff):
|
||||
flag = ff.get(FeatureScope.BATCH_EXPORT)
|
||||
assert flag is not None
|
||||
assert flag.name == "ai_voice_generation"
|
||||
assert flag.name == FeatureScope.BATCH_EXPORT
|
||||
|
||||
def test_get_nonexistent_flag(self, flags):
|
||||
"""测试获取不存在的 flag 返回 None"""
|
||||
assert flags.get("nonexistent") is None
|
||||
def test_get_nonexistent_flag(self, ff):
|
||||
assert ff.get("nonexistent") is None
|
||||
|
||||
# ===== is_enabled 方法 =====
|
||||
def test_is_enabled_global(self, ff):
|
||||
assert ff.is_enabled(FeatureScope.BATCH_EXPORT) is True
|
||||
|
||||
def test_is_enabled_nonexistent_flag_returns_false(self, flags):
|
||||
"""测试不存在的 flag 返回 False"""
|
||||
assert flags.is_enabled("nonexistent_flag") is False
|
||||
def test_is_enabled_nonexistent_returns_false(self, ff):
|
||||
"""未知 flag 默认禁用(安全保守)"""
|
||||
assert ff.is_enabled("unknown_feature") is False
|
||||
|
||||
def test_is_enabled_without_plan_or_user(self, flags):
|
||||
"""测试不传套餐和用户ID"""
|
||||
assert flags.is_enabled("ai_voice_generation") is True
|
||||
def test_free_plan_ai_voice_disabled(self, ff):
|
||||
"""AI 配音 free 套餐不可用"""
|
||||
assert ff.is_enabled(FeatureScope.AI_VOICE_GENERATION, user_plan="free") is False
|
||||
|
||||
# ===== set_global =====
|
||||
def test_premium_plan_ai_voice_enabled(self, ff):
|
||||
assert ff.is_enabled(FeatureScope.AI_VOICE_GENERATION, user_plan="premium") is True
|
||||
|
||||
def test_set_global_enable(self, flags):
|
||||
"""测试设置全局启用"""
|
||||
flags.set_global("ai_voice_generation", enabled=False)
|
||||
assert flags.is_enabled("ai_voice_generation", user_plan="premium") is False
|
||||
def test_deduplication_only_premium(self, ff):
|
||||
"""去重报告仅 premium 可用"""
|
||||
assert ff.is_enabled(FeatureScope.DEDUPLICATION_REPORT, user_plan="free") is False
|
||||
assert ff.is_enabled(FeatureScope.DEDUPLICATION_REPORT, user_plan="basic") is False
|
||||
assert ff.is_enabled(FeatureScope.DEDUPLICATION_REPORT, user_plan="premium") is True
|
||||
|
||||
def test_set_global_disable(self, flags):
|
||||
"""测试设置全局禁用"""
|
||||
flags.set_global("deduplication_report", enabled=False)
|
||||
assert flags.is_enabled("deduplication_report", user_plan="premium") is False
|
||||
def test_set_global(self, ff):
|
||||
ff.set_global(FeatureScope.BATCH_EXPORT, False)
|
||||
assert ff.is_enabled(FeatureScope.BATCH_EXPORT) is False
|
||||
# 恢复
|
||||
ff.set_global(FeatureScope.BATCH_EXPORT, True)
|
||||
assert ff.is_enabled(FeatureScope.BATCH_EXPORT) is True
|
||||
|
||||
def test_set_global_nonexistent_raises(self, flags):
|
||||
"""测试设置不存在的 flag 抛出异常"""
|
||||
with pytest.raises(KeyError, match="not found"):
|
||||
flags.set_global("nonexistent", enabled=True)
|
||||
def test_set_global_nonexistent_raises(self, ff):
|
||||
with pytest.raises(KeyError):
|
||||
ff.set_global("nonexistent", True)
|
||||
|
||||
# ===== set_plan_override =====
|
||||
def test_set_plan_override(self, ff):
|
||||
ff.set_plan_override(FeatureScope.BATCH_EXPORT, "enterprise", False)
|
||||
assert ff.is_enabled(FeatureScope.BATCH_EXPORT, user_plan="enterprise") is False
|
||||
|
||||
def test_set_plan_override(self, flags):
|
||||
"""测试设置套餐覆盖"""
|
||||
# 先确认 basic 套餐默认是去重报告禁用
|
||||
assert flags.is_enabled("deduplication_report", user_plan="basic") is False
|
||||
def test_set_plan_override_nonexistent_raises(self, ff):
|
||||
with pytest.raises(KeyError):
|
||||
ff.set_plan_override("nonexistent", "free", True)
|
||||
|
||||
flags.set_plan_override("deduplication_report", "basic", True)
|
||||
assert flags.is_enabled("deduplication_report", user_plan="basic") is True
|
||||
def test_set_user_override(self, ff):
|
||||
ff.set_user_override(FeatureScope.BATCH_EXPORT, "user_42", True)
|
||||
assert (
|
||||
ff.is_enabled(
|
||||
FeatureScope.BATCH_EXPORT,
|
||||
user_plan="free",
|
||||
user_id="user_42",
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
def test_set_plan_override_nonexistent_raises(self, flags):
|
||||
"""测试设置不存在 flag 的套餐覆盖抛出异常"""
|
||||
with pytest.raises(KeyError, match="not found"):
|
||||
flags.set_plan_override("nonexistent", "free", True)
|
||||
def test_set_user_override_nonexistent_raises(self, ff):
|
||||
with pytest.raises(KeyError):
|
||||
ff.set_user_override("nonexistent", "user_1", True)
|
||||
|
||||
# ===== set_user_override =====
|
||||
def test_register_new_flag(self, ff):
|
||||
new_flag = FeatureFlag(name="new_feature", description="新功能")
|
||||
ff.register(new_flag)
|
||||
assert ff.get("new_feature") is not None
|
||||
assert ff.is_enabled("new_feature") is True
|
||||
|
||||
def test_set_user_override_enable(self, flags):
|
||||
"""测试设置用户白名单启用"""
|
||||
assert flags.is_enabled("deduplication_report", user_plan="free", user_id="user-1") is False
|
||||
def test_register_overwrites(self, ff):
|
||||
flag1 = FeatureFlag(name="test", global_enabled=True)
|
||||
flag2 = FeatureFlag(name="test", global_enabled=False)
|
||||
ff.register(flag1)
|
||||
ff.register(flag2)
|
||||
assert ff.is_enabled("test") is False
|
||||
|
||||
flags.set_user_override("deduplication_report", "user-1", True)
|
||||
assert flags.is_enabled("deduplication_report", user_plan="free", user_id="user-1") is True
|
||||
def test_list_flags_returns_copy(self, ff):
|
||||
flags = ff.list_flags()
|
||||
assert isinstance(flags, dict)
|
||||
# 修改返回值不影响内部
|
||||
flags["new"] = FeatureFlag(name="new")
|
||||
assert ff.get("new") is None
|
||||
|
||||
def test_set_user_override_disable(self, flags):
|
||||
"""测试设置用户白名单禁用"""
|
||||
assert flags.is_enabled("batch_export", user_plan="premium", user_id="user-2") is True
|
||||
|
||||
flags.set_user_override("batch_export", "user-2", False)
|
||||
assert flags.is_enabled("batch_export", user_plan="premium", user_id="user-2") is False
|
||||
|
||||
def test_set_user_override_nonexistent_raises(self, flags):
|
||||
"""测试设置不存在 flag 的用户覆盖抛出异常"""
|
||||
with pytest.raises(KeyError, match="not found"):
|
||||
flags.set_user_override("nonexistent", "user-1", True)
|
||||
|
||||
# ===== list_flags =====
|
||||
|
||||
def test_list_flags_returns_copy(self, flags):
|
||||
"""测试 list_flags 返回副本"""
|
||||
all_flags = flags.list_flags()
|
||||
all_flags["fake"] = FeatureFlag(name="fake")
|
||||
|
||||
# 原注册表不应被修改
|
||||
assert "fake" not in flags.list_flags()
|
||||
|
||||
def test_list_flags_count(self, flags):
|
||||
"""测试默认 flag 数量"""
|
||||
all_flags = flags.list_flags()
|
||||
assert len(all_flags) == 5 # 5 个默认 flag
|
||||
|
||||
# ===== get_enabled_for_plan =====
|
||||
|
||||
def test_get_enabled_for_free_plan(self, flags):
|
||||
"""测试 free 套餐启用的功能"""
|
||||
enabled = flags.get_enabled_for_plan("free")
|
||||
# free 套餐应该只有 0 个默认启用的功能?不对,让我看看...
|
||||
# 所有5个默认功能 free 套餐都是 False 吗?
|
||||
# AI_VOICE_GENERATION: free=False
|
||||
# DEDUPLICATION_REPORT: free=False, basic=False
|
||||
# BATCH_EXPORT: free=False
|
||||
# MULTI_PLATFORM_OUTPUT: free=False, basic=False
|
||||
# RECIPE_REUSE: free=False
|
||||
# 所以 free 套餐一个都没有?
|
||||
assert len(enabled) == 0
|
||||
|
||||
def test_get_enabled_for_premium_plan(self, flags):
|
||||
"""测试 premium 套餐启用的功能"""
|
||||
enabled = flags.get_enabled_for_plan("premium")
|
||||
# premium 套餐所有功能都应该启用
|
||||
assert len(enabled) == 5
|
||||
assert "ai_voice_generation" in enabled
|
||||
assert "deduplication_report" in enabled
|
||||
assert "batch_export" in enabled
|
||||
assert "multi_platform_output" in enabled
|
||||
assert "recipe_reuse" in enabled
|
||||
|
||||
def test_get_enabled_for_basic_plan(self, flags):
|
||||
"""测试 basic 套餐启用的功能"""
|
||||
enabled = flags.get_enabled_for_plan("basic")
|
||||
# basic: ai_voice=True, dedup=False, batch=True, multi=False, recipe=True
|
||||
assert "ai_voice_generation" in enabled
|
||||
assert "deduplication_report" not in enabled
|
||||
assert "batch_export" in enabled
|
||||
assert "multi_platform_output" not in enabled
|
||||
assert "recipe_reuse" in enabled
|
||||
assert len(enabled) == 3
|
||||
|
||||
|
||||
class TestGlobalSingleton:
|
||||
"""全局单例测试"""
|
||||
|
||||
def test_global_singleton_exists(self):
|
||||
"""测试全局单例存在"""
|
||||
assert feature_flags is not None
|
||||
assert isinstance(feature_flags, FeatureFlags)
|
||||
|
||||
def test_global_singleton_has_defaults(self):
|
||||
"""测试全局单例有默认配置"""
|
||||
assert feature_flags.get("ai_voice_generation") is not None
|
||||
assert feature_flags.get("deduplication_report") is not None
|
||||
|
||||
def test_global_singleton_independent_from_new_instance(self):
|
||||
"""测试全局单例与新实例相互独立"""
|
||||
new_flags = FeatureFlags()
|
||||
new_flags.set_global("ai_voice_generation", False)
|
||||
|
||||
# 全局单例不应受影响
|
||||
assert feature_flags.is_enabled("ai_voice_generation") is True
|
||||
def test_get_enabled_for_plan(self, ff):
|
||||
free_features = ff.get_enabled_for_plan("free")
|
||||
premium_features = ff.get_enabled_for_plan("premium")
|
||||
assert len(premium_features) >= len(free_features)
|
||||
# free 套餐功能是 premium 的子集
|
||||
for f in free_features:
|
||||
assert f in premium_features
|
||||
|
||||
Executable
+206
@@ -0,0 +1,206 @@
|
||||
"""FFmpeg工具函数纯逻辑测试 — chain_filters / resolve_xfade_transition / build_xfade_filter_chain."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from video_processing.ffmpeg_utils import (
|
||||
XFADE_TRANSITION_MAP,
|
||||
build_xfade_filter_chain,
|
||||
chain_filters,
|
||||
resolve_xfade_transition,
|
||||
)
|
||||
|
||||
|
||||
class TestChainFilters:
|
||||
"""chain_filters 滤镜串联测试."""
|
||||
|
||||
def test_single_filter(self):
|
||||
"""单个滤镜."""
|
||||
result = chain_filters(["scale=1280:720"], "v0")
|
||||
assert result == "[0:v]scale=1280:720[v0]"
|
||||
|
||||
def test_multiple_filters(self):
|
||||
"""多个滤镜用逗号连接."""
|
||||
result = chain_filters(["scale=1280:720", "fps=25", "format=yuv420p"], "out")
|
||||
assert result == "[0:v]scale=1280:720,fps=25,format=yuv420p[out]"
|
||||
|
||||
def test_empty_filters(self):
|
||||
"""空滤镜列表."""
|
||||
result = chain_filters([], "v0")
|
||||
assert result == "[0:v][v0]"
|
||||
|
||||
def test_custom_input_label(self):
|
||||
"""自定义输入标签."""
|
||||
result = chain_filters(["scale=640:480"], "v1", input_label="1:v")
|
||||
assert result == "[1:v]scale=640:480[v1]"
|
||||
|
||||
|
||||
class TestResolveXfadeTransition:
|
||||
"""resolve_xfade_transition 转场名称映射测试."""
|
||||
|
||||
def test_direct_match_fade(self):
|
||||
"""fade直接匹配."""
|
||||
assert resolve_xfade_transition("fade") == "fade"
|
||||
|
||||
def test_direct_match_dissolve(self):
|
||||
"""dissolve直接匹配."""
|
||||
assert resolve_xfade_transition("dissolve") == "dissolve"
|
||||
|
||||
def test_alias_crossfade(self):
|
||||
"""crossfade别名→dissolve."""
|
||||
assert resolve_xfade_transition("crossfade") == "dissolve"
|
||||
|
||||
def test_alias_slide_left(self):
|
||||
"""slide_left别名→slideleft."""
|
||||
assert resolve_xfade_transition("slide_left") == "slideleft"
|
||||
|
||||
def test_unknown_fallback_to_fade(self):
|
||||
"""未知值回退到fade."""
|
||||
assert resolve_xfade_transition("nonexistent_effect") == "fade"
|
||||
|
||||
def test_empty_string_fallback(self):
|
||||
"""空字符串回退."""
|
||||
assert resolve_xfade_transition("") == "fade"
|
||||
|
||||
def test_enum_value_support(self):
|
||||
"""支持带value属性的枚举对象."""
|
||||
|
||||
class FakeEnum:
|
||||
value = "slideup"
|
||||
|
||||
assert resolve_xfade_transition(FakeEnum()) == "slideup"
|
||||
|
||||
def test_all_map_keys_resolve(self):
|
||||
"""映射表中所有key都能解析到有效值."""
|
||||
for key in XFADE_TRANSITION_MAP:
|
||||
result = resolve_xfade_transition(key)
|
||||
assert result and isinstance(result, str)
|
||||
assert result != ""
|
||||
|
||||
def test_cut_is_special_fallback(self):
|
||||
"""cut不在映射表中→回退到fade(硬切由调用方处理)."""
|
||||
# cut是特殊值,不在映射表里
|
||||
result = resolve_xfade_transition("cut")
|
||||
# 不在映射表里就fallback到fade
|
||||
assert result == "fade"
|
||||
|
||||
|
||||
class TestBuildXfadeFilterChain:
|
||||
"""build_xfade_filter_chain 转场滤镜链构建测试."""
|
||||
|
||||
def test_zero_clips(self):
|
||||
"""0个片段→空字符串+0时长."""
|
||||
filter_str, total_dur = build_xfade_filter_chain([], [], [])
|
||||
assert filter_str == ""
|
||||
assert total_dur == 0.0
|
||||
|
||||
def test_single_clip(self):
|
||||
"""1个片段→直接copy,总时长等于片段时长."""
|
||||
filter_str, total_dur = build_xfade_filter_chain([10.0], ["v0"], [], output_label="outv")
|
||||
assert "[v0]copy[outv]" in filter_str
|
||||
assert total_dur == pytest.approx(10.0)
|
||||
|
||||
def test_two_clips_basic(self):
|
||||
"""2个片段基本转场."""
|
||||
filter_str, total_dur = build_xfade_filter_chain(
|
||||
[5.0, 5.0],
|
||||
["v0", "v1"],
|
||||
["", "fade"],
|
||||
transition_duration=0.5,
|
||||
output_label="outv",
|
||||
)
|
||||
assert "xfade=transition=fade" in filter_str
|
||||
assert "offset=" in filter_str
|
||||
# 总时长 = 5 + 5 - 转场重叠
|
||||
assert total_dur == pytest.approx(9.5)
|
||||
|
||||
def test_three_clips_chain(self):
|
||||
"""3个片段形成链式转场."""
|
||||
filter_str, total_dur = build_xfade_filter_chain(
|
||||
[3.0, 4.0, 5.0],
|
||||
["v0", "v1", "v2"],
|
||||
["", "fade", "dissolve"],
|
||||
transition_duration=0.5,
|
||||
output_label="out",
|
||||
)
|
||||
# 应该有2个xfade操作
|
||||
assert filter_str.count("xfade=") == 2
|
||||
assert "transition=fade" in filter_str
|
||||
assert "transition=dissolve" in filter_str
|
||||
# 总时长 = 3+4+5 - 2*0.5 = 11
|
||||
assert total_dur == pytest.approx(11.0)
|
||||
|
||||
def test_transition_duration_clamped_to_clip(self):
|
||||
"""转场时长不能超过单个片段时长."""
|
||||
filter_str, total_dur = build_xfade_filter_chain(
|
||||
[2.0, 1.0],
|
||||
["v0", "v1"],
|
||||
["", "fade"],
|
||||
transition_duration=3.0, # 比第二个片段还长
|
||||
output_label="outv",
|
||||
)
|
||||
# 转场时长被钳制到第二个片段时长(1.0)
|
||||
assert "duration=1.000" in filter_str
|
||||
assert total_dur == pytest.approx(2.0) # 2 + 1 - 1 = 2
|
||||
|
||||
def test_very_short_clip_min_transition(self):
|
||||
"""极短片段至少保留1ms转场."""
|
||||
filter_str, total_dur = build_xfade_filter_chain(
|
||||
[1.0, 0.0001],
|
||||
["v0", "v1"],
|
||||
["", "fade"],
|
||||
transition_duration=0.5,
|
||||
output_label="outv",
|
||||
)
|
||||
# 至少有1ms
|
||||
assert "duration=0.001" in filter_str
|
||||
|
||||
def test_transition_offset_calculation(self):
|
||||
"""offset计算验证."""
|
||||
filter_str, _ = build_xfade_filter_chain(
|
||||
[10.0, 10.0],
|
||||
["v0", "v1"],
|
||||
["", "fade"],
|
||||
transition_duration=1.0,
|
||||
output_label="outv",
|
||||
)
|
||||
# offset = max(0, 10 - 1*1) = 9
|
||||
assert "offset=9.000" in filter_str
|
||||
|
||||
def test_fewer_transitions_than_clips(self):
|
||||
"""转场列表比片段少时使用cut(fallback to fade)."""
|
||||
filter_str, total_dur = build_xfade_filter_chain(
|
||||
[5.0, 5.0, 5.0],
|
||||
["v0", "v1", "v2"],
|
||||
["fade"], # 只有1个转场,第2个转场缺省
|
||||
transition_duration=0.5,
|
||||
output_label="out",
|
||||
)
|
||||
# 应该有2个xfade
|
||||
assert filter_str.count("xfade=") == 2
|
||||
# 第二个xfade的转场是cut→fade fallback
|
||||
assert filter_str.count("transition=fade") == 2
|
||||
|
||||
def test_output_label_final_clip(self):
|
||||
"""最后一个xfade的输出标签是output_label."""
|
||||
filter_str, _ = build_xfade_filter_chain(
|
||||
[3.0, 4.0, 5.0],
|
||||
["v0", "v1", "v2"],
|
||||
["", "fade", "slideleft"],
|
||||
output_label="final_v",
|
||||
)
|
||||
assert filter_str.rstrip().endswith("[final_v]")
|
||||
|
||||
def test_intermediate_labels(self):
|
||||
"""中间步骤使用xf1, xf2等标签(从i=1开始计数)."""
|
||||
filter_str, _ = build_xfade_filter_chain(
|
||||
[2.0, 3.0, 4.0, 5.0],
|
||||
["v0", "v1", "v2", "v3"],
|
||||
["", "fade", "fade", "fade"],
|
||||
output_label="out",
|
||||
)
|
||||
# 4个片段3次xfade,中间标签是xf1, xf2
|
||||
assert "[xf1]" in filter_str
|
||||
assert "[xf2]" in filter_str
|
||||
# 最后一个是[out]
|
||||
assert filter_str.rstrip().endswith("[out]")
|
||||
Executable
+230
@@ -0,0 +1,230 @@
|
||||
"""filter_presets 领域层单元测试 - 滤镜预设库"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.filter_presets import (
|
||||
FILTER_PRESET_LIBRARY,
|
||||
FilterPreset,
|
||||
build_ffmpeg_filter,
|
||||
get_filter_preset,
|
||||
list_filter_presets,
|
||||
)
|
||||
|
||||
|
||||
class TestFilterPreset:
|
||||
"""FilterPreset 数据类测试"""
|
||||
|
||||
def test_create_minimal(self):
|
||||
preset = FilterPreset(id="test", name="测试", category="basic")
|
||||
assert preset.id == "test"
|
||||
assert preset.name == "测试"
|
||||
assert preset.category == "basic"
|
||||
assert preset.description == ""
|
||||
assert preset.tags == []
|
||||
assert preset.brightness == 0.0
|
||||
assert preset.contrast == 1.0
|
||||
assert preset.saturation == 1.0
|
||||
assert preset.gamma == 1.0
|
||||
assert preset.gamma_r == 1.0
|
||||
assert preset.gamma_g == 1.0
|
||||
assert preset.gamma_b == 1.0
|
||||
assert preset.hue == 0.0
|
||||
assert preset.lut_url == ""
|
||||
|
||||
def test_create_with_all_params(self):
|
||||
preset = FilterPreset(
|
||||
id="custom",
|
||||
name="自定义",
|
||||
category="cinematic",
|
||||
description="电影感调色",
|
||||
tags=["电影", "调色"],
|
||||
brightness=0.1,
|
||||
contrast=1.2,
|
||||
saturation=0.9,
|
||||
gamma=1.1,
|
||||
gamma_r=1.05,
|
||||
gamma_g=1.0,
|
||||
gamma_b=0.95,
|
||||
hue=10.0,
|
||||
lut_url="http://example.com/lut.png",
|
||||
)
|
||||
assert preset.category == "cinematic"
|
||||
assert preset.description == "电影感调色"
|
||||
assert preset.tags == ["电影", "调色"]
|
||||
assert preset.brightness == 0.1
|
||||
assert preset.contrast == 1.2
|
||||
assert preset.lut_url == "http://example.com/lut.png"
|
||||
|
||||
def test_frozen_immutable(self):
|
||||
"""frozen dataclass 不可修改"""
|
||||
preset = FilterPreset(id="test", name="测试", category="basic")
|
||||
with pytest.raises(Exception): # FrozenInstanceError
|
||||
preset.name = "改名"
|
||||
|
||||
def test_tags_default_empty_list(self):
|
||||
preset = FilterPreset(id="test", name="测试", category="basic")
|
||||
assert preset.tags == []
|
||||
# 每次创建独立的 list
|
||||
preset2 = FilterPreset(id="test2", name="测试2", category="basic")
|
||||
assert preset.tags is not preset2.tags
|
||||
|
||||
|
||||
class TestFilterPresetLibrary:
|
||||
"""FILTER_PRESET_LIBRARY 预设库测试"""
|
||||
|
||||
def test_library_not_empty(self):
|
||||
assert len(FILTER_PRESET_LIBRARY) > 0
|
||||
|
||||
def test_all_presets_have_unique_ids(self):
|
||||
"""所有预设 ID 唯一"""
|
||||
ids = [p.id for p in FILTER_PRESET_LIBRARY]
|
||||
assert len(ids) == len(set(ids))
|
||||
|
||||
def test_all_presets_have_name_and_category(self):
|
||||
for preset in FILTER_PRESET_LIBRARY:
|
||||
assert preset.id, f"{preset} has no id"
|
||||
assert preset.name, f"{preset.id} has no name"
|
||||
assert preset.category, f"{preset.id} has no category"
|
||||
|
||||
def test_filter_none_exists(self):
|
||||
"""原图预设存在"""
|
||||
none_preset = next((p for p in FILTER_PRESET_LIBRARY if p.id == "filter_none"), None)
|
||||
assert none_preset is not None
|
||||
assert none_preset.name == "原图"
|
||||
assert none_preset.category == "basic"
|
||||
|
||||
def test_known_categories_exist(self):
|
||||
"""已知分类都有预设"""
|
||||
categories = {p.category for p in FILTER_PRESET_LIBRARY}
|
||||
assert "basic" in categories
|
||||
|
||||
def test_basic_category_presets(self):
|
||||
"""基础分类至少有几个预设"""
|
||||
basic = [p for p in FILTER_PRESET_LIBRARY if p.category == "basic"]
|
||||
assert len(basic) >= 3
|
||||
|
||||
def test_preset_params_in_reasonable_range(self):
|
||||
"""预设参数在合理范围内"""
|
||||
for preset in FILTER_PRESET_LIBRARY:
|
||||
assert -1.0 <= preset.brightness <= 1.0, f"{preset.id} brightness out of range"
|
||||
assert 0.0 <= preset.contrast <= 2.0, f"{preset.id} contrast out of range"
|
||||
assert 0.0 <= preset.saturation <= 3.0, f"{preset.id} saturation out of range"
|
||||
|
||||
|
||||
class TestGetFilterPreset:
|
||||
"""get_filter_preset 函数测试"""
|
||||
|
||||
def test_get_existing_preset(self):
|
||||
preset = get_filter_preset("filter_none")
|
||||
assert preset is not None
|
||||
assert preset.id == "filter_none"
|
||||
|
||||
def test_get_nonexistent_preset(self):
|
||||
assert get_filter_preset("nonexistent_filter") is None
|
||||
|
||||
def test_get_returns_correct_type(self):
|
||||
preset = get_filter_preset("filter_none")
|
||||
assert isinstance(preset, FilterPreset)
|
||||
|
||||
|
||||
class TestListFilterPresets:
|
||||
"""list_filter_presets 函数测试"""
|
||||
|
||||
def test_list_all(self):
|
||||
"""不带参数返回所有预设"""
|
||||
all_presets = list_filter_presets()
|
||||
assert len(all_presets) == len(FILTER_PRESET_LIBRARY)
|
||||
|
||||
def test_filter_by_category(self):
|
||||
"""按分类筛选"""
|
||||
basic_presets = list_filter_presets(category="basic")
|
||||
assert len(basic_presets) > 0
|
||||
assert all(p.category == "basic" for p in basic_presets)
|
||||
|
||||
def test_filter_by_nonexistent_category(self):
|
||||
"""不存在的分类返回空列表"""
|
||||
result = list_filter_presets(category="nonexistent_category")
|
||||
assert result == []
|
||||
|
||||
def test_search_by_name(self):
|
||||
"""按名称搜索"""
|
||||
result = list_filter_presets(keyword="明")
|
||||
assert len(result) >= 1
|
||||
assert any("明" in p.name for p in result)
|
||||
|
||||
def test_search_by_tag(self):
|
||||
"""按标签搜索"""
|
||||
# 找到有标签的预设
|
||||
tagged = [p for p in FILTER_PRESET_LIBRARY if p.tags]
|
||||
if tagged:
|
||||
tag = tagged[0].tags[0]
|
||||
result = list_filter_presets(keyword=tag)
|
||||
assert len(result) >= 1
|
||||
|
||||
def test_search_case_insensitive_in_name(self):
|
||||
"""搜索对中文名称有效"""
|
||||
result = list_filter_presets(keyword="原图")
|
||||
assert any(p.id == "filter_none" for p in result)
|
||||
|
||||
def test_search_empty_returns_all(self):
|
||||
"""空搜索返回所有"""
|
||||
result = list_filter_presets(keyword="")
|
||||
assert len(result) == len(FILTER_PRESET_LIBRARY)
|
||||
|
||||
def test_combined_category_and_search(self):
|
||||
"""同时按分类和搜索筛选"""
|
||||
result = list_filter_presets(category="basic", keyword="明")
|
||||
assert all(p.category == "basic" for p in result)
|
||||
if result:
|
||||
assert any("明" in p.name or any("明" in t for t in p.tags) for p in result)
|
||||
|
||||
def test_returns_list_of_filterpreset(self):
|
||||
result = list_filter_presets()
|
||||
assert all(isinstance(p, FilterPreset) for p in result)
|
||||
|
||||
|
||||
class TestBuildFfmpegFilter:
|
||||
"""build_ffmpeg_filter 函数测试"""
|
||||
|
||||
def test_filter_none_returns_empty_or_simple(self):
|
||||
"""原图滤镜应该返回空字符串或无操作滤镜"""
|
||||
result = build_ffmpeg_filter("filter_none", 100)
|
||||
# 应该是字符串,且不包含实质性调色参数
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_full_intensity(self):
|
||||
"""强度 100 时应用全量参数"""
|
||||
result = build_ffmpeg_filter("filter_brighten", 100)
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
def test_zero_intensity(self):
|
||||
"""强度 0 时应该是原图效果"""
|
||||
result = build_ffmpeg_filter("filter_brighten", 0)
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_half_intensity(self):
|
||||
"""强度 50 时参数减半"""
|
||||
result50 = build_ffmpeg_filter("filter_brighten", 50)
|
||||
result100 = build_ffmpeg_filter("filter_brighten", 100)
|
||||
# 50% 和 100% 的结果应该不同
|
||||
assert result50 != result100
|
||||
|
||||
def test_nonexistent_preset(self):
|
||||
"""不存在的预设返回空字符串或默认值"""
|
||||
result = build_ffmpeg_filter("nonexistent", 100)
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_intensity_clamped(self):
|
||||
"""强度超过 100 或低于 0 的处理"""
|
||||
result_high = build_ffmpeg_filter("filter_brighten", 150)
|
||||
result_low = build_ffmpeg_filter("filter_brighten", -10)
|
||||
assert isinstance(result_high, str)
|
||||
assert isinstance(result_low, str)
|
||||
|
||||
def test_contains_eq_filter(self):
|
||||
"""结果应该包含 eq 滤镜参数"""
|
||||
result = build_ffmpeg_filter("filter_brighten", 100)
|
||||
# FFmpeg eq 滤镜通常包含 brightness/contrast/saturation 等参数
|
||||
# 至少应该有滤镜相关的字符串
|
||||
assert len(result) > 0
|
||||
Executable
+139
@@ -0,0 +1,139 @@
|
||||
"""GeneratedVideo 生成视频领域实体单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.generated_video import GeneratedVideo
|
||||
|
||||
|
||||
class TestGeneratedVideoCreate:
|
||||
def test_create_normal(self):
|
||||
video = GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="我的视频",
|
||||
file_url="https://example.com/video.mp4",
|
||||
file_size=1024000,
|
||||
duration=30.5,
|
||||
width=1920,
|
||||
height=1080,
|
||||
fps=30.0,
|
||||
)
|
||||
assert video.id
|
||||
assert video.project_id == "proj1"
|
||||
assert video.generation_task_id == "task1"
|
||||
assert video.name == "我的视频"
|
||||
assert video.file_url == "https://example.com/video.mp4"
|
||||
assert video.file_size == 1024000
|
||||
assert video.duration == 30.5
|
||||
assert video.width == 1920
|
||||
assert video.height == 1080
|
||||
assert video.fps == 30.0
|
||||
assert video.status == "completed"
|
||||
assert video.review_status == "pending_review"
|
||||
assert video.is_duplicate is False
|
||||
assert video.generation_params == {}
|
||||
|
||||
def test_create_strips_whitespace(self):
|
||||
video = GeneratedVideo.create(
|
||||
project_id=" proj1 ",
|
||||
generation_task_id=" task1 ",
|
||||
name=" 我的视频 ",
|
||||
file_url=" https://example.com/video.mp4 ",
|
||||
user_id=" user1 ",
|
||||
)
|
||||
assert video.project_id == "proj1"
|
||||
assert video.generation_task_id == "task1"
|
||||
assert video.name == "我的视频"
|
||||
assert video.file_url == "https://example.com/video.mp4"
|
||||
assert video.user_id == "user1"
|
||||
|
||||
def test_create_empty_project_id_raises(self):
|
||||
with pytest.raises(ValueError, match="project_id cannot be empty"):
|
||||
GeneratedVideo.create(
|
||||
project_id="",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
)
|
||||
|
||||
def test_create_whitespace_project_id_raises(self):
|
||||
with pytest.raises(ValueError, match="project_id cannot be empty"):
|
||||
GeneratedVideo.create(
|
||||
project_id=" ",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
)
|
||||
|
||||
def test_create_empty_generation_task_id_raises(self):
|
||||
with pytest.raises(ValueError, match="generation_task_id cannot be empty"):
|
||||
GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
)
|
||||
|
||||
def test_create_empty_name_raises(self):
|
||||
with pytest.raises(ValueError, match="name cannot be empty"):
|
||||
GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="",
|
||||
file_url="https://example.com/v.mp4",
|
||||
)
|
||||
|
||||
def test_create_empty_file_url_raises(self):
|
||||
with pytest.raises(ValueError, match="file_url cannot be empty"):
|
||||
GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="",
|
||||
)
|
||||
|
||||
def test_create_default_values(self):
|
||||
video = GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
)
|
||||
assert video.file_size == 0
|
||||
assert video.duration == 0.0
|
||||
assert video.width == 0
|
||||
assert video.height == 0
|
||||
assert video.fps == 0.0
|
||||
assert video.thumbnail_url is None
|
||||
assert video.user_id == ""
|
||||
assert video.generation_params == {}
|
||||
|
||||
def test_create_with_generation_params(self):
|
||||
params = {"mode": "pip", "resolution": "1080p"}
|
||||
video = GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
generation_params=params,
|
||||
)
|
||||
assert video.generation_params == params
|
||||
|
||||
def test_create_none_generation_params(self):
|
||||
video = GeneratedVideo.create(
|
||||
project_id="proj1",
|
||||
generation_task_id="task1",
|
||||
name="视频",
|
||||
file_url="https://example.com/v.mp4",
|
||||
generation_params=None,
|
||||
)
|
||||
assert video.generation_params == {}
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
v1 = GeneratedVideo.create(
|
||||
project_id="proj1", generation_task_id="t1", name="v1", file_url="https://a.com/1.mp4"
|
||||
)
|
||||
v2 = GeneratedVideo.create(
|
||||
project_id="proj1", generation_task_id="t2", name="v2", file_url="https://a.com/2.mp4"
|
||||
)
|
||||
assert v1.id != v2.id
|
||||
Executable
+300
@@ -0,0 +1,300 @@
|
||||
"""GenerationTask 生成任务领域模型单测."""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.generation_task import (
|
||||
TERMINAL_STATUSES,
|
||||
GenerationTask,
|
||||
GenerationTaskStatus,
|
||||
)
|
||||
|
||||
|
||||
class TestGenerationTaskCreate:
|
||||
def test_create_with_template_id(self):
|
||||
task = GenerationTask.create(
|
||||
project_id="",
|
||||
asset_library_id="lib1",
|
||||
template_id="tmpl1",
|
||||
)
|
||||
assert task.id
|
||||
assert task.template_id == "tmpl1"
|
||||
assert task.asset_library_id == "lib1"
|
||||
assert task.status == GenerationTaskStatus.PENDING
|
||||
assert task.progress == 0.0
|
||||
assert task.retry_count == 0
|
||||
assert task.auto_retry_enabled is False
|
||||
|
||||
def test_create_with_project_id(self):
|
||||
task = GenerationTask.create(
|
||||
project_id="proj1",
|
||||
asset_library_id="lib1",
|
||||
)
|
||||
assert task.project_id == "proj1"
|
||||
|
||||
def test_create_both_empty_raises(self):
|
||||
with pytest.raises(ValueError, match="project_id 或 template_id 至少需要提供一个"):
|
||||
GenerationTask.create(
|
||||
project_id="",
|
||||
asset_library_id="lib1",
|
||||
template_id="",
|
||||
)
|
||||
|
||||
def test_create_asset_library_and_assets_both_empty_raises(self):
|
||||
with pytest.raises(ValueError, match="asset_library_id 或 asset_ids/title_ids/voice_ids 至少需要提供一个"):
|
||||
GenerationTask.create(
|
||||
project_id="proj1",
|
||||
asset_library_id="",
|
||||
asset_ids=None,
|
||||
title_ids=None,
|
||||
voice_ids=None,
|
||||
)
|
||||
|
||||
def test_create_with_asset_ids(self):
|
||||
task = GenerationTask.create(
|
||||
project_id="proj1",
|
||||
asset_library_id="",
|
||||
asset_ids=["a1", "a2"],
|
||||
)
|
||||
assert task.asset_ids == ["a1", "a2"]
|
||||
|
||||
def test_create_strips_whitespace(self):
|
||||
task = GenerationTask.create(
|
||||
project_id=" proj1 ",
|
||||
asset_library_id=" lib1 ",
|
||||
template_id=" tmpl1 ",
|
||||
video_title=" 测试视频 ",
|
||||
resolution=" 1080p ",
|
||||
created_by_user_id=" user1 ",
|
||||
source_edit_plan_id=" plan1 ",
|
||||
)
|
||||
assert task.project_id == "proj1"
|
||||
assert task.asset_library_id == "lib1"
|
||||
assert task.template_id == "tmpl1"
|
||||
assert task.video_title == "测试视频"
|
||||
assert task.resolution == "1080p"
|
||||
assert task.created_by_user_id == "user1"
|
||||
assert task.source_edit_plan_id == "plan1"
|
||||
|
||||
def test_create_default_values(self):
|
||||
task = GenerationTask.create(
|
||||
project_id="proj1",
|
||||
asset_library_id="lib1",
|
||||
)
|
||||
assert task.title_ids == []
|
||||
assert task.voice_ids == []
|
||||
assert task.result_count == 0
|
||||
assert task.error_message == ""
|
||||
assert task.error_info == {}
|
||||
assert task.bgm_config == {}
|
||||
assert task.logs == "[]"
|
||||
|
||||
def test_create_unique_ids(self):
|
||||
t1 = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
t2 = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
assert t1.id != t2.id
|
||||
|
||||
|
||||
class TestGenerationTaskStatusQueries:
|
||||
def test_is_terminal_completed(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_completed()
|
||||
assert task.is_terminal is True
|
||||
assert task.is_completed is True
|
||||
assert task.is_failed is False
|
||||
assert task.is_running is False
|
||||
|
||||
def test_is_terminal_failed(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_failed("error")
|
||||
assert task.is_terminal is True
|
||||
assert task.is_completed is False
|
||||
assert task.is_failed is True
|
||||
|
||||
def test_is_terminal_cancelled(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.transition_to(GenerationTaskStatus.CANCELLED)
|
||||
assert task.is_terminal is True
|
||||
|
||||
def test_is_running(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
assert task.is_running is False
|
||||
task.mark_processing()
|
||||
assert task.is_running is True
|
||||
|
||||
def test_terminal_statuses_set(self):
|
||||
assert GenerationTaskStatus.COMPLETED in TERMINAL_STATUSES
|
||||
assert GenerationTaskStatus.FAILED in TERMINAL_STATUSES
|
||||
assert GenerationTaskStatus.CANCELLED in TERMINAL_STATUSES
|
||||
assert GenerationTaskStatus.PENDING not in TERMINAL_STATUSES
|
||||
assert GenerationTaskStatus.RUNNING not in TERMINAL_STATUSES
|
||||
|
||||
|
||||
class TestGenerationTaskStateTransitions:
|
||||
def test_pending_to_running(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
assert task.status == GenerationTaskStatus.RUNNING
|
||||
assert task.started_at is not None
|
||||
assert task.error_message == ""
|
||||
|
||||
def test_running_to_completed(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_completed(result_count=3)
|
||||
assert task.status == GenerationTaskStatus.COMPLETED
|
||||
assert task.completed_at is not None
|
||||
assert task.progress == 100.0
|
||||
assert task.result_count == 3
|
||||
assert task.error_message == ""
|
||||
|
||||
def test_running_to_failed_with_error_info(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_failed("渲染失败", error_info={"stage": "render"})
|
||||
assert task.status == GenerationTaskStatus.FAILED
|
||||
assert task.completed_at is not None
|
||||
assert task.error_message == "渲染失败"
|
||||
assert task.error_info["stage"] == "render"
|
||||
|
||||
def test_running_to_failed_without_error_info(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_failed("未知错误")
|
||||
assert task.error_info is not None
|
||||
assert task.error_info["message"] == "未知错误"
|
||||
assert "error_type" in task.error_info
|
||||
assert "failed_at" in task.error_info
|
||||
|
||||
def test_failed_to_pending_retry(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_failed("error")
|
||||
assert task.retry_count == 0
|
||||
|
||||
task.mark_pending_from_failed()
|
||||
assert task.status == GenerationTaskStatus.PENDING
|
||||
assert task.retry_count == 1
|
||||
assert task.error_message == ""
|
||||
assert task.error_info == {}
|
||||
assert task.started_at is None
|
||||
assert task.completed_at is None
|
||||
assert task.progress == 0.0
|
||||
assert task.result_count == 0
|
||||
|
||||
def test_mark_pending_from_failed_wrong_status_raises(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
with pytest.raises(ValueError, match="只有 failed 状态的任务可以重置为 pending"):
|
||||
task.mark_pending_from_failed()
|
||||
|
||||
def test_invalid_transition_raises(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
# pending 不能直接到 completed
|
||||
with pytest.raises(ValueError, match="非法状态转换"):
|
||||
task.transition_to(GenerationTaskStatus.COMPLETED)
|
||||
|
||||
def test_completed_cannot_transition(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_completed()
|
||||
with pytest.raises(ValueError, match="非法状态转换"):
|
||||
task.mark_failed("test")
|
||||
|
||||
def test_transition_to_with_string(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.transition_to("running")
|
||||
assert task.status == GenerationTaskStatus.RUNNING
|
||||
|
||||
def test_transition_to_invalid_string_raises(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
with pytest.raises(ValueError, match="无效状态"):
|
||||
task.transition_to("invalid_status")
|
||||
|
||||
|
||||
class TestGenerationTaskLogs:
|
||||
def test_append_log_single(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.append_log("初始化", "任务创建成功")
|
||||
logs = task.get_logs()
|
||||
assert len(logs) == 1
|
||||
assert logs[0]["stage"] == "初始化"
|
||||
assert logs[0]["message"] == "任务创建成功"
|
||||
assert logs[0]["level"] == "INFO"
|
||||
assert "ts" in logs[0]
|
||||
|
||||
def test_append_log_multiple(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
for i in range(5):
|
||||
task.append_log(f"stage{i}", f"msg{i}", level="INFO")
|
||||
logs = task.get_logs()
|
||||
assert len(logs) == 5
|
||||
assert logs[0]["stage"] == "stage0"
|
||||
assert logs[4]["stage"] == "stage4"
|
||||
|
||||
def test_append_log_with_extra_fields(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.append_log("下载", "下载完成", asset_id="a1", duration=10.5)
|
||||
logs = task.get_logs()
|
||||
assert logs[0]["asset_id"] == "a1"
|
||||
assert logs[0]["duration"] == 10.5
|
||||
|
||||
def test_append_log_error_level(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.append_log("渲染", "渲染失败", level="ERROR")
|
||||
logs = task.get_logs()
|
||||
assert logs[0]["level"] == "ERROR"
|
||||
|
||||
def test_logs_max_limit(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
# _MAX_LOGS = 200
|
||||
for i in range(250):
|
||||
task.append_log("test", f"msg{i}")
|
||||
logs = task.get_logs()
|
||||
assert len(logs) == 200
|
||||
# 保留最新的200条
|
||||
assert logs[0]["message"] == "msg50"
|
||||
assert logs[-1]["message"] == "msg249"
|
||||
|
||||
def test_get_logs_empty(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
assert task.get_logs() == []
|
||||
|
||||
def test_get_logs_corrupted_json(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.logs = "not json"
|
||||
assert task.get_logs() == []
|
||||
|
||||
def test_mark_failed_without_error_info(self):
|
||||
task = GenerationTask.create(project_id="p1", asset_library_id="l1")
|
||||
task.mark_processing()
|
||||
task.mark_failed("error msg")
|
||||
assert task.error_info is not None
|
||||
assert task.error_info["message"] == "error msg"
|
||||
assert "error_type" in task.error_info
|
||||
assert "failed_at" in task.error_info
|
||||
|
||||
|
||||
class TestGenerationTaskCreateWithStrategy:
|
||||
def test_create_with_strategy_and_voice(self):
|
||||
task = GenerationTask.create(
|
||||
project_id="p1",
|
||||
asset_library_id="l1",
|
||||
strategy_id="s1",
|
||||
voice_library_id="v1",
|
||||
auto_retry_enabled=True,
|
||||
auto_retry_max=3,
|
||||
)
|
||||
assert task.strategy_id == "s1"
|
||||
assert task.voice_library_id == "v1"
|
||||
assert task.auto_retry_enabled is True
|
||||
assert task.auto_retry_max == 3
|
||||
|
||||
def test_create_with_bgm_config(self):
|
||||
bgm = {"volume": 0.5, "track": "bgm1"}
|
||||
task = GenerationTask.create(
|
||||
project_id="p1",
|
||||
asset_library_id="l1",
|
||||
bgm_config=bgm,
|
||||
)
|
||||
assert task.bgm_config == bgm
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
"""GenerationTaskStatus 枚举兼容性测试。
|
||||
|
||||
验证历史脏数据(如 'success'/'done')不会导致枚举转换失败。
|
||||
关联 Issue: #809 [Staging] E2E测试失败 - 模板生成接口返回500
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.domain.generation_task import GenerationTaskStatus
|
||||
|
||||
|
||||
class TestGenerationTaskStatusNormalValues:
|
||||
"""正常值应该正确映射。"""
|
||||
|
||||
def test_pending(self):
|
||||
assert GenerationTaskStatus("pending") == GenerationTaskStatus.PENDING
|
||||
|
||||
def test_running(self):
|
||||
assert GenerationTaskStatus("running") == GenerationTaskStatus.RUNNING
|
||||
|
||||
def test_completed(self):
|
||||
assert GenerationTaskStatus("completed") == GenerationTaskStatus.COMPLETED
|
||||
|
||||
def test_failed(self):
|
||||
assert GenerationTaskStatus("failed") == GenerationTaskStatus.FAILED
|
||||
|
||||
def test_cancelled(self):
|
||||
assert GenerationTaskStatus("cancelled") == GenerationTaskStatus.CANCELLED
|
||||
|
||||
|
||||
class TestGenerationTaskStatusHistoricalValues:
|
||||
"""历史脏数据应该正确映射到对应状态,不抛异常。"""
|
||||
|
||||
@pytest.mark.parametrize("value", ["done", "success", "finished", "complete", "completed"])
|
||||
def test_completed_like_values_map_to_completed(self, value):
|
||||
assert GenerationTaskStatus(value) == GenerationTaskStatus.COMPLETED
|
||||
|
||||
@pytest.mark.parametrize("value", ["fail", "failed", "error", "err"])
|
||||
def test_failed_like_values_map_to_failed(self, value):
|
||||
assert GenerationTaskStatus(value) == GenerationTaskStatus.FAILED
|
||||
|
||||
@pytest.mark.parametrize("value", ["process", "processing", "run", "running", "in_progress"])
|
||||
def test_running_like_values_map_to_running(self, value):
|
||||
assert GenerationTaskStatus(value) == GenerationTaskStatus.RUNNING
|
||||
|
||||
@pytest.mark.parametrize("value", ["cancel", "cancelled", "canceled"])
|
||||
def test_cancelled_like_values_map_to_cancelled(self, value):
|
||||
assert GenerationTaskStatus(value) == GenerationTaskStatus.CANCELLED
|
||||
|
||||
@pytest.mark.parametrize("value", [" Done ", "SUCCESS", " failed "])
|
||||
def test_whitespace_and_case_insensitive(self, value):
|
||||
"""带空格和大小写不影响匹配。"""
|
||||
# 只要能找到对应状态且不抛异常即可
|
||||
result = GenerationTaskStatus(value)
|
||||
assert result in (
|
||||
GenerationTaskStatus.COMPLETED,
|
||||
GenerationTaskStatus.FAILED,
|
||||
)
|
||||
|
||||
|
||||
class TestGenerationTaskStatusFallback:
|
||||
"""完全未知的值兜底为 PENDING,不抛500。"""
|
||||
|
||||
@pytest.mark.parametrize("value", ["unknown", "foo_bar", "deleted", ""])
|
||||
def test_unknown_value_falls_back_to_pending(self, value):
|
||||
assert GenerationTaskStatus(value) == GenerationTaskStatus.PENDING
|
||||
|
||||
def test_none_value_falls_back_to_pending(self):
|
||||
assert GenerationTaskStatus(None) == GenerationTaskStatus.PENDING # type: ignore[arg-type]
|
||||
|
||||
def test_int_value_falls_back_to_pending(self):
|
||||
assert GenerationTaskStatus(123) == GenerationTaskStatus.PENDING # type: ignore[arg-type]
|
||||
|
||||
|
||||
class TestGenerationTaskStatusStrValue:
|
||||
"""枚举值仍为字符串类型,不影响序列化。"""
|
||||
|
||||
def test_value_unchanged(self):
|
||||
assert GenerationTaskStatus.PENDING.value == "pending"
|
||||
assert GenerationTaskStatus.COMPLETED.value == "completed"
|
||||
assert isinstance(GenerationTaskStatus.PENDING, str)
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
"""InMemoryAssetLibraryRepository 单测 — 素材库仓储内存实现."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.in_memory.asset_library_repository import (
|
||||
InMemoryAssetLibraryRepository,
|
||||
)
|
||||
from packages.domain import AssetLibrary, AssetLibraryKind
|
||||
|
||||
# ── Fixtures ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo():
|
||||
return InMemoryAssetLibraryRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_libraries(repo):
|
||||
"""创建几个测试素材库."""
|
||||
libs = []
|
||||
for i, kind in enumerate(
|
||||
[
|
||||
AssetLibraryKind.VIDEO,
|
||||
AssetLibraryKind.VOICE,
|
||||
AssetLibraryKind.IMAGE,
|
||||
]
|
||||
):
|
||||
lib = AssetLibrary.create(
|
||||
project_id="proj-1",
|
||||
name=f"Library {i}",
|
||||
kind=kind,
|
||||
)
|
||||
libs.append(repo.create(lib))
|
||||
# 另一个项目的
|
||||
lib2 = AssetLibrary.create(
|
||||
project_id="proj-2",
|
||||
name="Other Project Lib",
|
||||
kind=AssetLibraryKind.VIDEO,
|
||||
)
|
||||
libs.append(repo.create(lib2))
|
||||
return libs
|
||||
|
||||
|
||||
# ── CRUD 基本操作 ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetLibraryRepoCRUD:
|
||||
"""基本 CRUD 操作."""
|
||||
|
||||
def test_create_and_get(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="Test Lib", kind=AssetLibraryKind.VIDEO)
|
||||
created = repo.create(lib)
|
||||
assert created.id == lib.id
|
||||
assert created.name == "Test Lib"
|
||||
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched is not None
|
||||
assert fetched.kind == AssetLibraryKind.VIDEO
|
||||
|
||||
def test_get_not_found(self, repo):
|
||||
assert repo.get("nonexistent") is None
|
||||
|
||||
def test_find_by_id_alias(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="Test", kind=AssetLibraryKind.VOICE)
|
||||
repo.create(lib)
|
||||
assert repo.find_by_id(lib.id).id == lib.id
|
||||
|
||||
def test_update(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="Old Name", kind=AssetLibraryKind.IMAGE)
|
||||
repo.create(lib)
|
||||
|
||||
lib.name = "New Name"
|
||||
updated = repo.update(lib)
|
||||
assert updated.name == "New Name"
|
||||
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched.name == "New Name"
|
||||
|
||||
def test_delete_existing(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="To Delete", kind=AssetLibraryKind.VIDEO)
|
||||
repo.create(lib)
|
||||
|
||||
result = repo.delete(lib.id)
|
||||
assert result is True
|
||||
assert repo.get(lib.id) is None
|
||||
|
||||
def test_delete_nonexistent(self, repo):
|
||||
result = repo.delete("nonexistent")
|
||||
assert result is False
|
||||
|
||||
|
||||
# ── 查询方法 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetLibraryRepoQueries:
|
||||
"""查询类方法."""
|
||||
|
||||
def test_find_by_project_all_kinds(self, repo, sample_libraries):
|
||||
result = repo.find_by_project("proj-1")
|
||||
assert len(result) == 3
|
||||
|
||||
def test_find_by_project_filter_by_kind(self, repo, sample_libraries):
|
||||
result = repo.find_by_project("proj-1", kind=AssetLibraryKind.VIDEO)
|
||||
assert len(result) == 1
|
||||
assert result[0].kind == AssetLibraryKind.VIDEO
|
||||
|
||||
def test_find_by_project_empty(self, repo):
|
||||
result = repo.find_by_project("nonexistent")
|
||||
assert result == []
|
||||
|
||||
def test_find_by_project_with_kind_none_returns_all(self, repo, sample_libraries):
|
||||
result = repo.find_by_project("proj-1", kind=None)
|
||||
assert len(result) == 3
|
||||
|
||||
|
||||
# ── 计数方法 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetLibraryRepoCounting:
|
||||
"""素材计数相关方法."""
|
||||
|
||||
def test_increment_asset_count(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="Test", kind=AssetLibraryKind.VIDEO)
|
||||
repo.create(lib)
|
||||
assert lib.asset_count == 0
|
||||
assert lib.total_size == 0
|
||||
|
||||
repo.increment_asset_count(lib.id, 1024)
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched.asset_count == 1
|
||||
assert fetched.total_size == 1024
|
||||
|
||||
repo.increment_asset_count(lib.id, 2048)
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched.asset_count == 2
|
||||
assert fetched.total_size == 3072
|
||||
|
||||
def test_decrement_asset_count(self, repo):
|
||||
lib = AssetLibrary.create(project_id="p1", name="Test", kind=AssetLibraryKind.VIDEO)
|
||||
lib.asset_count = 3
|
||||
lib.total_size = 3000
|
||||
repo.create(lib)
|
||||
|
||||
repo.decrement_asset_count(lib.id, 1000)
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched.asset_count == 2
|
||||
assert fetched.total_size == 2000
|
||||
|
||||
def test_decrement_not_below_zero(self, repo):
|
||||
"""计数和大小不会减到负数."""
|
||||
lib = AssetLibrary.create(project_id="p1", name="Test", kind=AssetLibraryKind.VIDEO)
|
||||
lib.asset_count = 1
|
||||
lib.total_size = 100
|
||||
repo.create(lib)
|
||||
|
||||
# 减 2 次,应该被钳制到 0
|
||||
repo.decrement_asset_count(lib.id, 200)
|
||||
fetched = repo.get(lib.id)
|
||||
assert fetched.asset_count == 0
|
||||
assert fetched.total_size == 0
|
||||
|
||||
def test_increment_nonexistent_library_no_error(self, repo):
|
||||
"""对不存在的素材库操作,不抛异常也无效果."""
|
||||
repo.increment_asset_count("nonexistent", 100)
|
||||
# 不报错
|
||||
assert repo.get("nonexistent") is None
|
||||
|
||||
def test_decrement_nonexistent_library_no_error(self, repo):
|
||||
repo.decrement_asset_count("nonexistent", 100)
|
||||
assert repo.get("nonexistent") is None
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
"""InMemoryAssetRepository 单测 — 素材仓储内存实现."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.in_memory.asset_repository import InMemoryAssetRepository
|
||||
from packages.domain import Asset, AssetStatus
|
||||
|
||||
# ── Fixtures ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo():
|
||||
return InMemoryAssetRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_asset():
|
||||
return Asset.create(
|
||||
project_id="proj-1",
|
||||
library_id="lib-1",
|
||||
name="test.mp4",
|
||||
storage_key="assets/test.mp4",
|
||||
mime_type="video/mp4",
|
||||
file_size=1024,
|
||||
file_hash="hash-abc",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_assets(repo):
|
||||
"""创建几个测试素材."""
|
||||
assets = []
|
||||
for i in range(5):
|
||||
asset = Asset.create(
|
||||
project_id="proj-1",
|
||||
library_id="lib-1",
|
||||
name=f"video_{i}.mp4",
|
||||
storage_key=f"assets/video_{i}.mp4",
|
||||
mime_type="video/mp4",
|
||||
file_size=1000 + i,
|
||||
file_hash=f"hash-{i}",
|
||||
)
|
||||
assets.append(repo.create(asset))
|
||||
return assets
|
||||
|
||||
|
||||
# ── CRUD 基本操作 ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetRepoCRUD:
|
||||
"""基本 CRUD 操作."""
|
||||
|
||||
def test_create_and_get(self, repo, sample_asset):
|
||||
created = repo.create(sample_asset)
|
||||
assert created.id == sample_asset.id
|
||||
|
||||
fetched = repo.get(sample_asset.id)
|
||||
assert fetched is not None
|
||||
assert fetched.id == sample_asset.id
|
||||
assert fetched.name == "test.mp4"
|
||||
|
||||
def test_get_not_found(self, repo):
|
||||
assert repo.get("nonexistent") is None
|
||||
|
||||
def test_find_by_id_alias(self, repo, sample_asset):
|
||||
repo.create(sample_asset)
|
||||
assert repo.find_by_id(sample_asset.id).id == sample_asset.id
|
||||
|
||||
def test_update(self, repo, sample_asset):
|
||||
repo.create(sample_asset)
|
||||
sample_asset.name = "renamed.mp4"
|
||||
updated = repo.update(sample_asset)
|
||||
assert updated.name == "renamed.mp4"
|
||||
|
||||
fetched = repo.get(sample_asset.id)
|
||||
assert fetched.name == "renamed.mp4"
|
||||
|
||||
def test_delete_existing(self, repo, sample_asset):
|
||||
repo.create(sample_asset)
|
||||
result = repo.delete(sample_asset.id)
|
||||
assert result is True
|
||||
assert repo.get(sample_asset.id) is None
|
||||
|
||||
def test_delete_nonexistent(self, repo):
|
||||
result = repo.delete("nonexistent")
|
||||
assert result is False
|
||||
|
||||
|
||||
# ── 查询方法 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetRepoQueries:
|
||||
"""查询类方法."""
|
||||
|
||||
def test_list_by_project(self, repo, sample_assets):
|
||||
result = repo.list_by_project("proj-1")
|
||||
assert len(result) == 5
|
||||
|
||||
def test_list_by_project_empty(self, repo):
|
||||
result = repo.list_by_project("nonexistent")
|
||||
assert result == []
|
||||
|
||||
def test_list_by_library(self, repo, sample_assets):
|
||||
result = repo.list_by_library("lib-1")
|
||||
assert len(result) == 5
|
||||
|
||||
def test_find_by_library_alias(self, repo, sample_assets):
|
||||
result = repo.find_by_library("lib-1")
|
||||
assert len(result) == 5
|
||||
|
||||
def test_find_by_library_and_file_type_video(self, repo):
|
||||
video = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="lib-1",
|
||||
name="v.mp4",
|
||||
storage_key="v.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
audio = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="lib-1",
|
||||
name="a.mp3",
|
||||
storage_key="a.mp3",
|
||||
mime_type="audio/mp3",
|
||||
)
|
||||
image = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="lib-1",
|
||||
name="i.jpg",
|
||||
storage_key="i.jpg",
|
||||
mime_type="image/jpeg",
|
||||
)
|
||||
repo.create(video)
|
||||
repo.create(audio)
|
||||
repo.create(image)
|
||||
|
||||
videos = repo.find_by_library_and_file_type("lib-1", "video")
|
||||
assert len(videos) == 1
|
||||
assert videos[0].id == video.id
|
||||
|
||||
audios = repo.find_by_library_and_file_type("lib-1", "audio")
|
||||
assert len(audios) == 1
|
||||
assert audios[0].id == audio.id
|
||||
|
||||
def test_find_by_project_with_pagination(self, repo, sample_assets):
|
||||
result = repo.find_by_project("proj-1", skip=0, limit=3)
|
||||
assert len(result) == 3
|
||||
|
||||
result2 = repo.find_by_project("proj-1", skip=3, limit=10)
|
||||
assert len(result2) == 2
|
||||
|
||||
def test_find_by_tag_ids_single_tag(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.tag_ids = ["tag1", "tag2"]
|
||||
a2 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a2.mp4",
|
||||
storage_key="a2.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a2.tag_ids = ["tag1"]
|
||||
a3 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a3.mp4",
|
||||
storage_key="a3.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a3.tag_ids = ["tag3"]
|
||||
repo.create(a1)
|
||||
repo.create(a2)
|
||||
repo.create(a3)
|
||||
|
||||
result = repo.find_by_tag_ids(["tag1"])
|
||||
assert len(result) == 2
|
||||
|
||||
def test_find_by_tag_ids_multiple_tags_all_match(self, repo):
|
||||
"""必须包含所有指定标签(AND 逻辑)."""
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.tag_ids = ["tag1", "tag2"]
|
||||
a2 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a2.mp4",
|
||||
storage_key="a2.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a2.tag_ids = ["tag1"]
|
||||
repo.create(a1)
|
||||
repo.create(a2)
|
||||
|
||||
result = repo.find_by_tag_ids(["tag1", "tag2"])
|
||||
assert len(result) == 1
|
||||
assert result[0].id == a1.id
|
||||
|
||||
def test_find_by_tag_ids_empty_list(self, repo, sample_assets):
|
||||
result = repo.find_by_tag_ids([])
|
||||
assert result == []
|
||||
|
||||
def test_find_by_library_and_file_hash(self, repo, sample_asset):
|
||||
repo.create(sample_asset)
|
||||
result = repo.find_by_library_and_file_hash("lib-1", "hash-abc")
|
||||
assert result is not None
|
||||
assert result.id == sample_asset.id
|
||||
|
||||
def test_find_by_library_and_file_hash_not_found(self, repo):
|
||||
result = repo.find_by_library_and_file_hash("lib-1", "nonexistent")
|
||||
assert result is None
|
||||
|
||||
def test_find_by_library_and_file_hash_empty_hash(self, repo, sample_asset):
|
||||
repo.create(sample_asset)
|
||||
result = repo.find_by_library_and_file_hash("lib-1", "")
|
||||
assert result is None
|
||||
|
||||
|
||||
# ── 批量操作 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestAssetRepoBatchOperations:
|
||||
"""批量操作方法."""
|
||||
|
||||
def test_batch_delete_marks_deleted(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a2 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a2.mp4",
|
||||
storage_key="a2.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
repo.create(a1)
|
||||
repo.create(a2)
|
||||
|
||||
count = repo.batch_delete([a1.id, a2.id])
|
||||
assert count == 2
|
||||
|
||||
# 状态变为 deleted
|
||||
assert repo.get(a1.id).status == AssetStatus.DELETED
|
||||
assert repo.get(a2.id).status == AssetStatus.DELETED
|
||||
|
||||
def test_batch_delete_skip_already_deleted(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.status = AssetStatus.DELETED
|
||||
repo.create(a1)
|
||||
a2 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a2.mp4",
|
||||
storage_key="a2.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
repo.create(a2)
|
||||
|
||||
count = repo.batch_delete([a1.id, a2.id])
|
||||
assert count == 1 # 只有a2被标记
|
||||
|
||||
def test_batch_delete_nonexistent(self, repo):
|
||||
count = repo.batch_delete(["nonexistent"])
|
||||
assert count == 0
|
||||
|
||||
def test_batch_update_metadata(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.metadata = {"key1": "val1"}
|
||||
a2 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a2.mp4",
|
||||
storage_key="a2.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
repo.create(a1)
|
||||
repo.create(a2)
|
||||
|
||||
count = repo.batch_update_metadata([a1.id, a2.id], {"key2": "val2"})
|
||||
assert count == 2
|
||||
|
||||
# 合并而非覆盖
|
||||
assert repo.get(a1.id).metadata["key1"] == "val1"
|
||||
assert repo.get(a1.id).metadata["key2"] == "val2"
|
||||
assert repo.get(a2.id).metadata["key2"] == "val2"
|
||||
|
||||
def test_batch_add_tags(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.tag_ids = ["existing"]
|
||||
repo.create(a1)
|
||||
|
||||
count = repo.batch_add_tags([a1.id], ["tag1", "tag2"])
|
||||
assert count == 1
|
||||
|
||||
tags = repo.get(a1.id).tag_ids
|
||||
assert "existing" in tags
|
||||
assert "tag1" in tags
|
||||
assert "tag2" in tags
|
||||
|
||||
def test_batch_add_tags_dedup(self, repo):
|
||||
"""添加已存在的标签不会重复."""
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.tag_ids = ["tag1"]
|
||||
repo.create(a1)
|
||||
|
||||
before_count = len(a1.tag_ids)
|
||||
repo.batch_add_tags([a1.id], ["tag1", "tag1"])
|
||||
# 没有变化,count 应该是0?不对,tag_ids去重后还是["tag1"],但原先是["tag1"]
|
||||
# 添加tag1时发现已存在,changed=False,所以count=0
|
||||
assert repo.get(a1.id).tag_ids.count("tag1") == 1
|
||||
|
||||
def test_batch_replace_tags(self, repo):
|
||||
a1 = Asset.create(
|
||||
project_id="p1",
|
||||
library_id="l1",
|
||||
name="a1.mp4",
|
||||
storage_key="a1.mp4",
|
||||
mime_type="video/mp4",
|
||||
)
|
||||
a1.tag_ids = ["old1", "old2"]
|
||||
repo.create(a1)
|
||||
|
||||
count = repo.batch_replace_tags([a1.id], ["new1", "new2"])
|
||||
assert count == 1
|
||||
|
||||
tags = repo.get(a1.id).tag_ids
|
||||
assert tags == ["new1", "new2"]
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
In-Memory 项目仓储 + 小仓储测试.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.in_memory.classification_job_repository import InMemoryClassificationJobRepository
|
||||
from packages.adapters.in_memory.ingest_job_repository import InMemoryIngestJobRepository
|
||||
from packages.adapters.in_memory.project_repository import InMemoryProjectRepository
|
||||
from packages.domain import ClassificationJob, IngestJob, Project
|
||||
|
||||
# ── Project Repository ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_repo():
|
||||
return InMemoryProjectRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_project():
|
||||
counter = 0
|
||||
|
||||
def _make(owner_id: str = "user_1", name: str = "测试项目"):
|
||||
nonlocal counter
|
||||
counter += 1
|
||||
return Project(
|
||||
id=f"proj_{counter}",
|
||||
owner_user_id=owner_id,
|
||||
name=name,
|
||||
)
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
class TestInMemoryProjectRepository:
|
||||
"""项目仓储."""
|
||||
|
||||
def test_save_and_find_by_id(self, project_repo, make_project):
|
||||
proj = make_project()
|
||||
project_repo.save(proj)
|
||||
found = project_repo.find_by_id(proj.id)
|
||||
assert found is not None
|
||||
assert found.id == proj.id
|
||||
assert found.name == "测试项目"
|
||||
|
||||
def test_find_by_id_not_found(self, project_repo):
|
||||
assert project_repo.find_by_id("nonexistent") is None
|
||||
|
||||
def test_find_by_owner(self, project_repo, make_project):
|
||||
for i in range(3):
|
||||
project_repo.save(make_project(owner_id="user_1", name=f"p{i}"))
|
||||
project_repo.save(make_project(owner_id="user_2", name="other"))
|
||||
|
||||
result = project_repo.find_by_owner_user_id("user_1")
|
||||
assert len(result) == 3
|
||||
assert all(p.owner_user_id == "user_1" for p in result)
|
||||
|
||||
def test_count_by_owner(self, project_repo, make_project):
|
||||
for i in range(5):
|
||||
project_repo.save(make_project(owner_id="user_1", name=f"p{i}"))
|
||||
project_repo.save(make_project(owner_id="user_2", name="other"))
|
||||
assert project_repo.count_by_owner("user_1") == 5
|
||||
assert project_repo.count_by_owner("user_2") == 1
|
||||
assert project_repo.count_by_owner("user_3") == 0
|
||||
|
||||
def test_delete_existing(self, project_repo, make_project):
|
||||
proj = make_project()
|
||||
project_repo.save(proj)
|
||||
result = project_repo.delete(proj.id)
|
||||
assert result is True
|
||||
assert project_repo.find_by_id(proj.id) is None
|
||||
|
||||
def test_delete_nonexistent(self, project_repo):
|
||||
assert project_repo.delete("nonexistent") is False
|
||||
|
||||
def test_save_updates(self, project_repo, make_project):
|
||||
proj = make_project(name="v1")
|
||||
project_repo.save(proj)
|
||||
proj.name = "v2"
|
||||
project_repo.save(proj)
|
||||
found = project_repo.find_by_id(proj.id)
|
||||
assert found.name == "v2"
|
||||
|
||||
def test_find_accessible_projects(self, project_repo, make_project):
|
||||
p1 = make_project(owner_id="user_1", name="owned")
|
||||
project_repo.save(p1)
|
||||
# 自己拥有的项目可访问
|
||||
result = project_repo.find_accessible_projects("user_1")
|
||||
assert len(result) >= 1
|
||||
assert any(p.id == p1.id for p in result)
|
||||
|
||||
|
||||
# ── Classification Job Repository ──────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def classif_repo():
|
||||
return InMemoryClassificationJobRepository()
|
||||
|
||||
|
||||
class TestInMemoryClassificationJobRepository:
|
||||
"""分类任务仓储."""
|
||||
|
||||
def test_create_and_get(self, classif_repo):
|
||||
job = ClassificationJob(
|
||||
id="job_1",
|
||||
project_id="p1",
|
||||
asset_id="a1",
|
||||
status="pending",
|
||||
)
|
||||
classif_repo.create(job)
|
||||
found = classif_repo.get("job_1")
|
||||
assert found is not None
|
||||
assert found.id == "job_1"
|
||||
assert found.status == "pending"
|
||||
|
||||
def test_get_not_found(self, classif_repo):
|
||||
assert classif_repo.get("nonexistent") is None
|
||||
|
||||
def test_update(self, classif_repo):
|
||||
job = ClassificationJob(
|
||||
id="job_1",
|
||||
project_id="p1",
|
||||
asset_id="a1",
|
||||
status="pending",
|
||||
)
|
||||
classif_repo.create(job)
|
||||
job.status = "completed"
|
||||
classif_repo.update(job)
|
||||
found = classif_repo.get("job_1")
|
||||
assert found.status == "completed"
|
||||
|
||||
def test_update_nonexistent_creates(self, classif_repo):
|
||||
"""update 对不存在的也会写入(dict 赋值)"""
|
||||
job = ClassificationJob(
|
||||
id="new_job",
|
||||
project_id="p1",
|
||||
asset_id="a1",
|
||||
status="running",
|
||||
)
|
||||
classif_repo.update(job)
|
||||
found = classif_repo.get("new_job")
|
||||
assert found is not None
|
||||
|
||||
|
||||
# ── Ingest Job Repository ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ingest_repo():
|
||||
return InMemoryIngestJobRepository()
|
||||
|
||||
|
||||
class TestInMemoryIngestJobRepository:
|
||||
"""导入任务仓储."""
|
||||
|
||||
def test_create_and_get(self, ingest_repo):
|
||||
job = IngestJob(
|
||||
id="ingest_1",
|
||||
project_id="p1",
|
||||
library_id="lib1",
|
||||
storage_key="key1",
|
||||
status="pending",
|
||||
)
|
||||
ingest_repo.create(job)
|
||||
found = ingest_repo.get("ingest_1")
|
||||
assert found is not None
|
||||
assert found.id == "ingest_1"
|
||||
assert found.status == "pending"
|
||||
|
||||
def test_get_not_found(self, ingest_repo):
|
||||
assert ingest_repo.get("nonexistent") is None
|
||||
|
||||
def test_update(self, ingest_repo):
|
||||
job = IngestJob(
|
||||
id="ingest_1",
|
||||
project_id="p1",
|
||||
library_id="lib1",
|
||||
storage_key="key1",
|
||||
status="pending",
|
||||
)
|
||||
ingest_repo.create(job)
|
||||
job.status = "completed"
|
||||
ingest_repo.update(job)
|
||||
found = ingest_repo.get("ingest_1")
|
||||
assert found.status == "completed"
|
||||
|
||||
def test_update_nonexistent_creates(self, ingest_repo):
|
||||
job = IngestJob(
|
||||
id="new_ingest",
|
||||
project_id="p1",
|
||||
library_id="lib1",
|
||||
storage_key="key1",
|
||||
status="running",
|
||||
)
|
||||
ingest_repo.update(job)
|
||||
found = ingest_repo.get("new_ingest")
|
||||
assert found is not None
|
||||
Executable
+174
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
In-Memory 标签仓储测试.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.in_memory.tag_repository import InMemoryTagRepository
|
||||
from packages.domain import Tag
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo():
|
||||
return InMemoryTagRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_tag():
|
||||
counter = 0
|
||||
|
||||
def _make(user_id: str = "user_1", name: str = "默认标签"):
|
||||
nonlocal counter
|
||||
counter += 1
|
||||
return Tag(
|
||||
id=f"tag_{counter}",
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
created_at=datetime.now(),
|
||||
)
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryCreate:
|
||||
"""创建标签."""
|
||||
|
||||
def test_create_tag(self, repo, make_tag):
|
||||
tag = make_tag()
|
||||
result = repo.create(tag)
|
||||
assert result.id == tag.id
|
||||
assert result.name == tag.name
|
||||
|
||||
def test_create_same_id_overwrites(self, repo, make_tag):
|
||||
tag = make_tag(name="first")
|
||||
repo.create(tag)
|
||||
tag.name = "second"
|
||||
repo.create(tag)
|
||||
found = repo.get(tag.id)
|
||||
assert found.name == "second"
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryGet:
|
||||
"""获取标签."""
|
||||
|
||||
def test_get_existing(self, repo, make_tag):
|
||||
tag = make_tag()
|
||||
repo.create(tag)
|
||||
found = repo.get(tag.id)
|
||||
assert found is not None
|
||||
assert found.id == tag.id
|
||||
|
||||
def test_get_nonexistent(self, repo):
|
||||
assert repo.get("nonexistent") is None
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryFindByName:
|
||||
"""按名称查找."""
|
||||
|
||||
def test_find_by_name_found(self, repo, make_tag):
|
||||
tag = make_tag(name="风景")
|
||||
repo.create(tag)
|
||||
found = repo.find_by_name("user_1", "风景")
|
||||
assert found is not None
|
||||
assert found.id == tag.id
|
||||
|
||||
def test_find_by_name_not_found(self, repo, make_tag):
|
||||
tag = make_tag(name="风景")
|
||||
repo.create(tag)
|
||||
assert repo.find_by_name("user_1", "美食") is None
|
||||
assert repo.find_by_name("user_2", "风景") is None
|
||||
|
||||
def test_find_by_name_different_user(self, repo, make_tag):
|
||||
tag = make_tag(user_id="user_1", name="风景")
|
||||
repo.create(tag)
|
||||
assert repo.find_by_name("user_2", "风景") is None
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryListByUser:
|
||||
"""用户标签列表."""
|
||||
|
||||
def test_list_by_user_empty(self, repo):
|
||||
result = repo.list_by_user("user_1")
|
||||
assert result == []
|
||||
|
||||
def test_list_by_user_filters_correctly(self, repo, make_tag):
|
||||
for i in range(5):
|
||||
make_tag(user_id="user_1", name=f"标签{i}")
|
||||
repo.create(make_tag(user_id="user_1", name=f"标签{i}"))
|
||||
repo.create(make_tag(user_id="user_2", name="其他标签"))
|
||||
|
||||
result = repo.list_by_user("user_1")
|
||||
assert len(result) == 5
|
||||
assert all(t.user_id == "user_1" for t in result)
|
||||
|
||||
def test_list_sorted_by_created_desc(self, repo, make_tag):
|
||||
tags = []
|
||||
for i in range(3):
|
||||
tag = make_tag(name=f"t{i}")
|
||||
tag.created_at = datetime.fromtimestamp(1000 + i * 100)
|
||||
repo.create(tag)
|
||||
tags.append(tag)
|
||||
|
||||
result = repo.list_by_user("user_1")
|
||||
assert len(result) == 3
|
||||
# 最新的排在前面
|
||||
assert result[0].created_at > result[2].created_at
|
||||
|
||||
def test_list_pagination(self, repo, make_tag):
|
||||
for i in range(10):
|
||||
repo.create(make_tag(name=f"tag{i}"))
|
||||
|
||||
page1 = repo.list_by_user("user_1", skip=0, limit=3)
|
||||
page2 = repo.list_by_user("user_1", skip=3, limit=3)
|
||||
assert len(page1) == 3
|
||||
assert len(page2) == 3
|
||||
assert page1[0].id != page2[0].id
|
||||
|
||||
def test_list_limit_exceeds_total(self, repo, make_tag):
|
||||
for i in range(3):
|
||||
repo.create(make_tag(name=f"t{i}"))
|
||||
result = repo.list_by_user("user_1", skip=0, limit=100)
|
||||
assert len(result) == 3
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryCount:
|
||||
"""统计用户标签数."""
|
||||
|
||||
def test_count_zero(self, repo):
|
||||
assert repo.count_by_user("user_1") == 0
|
||||
|
||||
def test_count_correct(self, repo, make_tag):
|
||||
for i in range(7):
|
||||
repo.create(make_tag(user_id="user_1", name=f"t{i}"))
|
||||
repo.create(make_tag(user_id="user_2", name="other"))
|
||||
assert repo.count_by_user("user_1") == 7
|
||||
assert repo.count_by_user("user_2") == 1
|
||||
|
||||
|
||||
class TestInMemoryTagRepositoryDelete:
|
||||
"""删除标签."""
|
||||
|
||||
def test_delete_existing(self, repo, make_tag):
|
||||
tag = make_tag()
|
||||
repo.create(tag)
|
||||
result = repo.delete(tag.id)
|
||||
assert result is True
|
||||
assert repo.get(tag.id) is None
|
||||
|
||||
def test_delete_nonexistent(self, repo):
|
||||
result = repo.delete("nonexistent")
|
||||
assert result is False
|
||||
|
||||
def test_delete_does_not_affect_others(self, repo, make_tag):
|
||||
t1 = make_tag(name="a")
|
||||
t2 = make_tag(name="b")
|
||||
repo.create(t1)
|
||||
repo.create(t2)
|
||||
repo.delete(t1.id)
|
||||
assert repo.get(t2.id) is not None
|
||||
assert repo.count_by_user("user_1") == 1
|
||||
Executable
+189
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
In-Memory 用户仓储测试.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.in_memory.user_repository import InMemoryUserRepository
|
||||
from packages.domain.entities import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo():
|
||||
return InMemoryUserRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_user():
|
||||
return User(
|
||||
id="user_1",
|
||||
email="test@example.com",
|
||||
display_name="Test User",
|
||||
username="testuser",
|
||||
password_hash="hashed",
|
||||
email_verified=True,
|
||||
email_verification_token="verify_token",
|
||||
password_reset_token="reset_token",
|
||||
wechat_openid="openid_123",
|
||||
wechat_unionid="unionid_123",
|
||||
phone="13800138000",
|
||||
)
|
||||
|
||||
|
||||
class TestInMemoryUserRepositorySave:
|
||||
"""保存用户."""
|
||||
|
||||
def test_save_new_user(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_id("user_1")
|
||||
assert found is not None
|
||||
assert found.email == "test@example.com"
|
||||
|
||||
def test_save_updates_existing(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
sample_user.display_name = "Updated"
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_id("user_1")
|
||||
assert found.display_name == "Updated"
|
||||
|
||||
def test_email_index_case_insensitive(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_email("TEST@EXAMPLE.COM")
|
||||
assert found is not None
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_username_index_case_insensitive(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_username("TESTUSER")
|
||||
assert found is not None
|
||||
assert found.id == "user_1"
|
||||
|
||||
|
||||
class TestInMemoryUserRepositoryFind:
|
||||
"""各种查找方式."""
|
||||
|
||||
def test_find_by_id_found(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_id("user_1")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_id_not_found(self, repo):
|
||||
assert repo.find_by_id("nonexistent") is None
|
||||
|
||||
def test_find_by_email_found(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_email("test@example.com")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_email_not_found(self, repo):
|
||||
assert repo.find_by_email("no@example.com") is None
|
||||
|
||||
def test_find_by_username_found(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_username("testuser")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_username_not_found(self, repo):
|
||||
assert repo.find_by_username("nobody") is None
|
||||
|
||||
def test_find_by_verification_token(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_verification_token("verify_token")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_verification_token_not_found(self, repo):
|
||||
assert repo.find_by_verification_token("bad_token") is None
|
||||
|
||||
def test_find_by_password_reset_token(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_password_reset_token("reset_token")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_password_reset_token_not_found(self, repo):
|
||||
assert repo.find_by_password_reset_token("bad_token") is None
|
||||
|
||||
def test_find_by_wechat_openid(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_wechat_openid("openid_123")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_wechat_openid_not_found(self, repo):
|
||||
assert repo.find_by_wechat_openid("bad_openid") is None
|
||||
|
||||
def test_find_by_wechat_unionid(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_wechat_unionid("unionid_123")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_wechat_unionid_empty_returns_none(self, repo):
|
||||
"""空 unionid 直接返回 None."""
|
||||
assert repo.find_by_wechat_unionid("") is None
|
||||
assert repo.find_by_wechat_unionid(None) is None # type: ignore
|
||||
|
||||
def test_find_by_wechat_unionid_not_found(self, repo):
|
||||
assert repo.find_by_wechat_unionid("bad_unionid") is None
|
||||
|
||||
def test_find_by_phone(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
found = repo.find_by_phone("13800138000")
|
||||
assert found.id == "user_1"
|
||||
|
||||
def test_find_by_phone_empty_returns_none(self, repo):
|
||||
assert repo.find_by_phone("") is None
|
||||
assert repo.find_by_phone(None) is None # type: ignore
|
||||
|
||||
def test_find_by_phone_not_found(self, repo):
|
||||
assert repo.find_by_phone("13900139000") is None
|
||||
|
||||
def test_user_without_username_not_in_username_index(self, repo):
|
||||
user = User(id="u2", email="no_user@example.com", display_name="No Username")
|
||||
repo.save(user)
|
||||
assert repo.find_by_username("") is None
|
||||
|
||||
|
||||
class TestInMemoryUserRepositoryDelete:
|
||||
"""删除用户."""
|
||||
|
||||
def test_delete_existing(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
result = repo.delete("user_1")
|
||||
assert result is True
|
||||
assert repo.find_by_id("user_1") is None
|
||||
assert repo.find_by_email("test@example.com") is None
|
||||
assert repo.find_by_username("testuser") is None
|
||||
assert repo.find_by_verification_token("verify_token") is None
|
||||
assert repo.find_by_password_reset_token("reset_token") is None
|
||||
|
||||
def test_delete_nonexistent(self, repo):
|
||||
result = repo.delete("nonexistent")
|
||||
assert result is False
|
||||
|
||||
def test_delete_cleans_wechat_and_phone_indexes(self, repo, sample_user):
|
||||
repo.save(sample_user)
|
||||
repo.delete("user_1")
|
||||
assert repo.find_by_wechat_openid("openid_123") is None
|
||||
assert repo.find_by_wechat_unionid("unionid_123") is None
|
||||
assert repo.find_by_phone("13800138000") is None
|
||||
|
||||
|
||||
class TestInMemoryUserRepositoryMultipleUsers:
|
||||
"""多用户场景."""
|
||||
|
||||
def test_multiple_users(self, repo):
|
||||
for i in range(5):
|
||||
user = User(
|
||||
id=f"user_{i}",
|
||||
email=f"user{i}@example.com",
|
||||
display_name=f"User {i}",
|
||||
username=f"user{i}",
|
||||
)
|
||||
repo.save(user)
|
||||
|
||||
for i in range(5):
|
||||
assert repo.find_by_id(f"user_{i}") is not None
|
||||
assert repo.find_by_email(f"user{i}@example.com") is not None
|
||||
assert repo.find_by_username(f"user{i}") is not None
|
||||
Executable
+308
@@ -0,0 +1,308 @@
|
||||
"""片头片尾引擎单元测试 - 配置解析等纯逻辑."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from video_processing.intro_outro_engine import IntroOutroConfig
|
||||
|
||||
|
||||
class TestIntroOutroConfigDefaults:
|
||||
"""默认配置测试."""
|
||||
|
||||
def test_default_values(self):
|
||||
"""默认值正确."""
|
||||
config = IntroOutroConfig()
|
||||
assert config.enabled is False
|
||||
assert config.intro_type == "none"
|
||||
assert config.outro_type == "none"
|
||||
assert config.intro_duration == 3.0
|
||||
assert config.outro_duration == 3.0
|
||||
assert config.transition_effect == "fade"
|
||||
assert config.transition_duration == 0.5
|
||||
|
||||
|
||||
class TestIntroOutroConfigFromDict:
|
||||
"""from_dict 配置解析测试."""
|
||||
|
||||
def test_none_returns_default(self):
|
||||
"""None 返回默认配置."""
|
||||
config = IntroOutroConfig.from_dict(None)
|
||||
assert config.enabled is False
|
||||
|
||||
def test_empty_dict_returns_default(self):
|
||||
"""空 dict 返回默认."""
|
||||
config = IntroOutroConfig.from_dict({})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_disabled_returns_default(self):
|
||||
"""enabled=False 返回默认."""
|
||||
config = IntroOutroConfig.from_dict({"enabled": False})
|
||||
assert config.enabled is False
|
||||
|
||||
def test_enabled_defaults(self):
|
||||
"""启用时默认值正确."""
|
||||
config = IntroOutroConfig.from_dict({"enabled": True})
|
||||
assert config.enabled is True
|
||||
assert config.intro_type == "none"
|
||||
assert config.outro_type == "none"
|
||||
|
||||
def test_text_intro(self):
|
||||
"""文字片头配置."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": {
|
||||
"type": "text",
|
||||
"title": "我的片头",
|
||||
"subtitle": "欢迎收看",
|
||||
},
|
||||
})
|
||||
assert config.intro_type == "text"
|
||||
assert config.intro_title == "我的片头"
|
||||
assert config.intro_subtitle == "欢迎收看"
|
||||
|
||||
def test_video_intro(self):
|
||||
"""视频片头配置."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": {
|
||||
"type": "video",
|
||||
"video_path": "/videos/intro.mp4",
|
||||
"duration": 5.0,
|
||||
},
|
||||
})
|
||||
assert config.intro_type == "video"
|
||||
assert config.intro_video_path == "/videos/intro.mp4"
|
||||
assert config.intro_duration == 5.0
|
||||
|
||||
def test_video_intro_video_alias(self):
|
||||
"""video 字段作为 video_path 别名."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": {
|
||||
"type": "video",
|
||||
"video": "/videos/intro.mp4",
|
||||
},
|
||||
})
|
||||
assert config.intro_video_path == "/videos/intro.mp4"
|
||||
|
||||
def test_text_outro(self):
|
||||
"""文字片尾配置."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"outro": {
|
||||
"type": "text",
|
||||
"title": "感谢观看",
|
||||
"subtitle": "点赞关注",
|
||||
},
|
||||
})
|
||||
assert config.outro_type == "text"
|
||||
assert config.outro_title == "感谢观看"
|
||||
assert config.outro_subtitle == "点赞关注"
|
||||
|
||||
def test_outro_default_title(self):
|
||||
"""片尾默认标题."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"outro": {"type": "text"},
|
||||
})
|
||||
assert config.outro_title == "感谢观看"
|
||||
assert config.outro_subtitle == "点赞关注不迷路"
|
||||
|
||||
def test_text_intro_styling(self):
|
||||
"""文字片头样式配置."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": {
|
||||
"type": "text",
|
||||
"title": "测试",
|
||||
"background": "#FF0000",
|
||||
"title_color": "yellow",
|
||||
"title_size": 64,
|
||||
"subtitle_color": "white",
|
||||
"subtitle_size": 32,
|
||||
},
|
||||
})
|
||||
assert config.intro_background == "#FF0000"
|
||||
assert config.intro_title_color == "yellow"
|
||||
assert config.intro_title_size == 64
|
||||
assert config.intro_subtitle_color == "white"
|
||||
assert config.intro_subtitle_size == 32
|
||||
|
||||
def test_transition_config(self):
|
||||
"""转场配置."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"transition": "dissolve",
|
||||
"transition_duration": 1.0,
|
||||
})
|
||||
assert config.transition_effect == "dissolve"
|
||||
assert config.transition_duration == 1.0
|
||||
|
||||
def test_empty_intro_dict(self):
|
||||
"""空 intro dict."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": {},
|
||||
})
|
||||
assert config.intro_type == "none"
|
||||
|
||||
def test_none_intro(self):
|
||||
"""None intro 值."""
|
||||
config = IntroOutroConfig.from_dict({
|
||||
"enabled": True,
|
||||
"intro": None,
|
||||
})
|
||||
assert config.intro_type == "none"
|
||||
|
||||
|
||||
class TestHasIntroOutro:
|
||||
"""has_intro / has_outro 属性测试."""
|
||||
|
||||
def test_no_intro_when_disabled(self):
|
||||
"""禁用时无片头."""
|
||||
config = IntroOutroConfig()
|
||||
assert config.has_intro is False
|
||||
assert config.has_outro is False
|
||||
|
||||
def test_video_intro_has_intro(self):
|
||||
"""视频片头有has_intro."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="video",
|
||||
intro_video_path="/a.mp4",
|
||||
)
|
||||
assert config.has_intro is True
|
||||
|
||||
def test_text_intro_has_intro(self):
|
||||
"""文字片头有has_intro."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="text",
|
||||
intro_title="test",
|
||||
)
|
||||
assert config.has_intro is True
|
||||
|
||||
def test_none_intro_no_intro(self):
|
||||
"""none类型无片头."""
|
||||
config = IntroOutroConfig(enabled=True, intro_type="none")
|
||||
assert config.has_intro is False
|
||||
|
||||
def test_video_outro_has_outro(self):
|
||||
"""视频片尾有has_outro."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="video",
|
||||
outro_video_path="/a.mp4",
|
||||
)
|
||||
assert config.has_outro is True
|
||||
|
||||
def test_text_outro_has_outro(self):
|
||||
"""文字片尾有has_outro."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="text",
|
||||
outro_title="test",
|
||||
)
|
||||
assert config.has_outro is True
|
||||
|
||||
def test_follow_outro_has_outro(self):
|
||||
"""follow类型片尾有has_outro."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="follow",
|
||||
outro_title="test",
|
||||
)
|
||||
assert config.has_outro is True
|
||||
|
||||
|
||||
class TestValidate:
|
||||
"""validate 配置校验测试."""
|
||||
|
||||
def test_disabled_valid(self):
|
||||
"""禁用配置合法."""
|
||||
config = IntroOutroConfig()
|
||||
ok, msg = config.validate()
|
||||
assert ok is True
|
||||
assert msg == ""
|
||||
|
||||
def test_video_intro_missing_path(self):
|
||||
"""视频片头缺少路径."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="video",
|
||||
intro_video_path="",
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "video_path" in msg
|
||||
|
||||
def test_text_intro_missing_title(self):
|
||||
"""文字片头缺少标题."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="text",
|
||||
intro_title="",
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "title" in msg
|
||||
|
||||
def test_video_outro_missing_path(self):
|
||||
"""视频片尾缺少路径."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="video",
|
||||
outro_video_path="",
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "video_path" in msg
|
||||
|
||||
def test_text_outro_missing_title(self):
|
||||
"""文字片尾缺少标题."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="text",
|
||||
outro_title="",
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "title" in msg
|
||||
|
||||
def test_zero_intro_duration_invalid(self):
|
||||
"""片头时长为0无效."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="text",
|
||||
intro_title="test",
|
||||
intro_duration=0,
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "时长" in msg
|
||||
|
||||
def test_negative_outro_duration_invalid(self):
|
||||
"""片尾时长为负无效."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
outro_type="text",
|
||||
outro_title="test",
|
||||
outro_duration=-1.0,
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is False
|
||||
assert "时长" in msg
|
||||
|
||||
def test_valid_text_both(self):
|
||||
"""文字片头片尾都合法."""
|
||||
config = IntroOutroConfig(
|
||||
enabled=True,
|
||||
intro_type="text",
|
||||
intro_title="片头",
|
||||
intro_duration=3.0,
|
||||
outro_type="text",
|
||||
outro_title="片尾",
|
||||
outro_duration=3.0,
|
||||
)
|
||||
ok, msg = config.validate()
|
||||
assert ok is True
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user