Compare commits

..

4 Commits

Author SHA1 Message Date
xiaoxia c4b80921a0 test(#1677): E2E 适配新 5 步流程(批量生成改造)
- Step1 下一步 → 数量弹窗(默认 1 个)确认
- Step4 标题+预览+确认生成(左预览右栏标题)
- 单视频(N=1)点击「确认生成视频」直接跳 Step5 封面,与旧流程一致
2026-09-05 09:37:31 +08:00
xiaoxia 6846f68e03 fix(#1677): AI Review 防御性修复 — setState 函数式更新空数组兜底
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Successful in 1s
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 2s
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / PR Build API Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 1m34s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m51s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 2m0s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 2m17s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 2m20s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 2m38s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 2m40s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 6m13s
AI Code Review / AI Code Review (pull_request) Successful in 6m17s
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Successful in 6s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 4m40s
Preview Cleanup / Cleanup Preview Environment (pull_request) Successful in 16s
ACR Cleanup / ACR Image Cleanup (pull_request_target) Failing after 10m59s
- setPreviewTitles/setVoiceLibraryIds/setPreviewCovers/setSelectedVariantIds
  函数式更新中 prev 加 (prev || []) 兜底,防御状态重置场景
- 清理 poster={url || undefined} 冗余写法
2026-09-05 08:56:25 +08:00
xiaoxia b0ea3565ee fix(#1677): AI Review 阻塞项修复 — 配音模式切换同步+预览标题双重叠加
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 9s
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Successful in 10s
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / PR Build API Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 2m12s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 2m58s
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 2m32s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 3m24s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 3m45s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 2m59s
AI Code Review / AI Code Review (pull_request) Failing after 4m29s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 5m10s
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Successful in 5s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
PR Automation / Auto Approve on CI Green (pull_request) Failing after 11m0s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Has been skipped
- 配音同步 effect 响应模式切换:独立→共用时所有变体刷成共用配音;
  独立模式下共用配音变化仅同步变体[0],不覆盖用户单独选择
- 批量预览不再传 titles/title_config 给后端:标题由 CSS 浮层实时叠加,
  避免服务器预览视频烧录标题后与前端浮层双重显示;
  buildPreviewRequest 移除 titleSettings 依赖及 eslint-disable;
  预览指纹不含 titles,标题文字/样式变化不触发重渲染
2026-09-05 08:38:12 +08:00
xiaoxia 970380662e feat(#1677): 多视频批量生成前端 — 数量弹窗/批量预览/独立标题配音封面/5步流程
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 5s
CI/CD Pipeline / PR Build API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
Preview Deploy / Deploy Preview Environment (pull_request) Failing after 3s
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m58s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 3m12s
AI Code Review / AI Code Review (pull_request) Failing after 3m30s
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Failing after 10m10s
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Frontend Lint (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Successful in 1m42s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 1m50s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 2m7s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 10m53s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 4m21s
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Successful in 3s
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
- Step1 选模板后弹数量弹窗(1-10),1=单视频零回归,N>1=批量模式
- Step4 标题页布局对调:左侧大区域预览(单=Canvas实时预览,批量=服务器预览网格),
  右边栏标题设置;批量时N个独立标题输入框+CSS浮层实时叠加
- 确认生成合并进标题页:预览卡片带勾选框(默认全选),底部确认生成N个视频
- 批量预览:POST /preview 传 preview_count,N个task_id并行轮询
- Step3 配音:共用/独立开关,独立模式N个紧凑选择器,提交 voice_library_ids[]
- 封面步骤:N张封面卡片按勾选顺序展示,逐个AI生成/上传,提交 cover_urls[]
- 正式生成:POST /tasks 传 count + titles[]/voice_library_ids[]/cover_urls[]
  (长度1共用/长度N独立/空数组回退旧逻辑),批量任务并行轮询平均进度
- STEPS 6步→5步(模板/素材/配音/标题/封面),删除Step7确认生成冗余组件
2026-09-05 07:58:56 +08:00
36 changed files with 1130 additions and 2759 deletions
+11 -19
View File
@@ -14,7 +14,6 @@ from app.core.task_enqueue import (
USER_PENDING_LIMIT,
GlobalQueueFull,
UserPendingLimitExceeded,
build_rate_limit_detail,
safe_enqueue_generation_task,
)
from app.dependencies import (
@@ -313,12 +312,12 @@ def create_preview_generation_task(
except UserPendingLimitExceeded as e:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(e, generation_task_repository, scope="user"),
detail=f"您的待处理任务过多(当前 {e.pending_count - count}/{e.limit},本次提交 {count} 个),请等待后再提交",
) from e
except GlobalQueueFull as e:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(e, generation_task_repository, scope="global"),
detail="系统繁忙,请稍后再试",
) from e
# 确定视频比例:优先前端传入,否则从模板 mode 推断
@@ -499,7 +498,6 @@ def create_preview_generation_task(
# ── 入队 ──
responses: list[PreviewGenerationTaskResponse] = []
rate_limit_exc: Exception | None = None # 记录首个限流异常,全部失败时返回结构化提示
for variant_index, task in enumerate(created_tasks):
try:
enqueued = safe_enqueue_generation_task(
@@ -512,29 +510,23 @@ def create_preview_generation_task(
if not enqueued:
logger.warning("[预览生成] 任务入队失败: task_id=%s", task.id)
_mark_task_failed(generation_task_repository, task, "任务入队失败")
except UserPendingLimitExceeded as e:
except UserPendingLimitExceeded:
_mark_task_failed(generation_task_repository, task, "待处理任务超限")
rate_limit_exc = rate_limit_exc or e
except GlobalQueueFull as e:
except GlobalQueueFull:
_mark_task_failed(generation_task_repository, task, "系统队列已满")
rate_limit_exc = rate_limit_exc or e
except Exception:
logger.exception("[预览生成] 入队异常: task_id=%s", task.id)
_mark_task_failed(generation_task_repository, task, "任务入队异常")
# enqueue 会原地更新 task 状态/进度,直接用 task 构造响应
responses.append(_to_preview_response(task))
# 队列满/限流时若全部失败,返回结构化错误码(前端区分"排队"与"创建失败"
if all(r.status == "failed" for r in responses) and rate_limit_exc is not None:
if isinstance(rate_limit_exc, UserPendingLimitExceeded):
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(rate_limit_exc, generation_task_repository, scope="user"),
)
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(rate_limit_exc, generation_task_repository, scope="global"),
)
# 队列满/限流时若全部失败,返回明确错误码
if all(r.status == "failed" for r in responses):
first_err = next((r.error_message for r in responses if r.error_message), "")
if "待处理任务" in first_err:
raise HTTPException(status_code=429, detail=first_err or "待处理任务超限")
if "队列" in first_err:
raise HTTPException(status_code=503, detail=first_err or "系统繁忙,请稍后再试")
logger.info(
"[预览生成] 创建完成: %d 个变体任务, task_ids=%s",
+14 -27
View File
@@ -10,7 +10,6 @@ from app.core.task_enqueue import (
USER_PENDING_LIMIT,
GlobalQueueFull,
UserPendingLimitExceeded,
build_rate_limit_detail,
safe_enqueue_generation_task,
)
from app.dependencies import (
@@ -418,12 +417,12 @@ def create_generation_task(
except UserPendingLimitExceeded as e:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(e, generation_task_repository, scope="user"),
detail=f"您的待处理任务过多(当前 {e.pending_count - count}/{e.limit},本次提交 {count} 个),请等待完成后再提交",
) from e
except GlobalQueueFull as e:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(e, generation_task_repository, scope="global"),
detail="系统繁忙,请稍后再试",
) from e
# 画中画已下线:strategy_id 中的 pip/voice_pip 统一映射为 one_take
@@ -580,7 +579,7 @@ def create_generation_task(
if not created_tasks:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="user"),
detail="您的待处理任务过多,请等待完成后再提交",
) from _e
break
except GlobalQueueFull as _e:
@@ -588,7 +587,7 @@ def create_generation_task(
if not created_tasks:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="global"),
detail="系统繁忙,请稍后再试",
) from _e
break
except HTTPException:
@@ -714,15 +713,15 @@ def confirm_generation(
log_task_status=True,
):
logger.warning("[确认生成] 入队失败: task_id=%s", new_task.id)
except UserPendingLimitExceeded as _e:
except UserPendingLimitExceeded:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="user"),
detail="您的待处理任务过多,请等待完成后再提交",
) from None
except GlobalQueueFull as _e:
except GlobalQueueFull:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="global"),
detail="系统繁忙,请稍后再试",
) from None
return BatchGenerationTaskResponse(
@@ -804,24 +803,12 @@ def retry_generation_task(
if user_pending >= USER_PENDING_LIMIT:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(
UserPendingLimitExceeded(
user_id=user_id,
pending_count=user_pending,
limit=USER_PENDING_LIMIT,
),
generation_task_repository,
scope="user",
),
detail=f"您的待处理任务过多(当前 {user_pending}/{USER_PENDING_LIMIT}),请等待完成后再提交",
)
if global_pending >= GLOBAL_PENDING_LIMIT:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(
GlobalQueueFull(pending_count=global_pending, limit=GLOBAL_PENDING_LIMIT),
generation_task_repository,
scope="global",
),
detail="系统繁忙,请稍后再试",
)
use_case = CreateGenerationTaskUseCase(generation_task_repository)
@@ -856,15 +843,15 @@ def retry_generation_task(
log_task_status=True,
):
logger.warning("[生成任务] 重试入队失败: task_id=%s", retried.id)
except UserPendingLimitExceeded as _e:
except UserPendingLimitExceeded:
raise HTTPException(
status_code=429,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="user"),
detail="您的待处理任务过多,请等待完成后再提交",
) from None
except GlobalQueueFull as _e:
except GlobalQueueFull:
raise HTTPException(
status_code=503,
detail=build_rate_limit_detail(_e, generation_task_repository, scope="global"),
detail="系统繁忙,请稍后再试",
) from None
return _to_generation_task_response(retried)
+3 -7
View File
@@ -252,10 +252,6 @@ class RecomputeDedupRequest(BaseModel):
None,
description="指定视频 ID 列表。为空则对当前用户所有缺少查重数据的视频重新计算。",
)
force: bool = Field(
False,
description="强制重算:即使视频已有查重数据也重新入队(#1702 查重算法升级后用于存量视频重算)。",
)
class RecomputeDedupResponse(BaseModel):
@@ -295,15 +291,15 @@ def recompute_dedup(
skipped = 0
for video in target_videos:
# 已有完整查重数据的跳过force=True 时强制重算,#1702 算法升级后存量视频需要重算指纹/分片)
if not request.force and video.duplicate_rate is not None and video.video_fingerprint:
# 已有完整查重数据的跳过
if video.duplicate_rate is not None and video.video_fingerprint:
skipped += 1
continue
# 触发异步查重任务
celery_app.send_task("worker.check_duplicate", args=[video.id])
enqueued += 1
logger.info("Enqueued re-dedup for video %s (user=%s, force=%s)", video.id, user_id, request.force)
logger.info("Enqueued re-dedup for video %s (user=%s)", video.id, user_id)
return RecomputeDedupResponse(
enqueued=enqueued,
+2 -120
View File
@@ -8,145 +8,27 @@ logger = logging.getLogger(__name__)
# ── 限流阈值常量(全系统统一管理,不要在业务代码里硬编码) ──
USER_PENDING_LIMIT = 3 # 单用户 pending 上限
GLOBAL_PENDING_LIMIT = 20 # 全局 pending 上限
WORKER_CONCURRENCY = 4 # worker 渲染并发数(infra/docker/compose.yml WORKER_CONCURRENCY 默认值)
# 限流错误码:前端据此区分"排队等待"与"创建失败"
ERROR_CODE_USER_QUEUE_FULL = "USER_QUEUE_FULL" # 429:用户自己的任务排队中
ERROR_CODE_SYSTEM_QUEUE_FULL = "SYSTEM_QUEUE_FULL" # 503:系统整体繁忙
class UserPendingLimitExceeded(Exception):
"""用户 pending 任务数超限,返回 429。"""
def __init__(
self,
user_id: str,
pending_count: int,
limit: int,
*,
running_count: int = 0,
requested_count: int = 1,
queue_ahead: int = 0,
estimated_wait_seconds: int = 0,
):
def __init__(self, user_id: str, pending_count: int, limit: int):
self.user_id = user_id
self.pending_count = pending_count
self.limit = limit
# 排队上下文(用于 429 结构化提示,前端展示"排队中"而非"创建失败"
self.running_count = running_count
self.requested_count = requested_count
self.queue_ahead = queue_ahead
self.estimated_wait_seconds = estimated_wait_seconds
super().__init__(f"用户 {user_id} pending 任务数 {pending_count} 超过上限 {limit}")
class GlobalQueueFull(Exception):
"""全局限流,返回 503。"""
def __init__(
self,
pending_count: int,
limit: int,
*,
running_count: int = 0,
queue_ahead: int = 0,
estimated_wait_seconds: int = 0,
):
def __init__(self, pending_count: int, limit: int):
self.pending_count = pending_count
self.limit = limit
self.running_count = running_count
self.queue_ahead = queue_ahead
self.estimated_wait_seconds = estimated_wait_seconds
super().__init__(f"系统 pending 任务数 {pending_count} 超过上限 {limit}")
def _estimate_wait_seconds(queue_ahead: int, generation_task_repository: Any) -> int:
"""根据排队任务数 + worker 并发数 + 历史平均任务耗时估算等待秒数。
估算公式:ceil(排队任务数 / 并发数) × 平均单任务耗时。
拿不到历史数据时仓储层返回默认 120 秒。
"""
import math
if queue_ahead <= 0:
return 0
try:
estimator = getattr(generation_task_repository, "estimate_avg_duration_seconds", None)
avg_seconds = estimator() if estimator is not None else 120.0
except Exception:
avg_seconds = 120.0
return int(math.ceil(queue_ahead / WORKER_CONCURRENCY) * avg_seconds)
def build_rate_limit_detail(
exc: Exception,
generation_task_repository: Any,
*,
scope: str = "user",
) -> dict:
"""构造结构化限流响应体(HTTPException 的 detail)。
前端按 detail.code 判断场景:
- USER_QUEUE_FULL (429):用户自己的任务在排队,应提示"等待/继续排队",不是创建失败
- SYSTEM_QUEUE_FULL (503):系统繁忙,稍后重试
detail 字段:
- code: 错误码
- message: 可读中文提示(可直接展示)
- queued_count: 当前排队(pending)任务数
- running_count: 当前渲染中(running)任务数
- queue_ahead: 前方排队任务数(预计等待批次依据)
- estimated_wait_seconds: 预计等待秒数
- limit: 对应限流上限
"""
if scope == "user" and isinstance(exc, UserPendingLimitExceeded):
running = exc.running_count
if not running:
try:
counter = getattr(generation_task_repository, "count_running_by_user", None)
running = counter(exc.user_id) if counter is not None else 0
except Exception:
running = 0
queue_ahead = exc.queue_ahead or max(exc.pending_count, 0)
wait = exc.estimated_wait_seconds or _estimate_wait_seconds(queue_ahead, generation_task_repository)
wait_minutes = max(1, round(wait / 60))
message = (
f"您有 {exc.pending_count} 个任务正在排队、{running} 个正在渲染,"
f"同一时间最多提交 {exc.limit} 个任务。请等待约 {wait_minutes} 分钟后再提交"
)
return {
"code": ERROR_CODE_USER_QUEUE_FULL,
"message": message,
"queued_count": exc.pending_count,
"running_count": running,
"queue_ahead": queue_ahead,
"estimated_wait_seconds": wait,
"limit": exc.limit,
}
# 全局繁忙
pending = getattr(exc, "pending_count", 0)
running = getattr(exc, "running_count", 0)
if not running:
try:
counter = getattr(generation_task_repository, "count_running_total", None)
running = counter() if counter is not None else 0
except Exception:
running = 0
queue_ahead = getattr(exc, "queue_ahead", 0) or pending
wait = getattr(exc, "estimated_wait_seconds", 0) or _estimate_wait_seconds(queue_ahead, generation_task_repository)
wait_minutes = max(1, round(wait / 60))
return {
"code": ERROR_CODE_SYSTEM_QUEUE_FULL,
"message": f"系统繁忙:当前 {pending} 个任务排队中、{running} 个渲染中,预计等待约 {wait_minutes} 分钟,请稍后再试",
"queued_count": pending,
"running_count": running,
"queue_ahead": queue_ahead,
"estimated_wait_seconds": wait,
"limit": getattr(exc, "limit", GLOBAL_PENDING_LIMIT),
}
def check_queue_limits(
user_id: str,
generation_task_repository: Any,
+2 -18
View File
@@ -185,13 +185,6 @@ test.describe("Core generation flow", () => {
await expect(page.locator(".xx-choice-item.selected")).toBeVisible()
await page.getByRole("button", { name: "下一步" }).click()
// Step1 下一步弹出数量选择弹窗(Issue #1677 固定6步:模板→素材→配音→标题→确认生成→封面)
// 单视频流程:默认 1 个,点击「生成 1 个视频」进入步骤2
await expect(page.getByRole("heading", { name: "要生成几个视频?" })).toBeVisible({
timeout: 10_000,
})
await page.getByRole("button", { name: "生成 1 个视频" }).click()
// Step 2: select material (card grid UI)
await expect(page.getByRole("heading", { name: /选择素材/ })).toBeVisible()
const librarySelect = page.locator("select").first()
@@ -262,18 +255,9 @@ test.describe("Core generation flow", () => {
expect(genData.items.length).toBeGreaterThan(0)
expect(genData.items[0].id).toBeTruthy()
// 单视频(N=1):点击「确认生成视频」后跳 Step 5「确认生成」,展示实时渲染进度
await expect(page.getByRole("heading", { name: "🎬 确认生成" })).toBeVisible({
timeout: 30_000,
})
// 等待渲染完成:进度卡变为「视频生成完成」(最长等待 3 分钟)
await expect(page.getByText("视频生成完成")).toBeVisible({ timeout: 180_000 })
// 全部完成后「下一步:选择封面」解锁,点击进入 Step 6
await page.getByRole("button", { name: /下一步:选择封面/ }).click()
// 单视频(N=1):点击「确认生成视频」后直接跳 Step 5 封面(与旧流程一致)
await expect(page.getByRole("heading", { name: /选择封面/ })).toBeVisible({
timeout: 30_000,
timeout: 180_000,
})
} else {
console.log(`[E2E] Generate API returned ${genResp.status()}, wizard flow test still passes`)
+207 -80
View File
@@ -1,12 +1,11 @@
/**
* 智能剪辑页面(Issue #1677 多视频批量生成,修正版
* 固定 6 步向导:模板(弹数量) → 素材 → 配音 → 标题确认生成 → 封面,单视频与批量完全一致
* 智能剪辑页面(Issue #1677 多视频批量生成)
* 5 步向导:选择模板(弹数量) → 素材 → 配音 → 标题(预览+确认生成) → 封面
*
* 架构:
* - 预览全部为纯前端 Canvas 实时播放FrontendPreviewPlayer),不调任何后端渲染接口:
* N=1 单播放器;N>1 CanvasPreviewGridvariantSeed 让素材排布/起始点不同,画面有差异)
* - 步骤5确认生成:正式生成接口(count + titles[]/voice_library_ids[]/cover_urls[]),
* 批量时逐任务独立进度/失败重试(BatchGenerationGrid
* - N=1前端 Canvas 实时预览FrontendPreviewPlayer),零回归
* - N>1:服务器批量预览(POST /generation/preview?preview_count=N),
* N 个变体分别轮询,网格展示、独立可播放、CSS 标题浮层实时叠加、勾选批量生成
*/
import React, { useMemo, useState, useEffect, useRef, useCallback } from "react"
import { message } from "antd"
@@ -17,7 +16,7 @@ import { useCloneProgress } from "@/hooks/useCloneProgress"
import CloneModal from "@/components/voice/CloneModal"
import GenerateHeader from "./components/GenerateHeader"
import FrontendPreviewPlayer from "./components/FrontendPreviewPlayer"
import CanvasPreviewGrid from "./components/CanvasPreviewGrid"
import ServerPreviewGrid from "./components/ServerPreviewGrid"
import PreviewCountModal from "./components/PreviewCountModal"
import GenerateStepsBar from "./components/GenerateStepsBar"
import GenerateStepContent from "./components/GenerateStepContent"
@@ -25,11 +24,12 @@ import GenerateStepActions from "./components/GenerateStepActions"
import { useGenerateFormState } from "./hooks/useGenerateFormState"
import { useStepNavigation } from "./hooks/useStepNavigation"
import { useGenerateVideo } from "./hooks/useGenerateVideo"
import { useBatchPreview } from "./hooks/useBatchPreview"
import { usePreviewAssets } from "./hooks/usePreviewAssets"
import { useTitleStyleUpdaters } from "./hooks/useStep4Title/useTitleStyleUpdaters"
import { getAssetsByKind } from "@/api/assets"
import { previewTts } from "@/api/tts"
import { calculateResolution } from "./utils/calculateResolution"
import "./generate.css"
const GeneratePage: React.FC = () => {
@@ -132,8 +132,6 @@ const GeneratePage: React.FC = () => {
const [previewVoiceAudioUrl, setPreviewVoiceAudioUrl] = useState<string | null>(null)
const ttsAbortRef = useRef<AbortController | null>(null)
// TTS 试听文案:批量跟随变体0标题(仅取首项,避免编辑其他变体标题触发多余 TTS 请求)
const variant0Title = isBatch ? previewTitles?.[0] || "" : ""
useEffect(() => {
const voiceAsset = voiceMaterials.find((m) => m.id === selectedVoice)
@@ -142,10 +140,8 @@ const GeneratePage: React.FC = () => {
return
}
// 批量模式下 TTS 文案跟随变体0标题;单视频跟随主标题
const ttsTitle = isBatch ? variant0Title || "" : titleSettings.title
const voiceId = selectedClonedVoice || selectedVoice
if (!voiceId || !ttsTitle) {
if (!voiceId || !titleSettings.title) {
setPreviewVoiceAudioUrl(null)
return
}
@@ -155,7 +151,7 @@ const GeneratePage: React.FC = () => {
ttsAbortRef.current = controller
let cancelled = false
previewTts({ text: ttsTitle, voice_id: voiceId })
previewTts({ text: titleSettings.title, voice_id: voiceId })
.then((res) => {
if (!cancelled && res.audio_url) {
setPreviewVoiceAudioUrl(res.audio_url)
@@ -172,14 +168,7 @@ const GeneratePage: React.FC = () => {
cancelled = true
controller.abort()
}
}, [
selectedVoice,
selectedClonedVoice,
titleSettings.title,
variant0Title,
isBatch,
voiceMaterials,
])
}, [selectedVoice, selectedClonedVoice, titleSettings.title, voiceMaterials])
/* ── 克隆声音 ── */
const { addClone } = useCloneProgress()
@@ -218,8 +207,76 @@ const GeneratePage: React.FC = () => {
previewAssetsEnabled,
)
/* ── 预览就绪:纯前端 Canvas 预览,素材详情加载完即可秒开(单视频/批量一致) ── */
const previewReady = previewAssetsReady && !!currentTemplate
/* ── 预览就绪 ── */
const singlePreviewReady = useMemo(
() => previewAssetsReady && !!currentTemplate,
[previewAssetsReady, currentTemplate],
)
/* ── 批量服务器预览(N>1) ── */
const buildPreviewRequest = useCallback(() => {
const { width, height } = calculateResolution(videoRatio || "9:16")
const voiceLibraryId =
voiceMode === "clone" ? selectedClonedVoice || selectedVoice || "" : selectedVoice || ""
return {
template_id: selectedTemplate,
asset_ids: previewAssetIds,
output_width: width,
output_height: height,
video_ratio: videoRatio,
voice_library_id: voiceLibraryId,
...(voiceModePerVideo && voiceLibraryIds.some(Boolean)
? { voice_library_ids: voiceLibraryIds.map((id) => id || voiceLibraryId) }
: {}),
preview_count: previewCount,
// 批量预览不传 titles/title_config:标题文字与样式由前端 CSS 浮层实时叠加
// (用户改标题/样式即时可见,无需重渲染);正式生成时才把标题烧录进成片
duration: duration || undefined,
bgm_config: {
enabled: bgm !== false,
...(bgmConfig?.music_id ? { preset_id: bgmConfig.music_id } : {}),
},
...(storedSourceEditPlanId || sourceEditPlanId
? { source_edit_plan_id: storedSourceEditPlanId || sourceEditPlanId || undefined }
: {}),
}
}, [
videoRatio,
voiceMode,
selectedClonedVoice,
selectedVoice,
selectedTemplate,
previewAssetIds,
voiceModePerVideo,
voiceLibraryIds,
previewCount,
duration,
bgm,
bgmConfig,
storedSourceEditPlanId,
sourceEditPlanId,
])
const {
variants,
status: batchPreviewStatus,
progress: batchPreviewProgress,
failedCount: batchFailedCount,
trigger: retryBatchPreview,
} = useBatchPreview({
enabled: isBatch && currentStep >= 4 && previewAssetIds.length > 0 && !!selectedTemplate,
buildRequest: buildPreviewRequest,
onPreviewTasksCreated: (_taskIds, planId) => {
if (planId) setStoredSourceEditPlanId(planId)
},
})
/** 批量预览就绪:全部变体渲染完成 */
const batchPreviewReady =
isBatch && variants.length > 0 && variants.every((v) => v.status === "ready")
/** 步骤4整体预览就绪状态 */
const previewReady = isBatch ? batchPreviewReady : singlePreviewReady
/* ── 勾选变体 ── */
const toggleVariantSelect = useCallback(
@@ -239,10 +296,8 @@ const GeneratePage: React.FC = () => {
generated,
generateError,
generatedVideos,
batchTasks,
generate: handleGenerate,
retry: handleRetryGenerate,
retryBatchTask: handleRetryBatchTask,
dismissError: handleDismissError,
download: handleDownload,
share: handleShare,
@@ -310,43 +365,31 @@ const GeneratePage: React.FC = () => {
],
)
/* ── 步骤4「确认生成视频」:校验通过 → 创建正式生成任务 → 跳步骤5看实时进展 ── */
/* ── 步骤4「确认生成视频」 ── */
const handleConfirmGenerate = useCallback(async () => {
// 标题校验:批量只校验已勾选的变体;单视频校验主标题
if (isBatch) {
if (selectedVariantIds.length === 0) {
message.warning("请至少勾选一个视频")
return
}
const missing = selectedVariantIds.some((i) => !previewTitles[i]?.trim())
if (missing) {
message.warning("请为每个勾选的视频输入标题")
return
}
} else if (!titleSettings.title?.trim()) {
// 与 buildPayload.validateGenerateInputs 一致:AI 自动选标题模式(aiAutoSelect
// 允许空标题由后端生成;手动模式必须填写,避免提交空标题
if (!titleSettings.aiAutoSelect) {
message.warning("请先选择或输入标题")
return
}
// 标题校验
if (previewTitles.some((t) => !t?.trim())) {
message.warning("请为每个视频输入标题")
return
}
if (isBatch && selectedVariantIds.length === 0) {
message.warning("请至少勾选一个视频")
return
}
if (!previewReady) {
message.warning("预览素材正在加载,请稍候")
message.warning("预览视频正在加载,请稍候")
return
}
const ok = await handleGenerate()
if (ok) {
// 单视频与批量一致:任务创建成功后进入步骤5「确认生成」看实时渲染进展
if (ok && !isBatch) {
setCurrentStep(5)
}
// 批量模式停留在步骤4,右侧网格显示生成进度,完成后点"下一步"进封面
}, [
isBatch,
selectedVariantIds,
previewTitles,
titleSettings.aiAutoSelect,
titleSettings.title,
selectedVariantIds.length,
previewReady,
previewTitles,
handleGenerate,
setCurrentStep,
])
@@ -360,20 +403,25 @@ const GeneratePage: React.FC = () => {
selectedMaterials,
smartSelectedIds,
titleSettings,
previewReady,
generated,
previewTitles,
selectedCount: isBatch ? selectedVariantIds.length : 1,
onOpenCountModal: () => setCountModalOpen(true),
})
/* ── 最终成片(单视频右侧播放) ── */
const finalVideo = generatedVideos[0]
/* ── 布局 class:步骤4标题页=预览+标题侧栏;步骤5/6批量=整行宽;步骤1~3=整行宽 ── */
const layoutClassName = useMemo(() => {
if (currentStep < 4) return "xx-generate-layout full-width"
if (currentStep === 4) return "xx-generate-layout step4-layout"
// 步骤5/6:批量网格需要整行宽度;单视频保持 表单+右侧成片 两栏
return isBatch ? "xx-generate-layout full-width" : "xx-generate-layout"
}, [currentStep, isBatch])
/** 批量生成进度文案 */
const batchGeneratingText = useMemo(() => {
if (batchPreviewStatus === "loading")
return `AI 正在渲染 ${previewCount} 个预览视频… ${batchPreviewProgress}%`
if (batchPreviewStatus === "failed") return "预览渲染失败,请重试"
if (batchPreviewStatus === "partial_failed")
return `${batchFailedCount} 个预览失败,可重新生成或勾选成功的视频`
return ""
}, [batchPreviewStatus, batchPreviewProgress, batchFailedCount, previewCount])
/* ================================================================
渲染
@@ -385,12 +433,16 @@ const GeneratePage: React.FC = () => {
<GenerateStepsBar currentStep={currentStep} onStepClick={setCurrentStep} />
<div className={layoutClassName}>
{/* ════ 步骤4:左侧预览大区域(纯前端 Canvas 实时预览) ════ */}
<div
className={`xx-generate-layout${currentStep < 4 ? " full-width" : ""}${
currentStep === 4 ? " step4-layout" : ""
}`}
>
{/* ════ 步骤4:左侧预览大区域 ════ */}
{currentStep === 4 && !!currentTemplate && (
<div className="xx-generate-preview-col">
{!isBatch ? (
/* 单视频:前端 Canvas 实时预览(与旧版一致,零回归 */
/* 单视频:前端 Canvas 实时预览(与旧版一致) */
<FrontendPreviewPlayer
assets={previewAssets}
template={currentTemplate}
@@ -414,32 +466,109 @@ const GeneratePage: React.FC = () => {
onTitlePositionChange={styleUpdaters.updateTitlePosition}
/>
) : (
/* 批量:N 个前端 Canvas 预览网格(不调任何后端渲染接口,秒开) */
/* 批量:服务器预览网格 */
<div className="xx-form-section">
<div className="xx-preview-header">
<h3>🎬 {previewCount} </h3>
<span style={{ fontSize: 13, color: "var(--text-secondary, #666)" }}>
</span>
{batchPreviewStatus === "loading" && (
<span style={{ fontSize: 13, color: "var(--text-secondary, #666)" }}>
{batchPreviewProgress}%
</span>
)}
{(batchPreviewStatus === "failed" || batchPreviewStatus === "partial_failed") && (
<button
type="button"
className="xx-btn xx-btn-ghost xx-btn-sm"
onClick={retryBatchPreview}
>
🔄
</button>
)}
</div>
<CanvasPreviewGrid
count={previewCount}
assets={previewAssets}
template={currentTemplate}
videoRatio={videoRatio}
{batchGeneratingText && (
<div
style={{
fontSize: 13,
color:
batchPreviewStatus === "failed"
? "var(--error-color, #ef4444)"
: "var(--text-secondary, #666)",
marginBottom: 12,
}}
>
{batchGeneratingText}
</div>
)}
<ServerPreviewGrid
variants={variants}
titles={previewTitles}
titleSettings={titleSettings}
voiceAudioUrl={previewVoiceAudioUrl || undefined}
titleStyle={{
position: titleSettings.position,
color: titleSettings.color,
size: titleSettings.size,
}}
selectedIds={selectedVariantIds}
onToggleSelect={toggleVariantSelect}
selectable={!generating}
/>
{/* 生成中进度(批量) */}
{generating && (
<div className="xx-gen-progress-card" style={{ marginTop: 16 }}>
<div className="xx-gen-progress-header">
<div className="xx-gen-progress-info">
<div className="xx-gen-progress-phase">
{selectedVariantIds.length} {Math.round(progress)}
%
</div>
<div className="xx-gen-progress-sub">
</div>
</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>
)}
{generateError && !generating && (
<div className="xx-gen-error-card" style={{ marginTop: 16 }}>
<div className="xx-gen-error-info">
<div className="xx-gen-error-title"></div>
<div className="xx-gen-error-msg">{generateError}</div>
</div>
<button
type="button"
className="xx-btn xx-btn-primary xx-btn-sm"
onClick={handleRetryGenerate}
>
🔄
</button>
</div>
)}
{generated && !generating && (
<div className="xx-gen-success-card" style={{ marginTop: 16 }}>
<div className="xx-gen-success-info">
<div className="xx-gen-success-title"> </div>
<div className="xx-gen-success-sub">
{generatedVideos.length}
</div>
</div>
</div>
)}
</div>
)}
</div>
)}
{/* ════ 右侧:步骤1~3 表单 / 步骤4 标题边栏 / 步骤5 确认生成进度 / 步骤6 封面 ════ */}
{/* ════ 右侧:步骤1~3 表单 / 步骤4 标题边栏 / 步骤5 封面 ════ */}
<div className="xx-generate-form">
<GenerateStepContent
currentStep={currentStep}
@@ -477,9 +606,7 @@ const GeneratePage: React.FC = () => {
progress={progress}
generatedVideos={generatedVideos}
onRetry={handleRetryGenerate}
onRetryBatchTask={handleRetryBatchTask}
onDismissError={handleDismissError}
batchTasks={batchTasks}
previewCount={previewCount}
previewTitles={previewTitles}
onPreviewTitlesChange={setPreviewTitles}
@@ -504,16 +631,16 @@ const GeneratePage: React.FC = () => {
/>
</div>
{/* ════ 步骤5/6(单视频):右侧成片播放器 ════ */}
{currentStep >= 5 && !isBatch && generated && finalVideo && (
{/* ════ 步骤5(封面):成片播放器(单视频) ════ */}
{currentStep === 5 && !isBatch && generated && finalVideo && (
<div className="xx-generate-right-col">
<div className="xx-inline-video-player">
<video
src={finalVideo.download_url || finalVideo.file_url}
controls
autoPlay={currentStep === 5}
autoPlay
style={{ width: "100%", maxHeight: "70vh", objectFit: "contain", borderRadius: 12 }}
poster={finalVideo.thumbnail_url || undefined}
poster={finalVideo.thumbnail_url}
/>
<div style={{ display: "flex", gap: 8, marginTop: 12, justifyContent: "center" }}>
<button className="xx-btn xx-btn-ghost xx-btn-sm" onClick={handleDownload}>
@@ -1,100 +0,0 @@
/**
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677
*
* N 个正式生成任务各自独立卡片:进度条 / 成功成片播放 / 失败原因 + 单独重试。
* 数据来自 useGenerateVideo 的 batchTasksuseGenerationPolling 实时回传)。
*/
import React from "react"
import { LoadingOutlined, CheckCircleFilled, CloseCircleOutlined } from "@ant-design/icons"
import type { BatchTaskState } from "../hooks/generate-video/useGenerationPolling"
import type { GeneratedVideo } from "@/api/template-editor"
interface BatchGenerationGridProps {
tasks: BatchTaskState[]
/** 变体标题(按变体序号取) */
titles: string[]
/** 失败任务重试 */
onRetryTask: (taskId: string) => void
}
const BatchGenerationGrid: React.FC<BatchGenerationGridProps> = ({
tasks,
titles,
onRetryTask,
}) => {
const sorted = [...tasks].sort(
(a, b) => Number(a.variantIndex || 0) - Number(b.variantIndex || 0),
)
return (
<div className="xx-form-section">
<div className="xx-preview-header">
<h3>🎬 {tasks.length} </h3>
<span style={{ fontSize: 13, color: "var(--text-secondary, #666)" }}>
{tasks.filter((t) => t.status === "completed").length} / {tasks.length}
</span>
</div>
<div className="xx-batch-gen-grid">
{sorted.map((task) => {
const title = titles[task.variantIndex] || `视频 ${task.variantIndex + 1}`
const video = (task.videos?.[0] || null) as GeneratedVideo | null
return (
<div key={task.taskId} className={`xx-batch-gen-card status-${task.status}`}>
<div className="xx-batch-gen-card-head">
<span className="xx-batch-gen-card-title" title={title}>
{task.status === "completed" ? (
<CheckCircleFilled style={{ color: "#52c41a", marginRight: 6 }} />
) : task.status === "failed" ? (
<CloseCircleOutlined style={{ color: "#ef4444", marginRight: 6 }} />
) : (
<LoadingOutlined style={{ color: "#1677ff", marginRight: 6 }} />
)}
{task.variantIndex + 1}{title}
</span>
</div>
<div className="xx-batch-gen-card-body">
{task.status === "running" && (
<>
<div className="xx-gen-progress-bar">
<div
className="xx-gen-progress-bar-fill"
style={{ width: `${Math.min(task.progress, 100)}%` }}
/>
</div>
<div className="xx-batch-gen-card-pct">{Math.round(task.progress)}%</div>
</>
)}
{task.status === "completed" && video && (
<video
src={video.download_url || video.file_url}
controls
style={{ width: "100%", borderRadius: 8, background: "#000", maxHeight: 280 }}
poster={video.thumbnail_url}
/>
)}
{task.status === "completed" && !video && (
<div className="xx-batch-gen-card-done"> </div>
)}
{task.status === "failed" && (
<div className="xx-batch-gen-card-failed">
<div className="xx-batch-gen-card-err">{task.error || "生成失败"}</div>
<button
type="button"
className="xx-btn xx-btn-primary xx-btn-sm"
onClick={() => onRetryTask(task.taskId)}
>
🔄
</button>
</div>
)}
</div>
</div>
)
})}
</div>
</div>
)
}
export default BatchGenerationGrid
@@ -1,97 +0,0 @@
/**
* 批量前端 Canvas 实时预览网格(Issue #1677 修正方案)
*
* N 个 FrontendPreviewPlayer 网格排列:
* - 纯前端 Canvas + video 元素实时播放素材片段,不调任何后端渲染接口
* - variantSeed 让每个变体素材排布/起始点不同,画面有可见差异
* - 各自叠加独立标题浮层(variantTitle),标题样式全局共用
* - 勾选框决定提交时生成哪些变体
*/
import React from "react"
import type { AssetItem } from "@/api/assets"
import type { EditingTemplate } from "@/api/editing-planner"
import type { TitleSettings } from "../types"
import FrontendPreviewPlayer from "./FrontendPreviewPlayer"
interface CanvasPreviewGridProps {
count: number
assets: AssetItem[]
template: EditingTemplate | null
videoRatio: string
titles: string[]
titleSettings: TitleSettings
/** 共用配音预览音频(仅第 1 个变体播放,避免多路音频重叠) */
voiceAudioUrl?: string
/** 勾选的变体序号 */
selectedIds: number[]
onToggleSelect: (index: number) => void
/** 生成中禁止勾选 */
selectable?: boolean
}
const CanvasPreviewGrid: React.FC<CanvasPreviewGridProps> = ({
count,
assets,
template,
videoRatio,
titles,
titleSettings,
voiceAudioUrl,
selectedIds,
onToggleSelect,
selectable = true,
}) => {
// count 上限已在源头 PreviewCountModal 的数量选择(1~MAX_PREVIEW_COUNT=10clamp
// 这里完整渲染所有变体,保证每个变体都有勾选/预览入口,UI 与数据不脱节
return (
<div className="xx-canvas-grid">
{Array.from({ length: count }, (_, i) => {
const checked = selectedIds.includes(i)
return (
<div
key={i}
className={`xx-canvas-grid-card${checked ? " selected" : ""}`}
data-variant={i}
>
<div className="xx-canvas-grid-card-bar">
<label className="xx-canvas-grid-check">
<input
type="checkbox"
checked={checked}
disabled={!selectable}
onChange={() => onToggleSelect(i)}
/>
<span> {i + 1}</span>
</label>
</div>
<FrontendPreviewPlayer
assets={assets}
template={template}
videoRatio={videoRatio}
ready={assets.length > 0}
variantSeed={i + 1}
variantTitle={titles[i] || ""}
voiceAudioUrl={i === 0 ? voiceAudioUrl : undefined}
compact
titleSettings={{
title: titles[i] || "",
size: titleSettings.size,
font: titleSettings.font,
color: titleSettings.color,
position: titleSettings.position as "top" | "center" | "bottom" | "custom",
bold: titleSettings.bold,
italic: titleSettings.italic,
stroke: titleSettings.stroke,
shadow: titleSettings.shadow,
posX: titleSettings.posX,
posY: titleSettings.posY,
}}
/>
</div>
)
})}
</div>
)
}
export default CanvasPreviewGrid
@@ -41,16 +41,6 @@ interface FrontendPreviewPlayerProps {
posY?: number | null
}
onTitlePositionChange?: (posX: number, posY: number) => void
/**
* 变体种子(批量生成 #1677):同一批素材在不同变体中采用不同的素材顺序与
* 片段起始点,让 N 个 Canvas 预览画面有差异(纯前端随机剪辑模拟,不调后端)。
* 0 / 不传 = 单视频,排布与旧版完全一致(零回归)。
*/
variantSeed?: number
/** 变体标题文字(批量时每个预览独立标题,叠加在画面上);不传用 titleSettings.title */
variantTitle?: string
/** 紧凑模式(批量网格中使用,缩小内边距/标题尺寸) */
compact?: boolean
}
function formatTime(seconds: number): string {
@@ -62,23 +52,10 @@ function formatTime(seconds: number): string {
/**
* 将素材映射为播放片段(复用原逻辑)
*/
/** 简单可复现随机数(mulberry32),同一种子产出稳定排布,避免每次渲染抖动 */
function seededRandom(seed: number): () => number {
let a = seed >>> 0
return () => {
a |= 0
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
function buildPlaybackSegments(
assets: AssetItem[],
template: EditingTemplate | null,
serverClips?: EditPlanClip[],
variantSeed = 0,
): PlaybackSegment[] {
if (!assets.length) return []
@@ -102,40 +79,18 @@ function buildPlaybackSegments(
}
}
// Fallback: 本地构建片段
// variantSeed=0(单视频):与旧行为完全一致(素材原序、起始点 0),零回归
// variantSeed>0(批量变体):素材顺序按种子轮换 + 片段起始点在素材内偏移,
// 模拟后端"AI 随机剪辑出不同版本",让 N 个预览画面有可见差异
// Fallback: 本地构建片段(与旧行为一致)
const templateSegments = template?.segments || []
const segments: PlaybackSegment[] = []
const orderedAssets = variantSeed > 0 ? [...assets] : assets
if (variantSeed > 0 && orderedAssets.length > 1) {
const rand = seededRandom(variantSeed * 7919 + 13)
// 素材轮换:把数组旋转 (seed % n) 位,再对后半段做一次稳定交换
const n = orderedAssets.length
const rotate = variantSeed % n
orderedAssets.push(...orderedAssets.splice(0, rotate))
const swapA = Math.floor(rand() * n)
const swapB = Math.floor(rand() * n)
if (swapA !== swapB) {
;[orderedAssets[swapA], orderedAssets[swapB]] = [orderedAssets[swapB], orderedAssets[swapA]]
}
}
orderedAssets.forEach((asset, i) => {
assets.forEach((asset, i) => {
const assetDuration = asset.duration || asset.metadata?.duration || 30
const tplSeg = templateSegments[i] || templateSegments[templateSegments.length - 1]
const segDuration = tplSeg
? Math.min(tplSeg.duration_max, Math.max(tplSeg.duration_min, assetDuration))
: Math.min(assetDuration, 10)
let startTime = 0
if (variantSeed > 0 && assetDuration - segDuration > 1) {
const rand = seededRandom(variantSeed * 104729 + i * 31 + 7)
// 起始点在素材可用区间内随机偏移(至少留 0.5s 余量)
const maxStart = Math.max(0, assetDuration - segDuration - 0.5)
startTime = Math.round(rand() * maxStart * 10) / 10
}
const startTime = 0
const endTime = Math.min(startTime + segDuration, assetDuration)
const videoUrl = asset.file_url || asset.storage_key
@@ -154,16 +109,11 @@ const FrontendPreviewPlayer: React.FC<FrontendPreviewPlayerProps> = ({
voiceAudioUrl,
titleSettings,
onTitlePositionChange,
variantSeed = 0,
variantTitle,
compact = false,
}) => {
const segments = useMemo(
() => buildPlaybackSegments(assets, template, serverClips, variantSeed),
[assets, template, serverClips, variantSeed],
() => buildPlaybackSegments(assets, template, serverClips),
[assets, template, serverClips],
)
// 批量变体:标题文字取 variantTitle,样式仍由全局 titleSettings 控制
const effectiveTitle = variantTitle ?? titleSettings?.title
// ── ASS 坐标系参数(与后端 ass_subtitle_builder.py 一致) ──
const TITLE_MARGIN_TOP = 120
@@ -284,7 +234,7 @@ const FrontendPreviewPlayer: React.FC<FrontendPreviewPlayerProps> = ({
// ── Canvas 播放器(WebCodecs 路径) ──
const canvasTitle = titleSettings
? {
text: effectiveTitle || "标题预览",
text: titleSettings.title || "标题预览",
fontSize: titleSettings.size,
fontFamily: titleSettings.font || "思源黑体",
color: titleSettings.color || "#ffffff",
@@ -570,15 +520,13 @@ const FrontendPreviewPlayer: React.FC<FrontendPreviewPlayerProps> = ({
style={{
position: "relative",
width: "100%",
maxWidth: compact ? "100%" : 280,
margin: compact ? 0 : "0 auto",
maxWidth: 280,
aspectRatio: "9 / 16",
background: "#0a0a0a",
borderRadius: compact ? 10 : 24,
borderRadius: 24,
overflow: "hidden",
boxShadow: compact
? "inset 0 0 0 1px rgba(255,255,255,0.06)"
: "0 4px 6px -1px rgba(0,0,0,0.3), 0 20px 50px -12px rgba(0,0,0,0.5), inset 0 0 0 1px rgba(255,255,255,0.06)",
boxShadow:
"0 4px 6px -1px rgba(0,0,0,0.3), 0 20px 50px -12px rgba(0,0,0,0.5), inset 0 0 0 1px rgba(255,255,255,0.06)",
}}
>
{/* ── Canvas 渲染层(WebCodecs 路径) ── */}
@@ -662,8 +610,8 @@ const FrontendPreviewPlayer: React.FC<FrontendPreviewPlayerProps> = ({
? { top: "50%", transform: "translate(-50%, -50%)" }
: { bottom: `${titleBottomPct}%` }),
}),
pointerEvents: onTitlePositionChange && variantSeed === 0 ? "auto" : "none",
cursor: onTitlePositionChange && variantSeed === 0 ? "grab" : "default",
pointerEvents: "auto",
cursor: onTitlePositionChange ? "grab" : "default",
touchAction: "none",
userSelect: "none",
WebkitUserSelect: "none",
@@ -693,7 +641,7 @@ const FrontendPreviewPlayer: React.FC<FrontendPreviewPlayerProps> = ({
: undefined,
}}
>
{(effectiveTitle || "").split(/[/]/).map((part, i) => (
{titleSettings.title.split(/[/]/).map((part, i) => (
<span key={i}>
{i > 0 && <br />}
{part}
@@ -1,10 +1,10 @@
/**
* GeneratePage 步骤底部操作按钮(Issue #1677 修正:固定 6 步)
* GeneratePage 步骤底部操作按钮(Issue #1677 改造后 5 步)
*
* 步骤 1~3:上一步 / 下一步
* 步骤 4选择标题):「✨ 确认生成视频 / 确认生成 N 个视频」→ 创建正式生成任务,成功后跳步骤5
* 步骤 5(确认生成):渲染进度页,全部完成后「下一步:选择封面」;仅上一步
* 步骤 6(选择封面):仅上一步
* 步骤 4标题+预览+确认生成):确认生成按钮在右侧边栏底部(含勾选数量),
* 渲染中显示进度;生成完成后显示"下一步 → 选择封面"
* 步骤 5(选择封面):仅上一步
*/
import React from "react"
@@ -12,7 +12,7 @@ export interface GenerateStepActionsProps {
currentStep: number
onPrev: () => void
onNext: () => void
/** 步骤4:确认生成视频(校验 + 创建渲染任务) */
/** 步骤4:确认生成视频(校验 + 创建渲染任务 + 成功后进入步骤5 */
onConfirmGenerate: () => void | Promise<void>
generating: boolean
generated: boolean
@@ -41,19 +41,26 @@ const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
)
}
/* 步骤 4选择标题 — 确认生成 */
/* 步骤 4标题+预览+确认生成 */
if (currentStep === 4) {
if (generating) {
return (
<button className="xx-btn xx-btn-primary" disabled>
</button>
)
}
if (generateError) {
return (
<button className="xx-btn xx-btn-primary" onClick={onConfirmGenerate}>
🔄
🔄
</button>
)
}
if (generated) {
return (
<button className="xx-btn xx-btn-primary" onClick={onNext}>
</button>
)
}
@@ -64,23 +71,7 @@ const GenerateStepActions: React.FC<GenerateStepActionsProps> = ({
)
}
/* 步骤 5:确认生成进度页 — 全部完成后下一步进封面 */
if (currentStep === 5) {
if (generated) {
return (
<button className="xx-btn xx-btn-primary" onClick={onNext}>
</button>
)
}
return (
<button className="xx-btn xx-btn-primary" disabled>
</button>
)
}
/* 步骤 6(封面,最后一步):无主按钮 */
/* 步骤 5(封面,最后一步):无主按钮 */
return null
}
@@ -1,7 +1,6 @@
/**
* GeneratePage 步骤内容渲染
* 步骤顺序(6步,Issue #1677 修正):模板(1) → 素材(2) → 配音(3) → 标题(4) → 确认生成(5) → 封面(6)
* 步骤4预览(Canvas 网格)与步骤5进度(批量渲染网格)由 GeneratePage 直接渲染在左侧大区域。
* 步骤顺序(5步,Issue #1677):模板(1) → 素材(2) → 配音(3) → 标题+预览+确认生成(4) → 封面(5)
*/
import React from "react"
import type { EditingTemplate } from "@/api/editing-planner"
@@ -13,8 +12,6 @@ import Step2MaterialSelect from "../components/Step2MaterialSelect"
import Step3VoiceWithMode from "./Step3VoiceWithMode"
import Step4TitleSettings from "../components/Step4TitleSettings"
import Step6CoverSettings from "../components/Step6CoverSettings"
import BatchGenerationGrid from "./BatchGenerationGrid"
import type { BatchTaskState } from "../hooks/generate-video/useGenerationPolling"
import type { GeneratedVideo } from "@/api/template-editor"
export interface GenerateStepContentProps {
@@ -57,10 +54,7 @@ export interface GenerateStepContentProps {
progress: number
generatedVideos: GeneratedVideo[]
onRetry: () => void
onRetryBatchTask: (taskId: string) => void
onDismissError: () => void
/** 批量:每个正式生成任务的独立状态(步骤5进度网格) */
batchTasks: BatchTaskState[]
/** BGM 开关 */
bgm: boolean
/** BGM 配置(来自模板) */
@@ -108,14 +102,7 @@ export const GenerateStepContent: React.FC<GenerateStepContentProps> = (props) =
selectedVoice,
onSelectedVoiceChange,
onServerClipsChange,
generating,
generated,
generateError,
progress,
onRetry,
generatedVideos,
batchTasks,
onRetryBatchTask,
previewCount,
previewTitles,
onPreviewTitlesChange,
@@ -189,62 +176,6 @@ export const GenerateStepContent: React.FC<GenerateStepContentProps> = (props) =
/>
)
case 5:
/* 确认生成页:批量=逐任务进度网格;单视频=进度状态卡(成片播放器在左侧大区域) */
if (previewCount > 1) {
return (
<BatchGenerationGrid
tasks={batchTasks}
titles={previewTitles}
onRetryTask={onRetryBatchTask}
/>
)
}
/* 单视频:渲染进度 / 失败重试 / 完成提示(成片播放器在右侧栏) */
return (
<div className="xx-form-section">
<h3>🎬 </h3>
{generating && (
<div className="xx-gen-progress-card">
<div className="xx-gen-progress-header">
<div className="xx-gen-progress-info">
<div className="xx-gen-progress-phase">
{Math.round(progress)}%
</div>
<div className="xx-gen-progress-sub">
</div>
</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>
)}
{generateError && !generating && (
<div className="xx-gen-error-card">
<div className="xx-gen-error-info">
<div className="xx-gen-error-title"></div>
<div className="xx-gen-error-msg">{generateError}</div>
</div>
<button type="button" className="xx-btn xx-btn-primary xx-btn-sm" onClick={onRetry}>
🔄
</button>
</div>
)}
{generated && !generating && (
<div className="xx-gen-success-card">
<div className="xx-gen-success-info">
<div className="xx-gen-success-title"> </div>
<div className="xx-gen-success-sub"></div>
</div>
</div>
)}
</div>
)
case 6:
return (
<Step6CoverSettings
coverSettings={coverSettings}
@@ -0,0 +1,127 @@
/**
* 批量预览网格(Issue #1677
* N 个服务器渲染的预览视频,网格排列、各自独立播放、CSS 标题浮层实时叠加、勾选框批量选择
*/
import React from "react"
import { LoadingOutlined, CheckCircleFilled, CloseCircleOutlined } from "@ant-design/icons"
import type { VariantPreview } from "../hooks/useBatchPreview"
interface ServerPreviewGridProps {
variants: VariantPreview[]
/** 每个变体的标题文字(实时叠加浮层) */
titles: string[]
/** 标题样式(全局共用) */
titleStyle: {
position: string
color: string
size: number
}
/** 勾选的变体索引 */
selectedIds: number[]
onToggleSelect: (index: number) => void
/** 是否显示勾选框(确认生成前) */
selectable?: boolean
}
const ServerPreviewGrid: React.FC<ServerPreviewGridProps> = ({
variants,
titles,
titleStyle,
selectedIds,
onToggleSelect,
selectable = true,
}) => {
if (variants.length === 0) return null
return (
<div className="xx-variant-grid">
{variants.map((v) => {
const selected = selectedIds.includes(v.index)
const titleText = titles[v.index] || ""
return (
<div
key={v.index}
className={`xx-variant-card ${selected ? "selected" : ""} ${
v.status === "failed" ? "failed" : ""
}`}
onClick={() => {
if (selectable && v.status === "ready") onToggleSelect(v.index)
}}
role="button"
tabIndex={0}
>
{/* 勾选框 */}
{selectable && v.status === "ready" && (
<div className={`xx-variant-check ${selected ? "checked" : ""}`}>
{selected && "✓"}
</div>
)}
{/* 变体序号 */}
<div className="xx-variant-index"> {v.index + 1}</div>
{/* 视频区域 */}
<div className="xx-variant-video-wrap">
{v.status === "loading" && (
<div className="xx-variant-loading">
<LoadingOutlined style={{ fontSize: 28, color: "#3b82f6" }} />
<div className="xx-variant-progress">
<div
className="xx-variant-progress-bar"
style={{ width: `${Math.min(v.progress, 100)}%` }}
/>
</div>
<span className="xx-variant-progress-text">{v.progress}%</span>
</div>
)}
{v.status === "failed" && (
<div className="xx-variant-failed">
<CloseCircleOutlined style={{ fontSize: 28, color: "#ef4444" }} />
<span>{v.error || "预览失败"}</span>
</div>
)}
{v.status === "ready" && v.videoUrl && (
<>
<video
src={v.videoUrl}
controls
style={{ width: "100%", display: "block", background: "#000", borderRadius: 8 }}
onClick={(e) => e.stopPropagation()}
/>
{/* 标题浮层(CSS 实时叠加,改标题即时可见) */}
{titleText && (
<div
className={`xx-variant-title-overlay pos-${titleStyle.position}`}
style={{
color: titleStyle.color,
fontSize: Math.max(13, Math.round(titleStyle.size * 0.55)),
WebkitTextStroke: "0.5px rgba(0,0,0,0.6)",
}}
onClick={(e) => e.stopPropagation()}
>
{titleText}
</div>
)}
</>
)}
</div>
{/* 底部状态 */}
<div className="xx-variant-footer">
{v.status === "ready" && selected && (
<span className="xx-variant-ready-tag">
<CheckCircleFilled style={{ color: "#52c41a" }} />
</span>
)}
{v.status === "ready" && !selected && selectable && (
<span className="xx-variant-skip-tag">/</span>
)}
</div>
</div>
)
})}
</div>
)
}
export default ServerPreviewGrid
@@ -1,22 +1,18 @@
/**
* Step 4 选择标题(Issue #1677 批量生成)
* Step 4 选择标题(Issue #1677 批量生成改造
*
* 布局(由 GeneratePage 编排):左侧大区域实时预览(单=大播放器,批量=Canvas 网格),
* 右侧边栏标题设置。本组件渲染在右侧边栏:
* - 单视频:AI 标题生成器 + AutoComplete 标题库(与旧版完全一致,零回归)
* - 批量:N 个独立标题输入框(AutoComplete 支持标题库选择)+ 批量 AI 生成
* (一次生成 N 个标题,分别填入各变体,可单独换一个)
* 布局(由 GeneratePage 编排):左侧大区域预览,右侧边栏标题设置。
* 本组件渲染在右侧边栏:
* - 标题文字:1 个视频 1 个输入框;N 个视频 N 个输入框各自独立
* - 标题样式(字体/颜色/位置/大小/粗斜描边/预设):全局统一
*/
import React, { useMemo, useState } from "react"
import { AutoComplete, Input, message } from "antd"
import { LoadingOutlined } from "@ant-design/icons"
import React from "react"
import { AutoComplete, Input } from "antd"
import type { TitleSettings } from "../types"
import { POSITION_OPTIONS, FONT_OPTIONS } from "../constants"
import { useStep4Title } from "../hooks/useStep4Title"
import AiTitleGenerator from "./title/AiTitleGenerator"
import TitleStylePanel from "./title/TitleStylePanel"
import { AI_TITLE_TEMPLATES } from "../constants"
interface Step4TitleSettingsProps {
titleSettings: TitleSettings
@@ -42,36 +38,6 @@ interface Step4TitleSettingsProps {
onPreviewTitlesChange?: (titles: string[]) => void
}
/** 从本地 AI 标题模板池按主题词生成 N 个不同标题(与单视频 AI 生成同源) */
function buildBatchAiTitles(topic: string, count: number): string[] {
const styles: Array<"catchy" | "emotional" | "informative"> = [
"catchy",
"emotional",
"informative",
]
const pool: string[] = []
styles.forEach((style) => {
const templates = AI_TITLE_TEMPLATES[style] || []
templates.forEach((tpl) => pool.push(tpl.replace(/\{topic\}/g, topic)))
})
// 洗牌后取前 count 个;不足则轮转补齐
const shuffled = [...pool].sort(() => Math.random() - 0.5)
const out: string[] = []
for (let i = 0; i < count; i++) {
out.push(shuffled[i % shuffled.length] || "")
}
return out
}
function extractTopic(text: string): string {
const keywords = text
.replace(/[,。!?、,.!?]/g, " ")
.split(/\s+/)
.filter(Boolean)
if (keywords.length === 0) return "这个话题"
return keywords.slice(0, 3).join("")
}
const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
const t = useStep4Title(props)
const {
@@ -91,10 +57,8 @@ const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
} = props
const isBatch = previewCount > 1
const [batchAiLoading, setBatchAiLoading] = useState(false)
const [batchAiTopic, setBatchAiTopic] = useState("")
/** 更新单个变体标题;变体0同步写回 titleSettings.title(全局样式面板/草稿/TTS 链路依赖) */
/** 更新单个变体标题;变体0同步写回 titleSettings.title(全局样式面板/草稿保存依赖) */
const updateVariantTitle = (index: number, val: string) => {
if (!previewTitles || !onPreviewTitlesChange) return
const next = [...previewTitles]
@@ -105,43 +69,12 @@ const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
}
}
/** 批量 AI 生成:按主题词生成标题,分别填入 N 个变体 */
const handleBatchAiGenerate = async (onlyEmpty = false) => {
if (!onPreviewTitlesChange || !previewTitles) return
const topic = (batchAiTopic || t.aiTitleInput || "").trim()
if (!topic) {
message.warning("请先输入主题词,例如:萌宠日常、旅行vlog")
return
}
setBatchAiLoading(true)
try {
// 与单视频一致:本地模板模拟 AI 生成(1200ms 体验延迟)
await new Promise((resolve) => setTimeout(resolve, 800))
const picked = buildBatchAiTitles(extractTopic(topic), previewCount)
const next = [...previewTitles]
for (let i = 0; i < previewCount; i++) {
if (onlyEmpty && next[i]?.trim()) continue
if (picked[i]) next[i] = picked[i]
}
onPreviewTitlesChange(next)
if (next[0]) t.updateTitle(next[0])
message.success(`已为 ${previewCount} 个视频生成标题,可单独修改`)
} finally {
setBatchAiLoading(false)
}
}
const titleOptions = useMemo(
() => t.userTitles.map((ut) => ({ label: ut.content, value: ut.content })),
[t.userTitles],
)
return (
<div className="xx-form-section xx-title-sidebar">
<h3>📝 </h3>
{!isBatch ? (
/* ── 单视频:原有 AI 标题 + 输入框(保持不变,零回归 ── */
/* ── 单视频:原有 AI 标题 + 输入框(保持不变) ── */
<>
{t.titleSettings.aiAutoSelect ? (
<>
@@ -211,7 +144,7 @@ const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
t.updateTitle(val || "")
onPreviewTitlesChange?.([val || ""])
}}
options={titleOptions}
options={t.userTitles.map((ut) => ({ label: ut.content, value: ut.content }))}
filterOption={(inputValue, option) => {
const title = (option?.label || option?.value || "") as string
return title.toLowerCase().includes((inputValue || "").toLowerCase())
@@ -222,7 +155,7 @@ const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
)}
</>
) : (
/* ── 批量:AI 批量生成 + N 个独立标题输入框(AutoComplete 支持标题库 ── */
/* ── 批量:N 个独立标题输入框(CSS 浮层实时叠加到对应预览 ── */
<div className="xx-batch-titles">
<div
style={{
@@ -234,52 +167,15 @@ const Step4TitleSettings: React.FC<Step4TitleSettingsProps> = (props) => {
>
//
</div>
{/* 批量 AI 标题 */}
<div className="xx-batch-ai-row">
<Input
placeholder="主题词,如:萌宠日常、旅行vlog"
value={batchAiTopic || t.aiTitleInput}
onChange={(e) => {
setBatchAiTopic(e.target.value)
t.setAiTitleInput(e.target.value)
}}
maxLength={30}
size="small"
style={{ flex: 1 }}
/>
<button
type="button"
className="xx-btn xx-btn-primary xx-btn-sm"
disabled={batchAiLoading}
onClick={() => handleBatchAiGenerate(false)}
>
{batchAiLoading ? <LoadingOutlined /> : "✨"} {previewCount}
</button>
<button
type="button"
className="xx-btn xx-btn-ghost xx-btn-sm"
disabled={batchAiLoading}
onClick={() => handleBatchAiGenerate(true)}
>
</button>
</div>
{Array.from({ length: previewCount }, (_, i) => (
<div className="xx-form-field" key={i}>
<label> {i + 1} </label>
<AutoComplete
<Input
placeholder={`视频 ${i + 1} 的标题…`}
maxLength={50}
style={{ width: "100%" }}
value={previewTitles?.[i] || undefined}
onChange={(val) => updateVariantTitle(i, val || "")}
options={titleOptions}
filterOption={(inputValue, option) => {
const title = (option?.label || option?.value || "") as string
return title.toLowerCase().includes((inputValue || "").toLowerCase())
}}
showCount
value={previewTitles?.[i] || ""}
onChange={(e) => updateVariantTitle(i, e.target.value)}
/>
</div>
))}
+1 -2
View File
@@ -33,8 +33,7 @@ export const STEPS = [
{ key: 2, label: "选择素材" },
{ key: 3, label: "选择配音" },
{ key: 4, label: "选择标题" },
{ key: 5, label: "确认生成" },
{ key: 6, label: "选择封面" },
{ key: 5, label: "选择封面" },
]
/* ── 批量生成限制 ── */
-164
View File
@@ -3278,167 +3278,3 @@
max-height: none;
}
}
/* ============================================================
批量前端 Canvas 预览网格(Issue #1677 修正:纯前端实时预览)
============================================================ */
.xx-canvas-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 16px;
}
.xx-canvas-grid-card {
border: 2px solid var(--border-primary, #e2e8f0);
border-radius: 12px;
overflow: hidden;
background: #000;
transition: border-color 0.2s ease;
min-width: 0;
}
.xx-canvas-grid-card.selected {
border-color: var(--primary-color, #1677ff);
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.15);
}
.xx-canvas-grid-card-bar {
position: relative;
z-index: 2;
display: flex;
align-items: center;
padding: 6px 10px;
background: var(--bg-surface, #fff);
border-bottom: 1px solid var(--border-primary, #e2e8f0);
}
.xx-canvas-grid-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
font-weight: 500;
color: var(--text-primary, #1a1a1a);
cursor: pointer;
user-select: none;
}
.xx-canvas-grid-check input[type="checkbox"] {
width: 15px;
height: 15px;
cursor: pointer;
accent-color: var(--primary-color, #1677ff);
}
/* ============================================================
批量标题:AI 一键生成行(Issue #1677
============================================================ */
.xx-batch-ai-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 10px 12px;
margin-bottom: 12px;
background: var(--bg-secondary, #f7f8fa);
border: 1px dashed var(--border-primary, #d9d9d9);
border-radius: 10px;
}
.xx-batch-ai-row .xx-form-field {
margin: 0;
flex: 1;
min-width: 140px;
}
.xx-batch-titles {
display: flex;
flex-direction: column;
gap: 10px;
}
/* ============================================================
第5步确认生成:批量渲染进度网格(Issue #1677
============================================================ */
.xx-batch-gen-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 16px;
}
.xx-batch-gen-card {
border: 1px solid var(--border-primary, #e2e8f0);
border-radius: 12px;
padding: 14px;
background: var(--bg-surface, #fff);
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.xx-batch-gen-card.status-completed {
border-color: rgba(82, 196, 26, 0.4);
background: rgba(82, 196, 26, 0.04);
}
.xx-batch-gen-card.status-failed {
border-color: rgba(239, 68, 68, 0.4);
background: rgba(239, 68, 68, 0.04);
}
.xx-batch-gen-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.xx-batch-gen-card-title {
font-size: 14px;
font-weight: 600;
color: var(--text-primary, #1a1a1a);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.xx-batch-gen-card-body {
display: flex;
flex-direction: column;
gap: 8px;
}
.xx-batch-gen-card-pct {
font-size: 13px;
color: var(--text-secondary, #666);
text-align: right;
}
.xx-batch-gen-card-done {
font-size: 13px;
color: var(--success-color, #52c41a);
padding: 8px 0;
}
.xx-batch-gen-card-failed {
display: flex;
flex-direction: column;
gap: 8px;
align-items: flex-start;
}
.xx-batch-gen-card-err {
font-size: 13px;
color: var(--error-color, #ef4444);
line-height: 1.5;
word-break: break-word;
}
/* ── 响应式:窄屏批量网格回退单列 ── */
@media (max-width: 960px) {
.xx-canvas-grid,
.xx-batch-gen-grid {
grid-template-columns: 1fr;
}
}
@@ -1,28 +1,14 @@
import { useRef, useCallback, useState } from "react"
import { useRef, useCallback } from "react"
import { message } from "antd"
import axios from "axios"
import { getGenerationTask, retryTask as retryGenerationTaskApi } from "@/api/tasks/tasks"
import { getGenerationTask } from "@/api/tasks/tasks"
import { getGenerationTaskResults } from "@/api/template-editor"
import { safeExtractError } from "./errorUtils"
/** 批量生成时单个任务的实时状态(Issue #1677 第5步确认生成页) */
export interface BatchTaskState {
taskId: string
/** 变体序号(0-based,与标题/封面数组对齐) */
variantIndex: number
status: "running" | "completed" | "failed"
progress: number
error: string | null
/** 完成后的成片视频 */
videos: unknown[]
}
interface UseGenerationPollingOptions {
onProgress: (progress: number) => void
onComplete: (videos: unknown[]) => void
onFailed: (errorMsg: string) => void
/** 批量:单任务状态变化(第5步逐卡片展示) */
onBatchTaskUpdate?: (taskId: string, patch: Partial<BatchTaskState>) => void
}
/** 最大连续错误次数(仅对可重试错误),超过后终止轮询 */
@@ -31,25 +17,20 @@ const MAX_RETRYABLE_ERRORS = 10
const MAX_RESULTS_RETRIES = 3
/**
* 生成状态轮询 Hookv4 — 批量任务独立状态 + 单任务重试
* 生成状态轮询 Hookv3支持批量任务)
*
* startPolling(taskId) 轮询单个任务;
* startPollingBatch(tasks) 并行轮询 N 个任务
* - 每个任务独立进度/状态/失败,通过 onBatchTaskUpdate 实时回传
* - 全部成功才 onComplete(聚合视频按变体顺序);任一失败不影响其他任务继续
* - retryTask(taskId) 单独重试失败任务(重新轮询,后端任务仍在跑则直接接续)
* startPollingBatch(taskIds) 并行轮询 N 个任务,全部完成后聚合结果,
* 任一任务失败即整体失败(其余任务仍在后端继续,不影响)。
* 进度为所有任务平均值。
*/
export function useGenerationPolling({
onProgress,
onComplete,
onFailed,
onBatchTaskUpdate,
}: UseGenerationPollingOptions) {
const progressTimer = useRef<ReturnType<typeof setTimeout>[]>([])
const cancelledRef = useRef(false)
/** 批量任务上下文:taskId → 变体序号 */
const batchContextRef = useRef<Map<string, number>>(new Map())
const [, forceTick] = useState(0)
const clearTimer = useCallback(() => {
cancelledRef.current = true
@@ -85,21 +66,9 @@ export function useGenerationPolling({
return safeExtractError(msg)
}
/**
* 轮询单个任务。
* - isBatch=true:状态变化通过 onBatchTaskUpdate 回传,不触发整体 onProgress/onComplete
* - resolve(videos) 成功;reject(Error) 失败
*/
/** 轮询单个任务,resolve 该任务的结果视频数组;失败时 reject(new Error(msg)) */
const pollSingleTask = useCallback(
(
taskId: string,
runId: number,
callbacks?: {
onTaskProgress?: (pct: number) => void
onTaskCompleted?: (videos: unknown[]) => void
onTaskFailed?: (msg: string) => void
},
): Promise<unknown[]> => {
(taskId: string, runId: number, onTaskProgress?: (pct: number) => void): Promise<unknown[]> => {
return new Promise((resolve, reject) => {
let consecutiveErrors = 0
let done = false
@@ -116,12 +85,9 @@ export function useGenerationPolling({
const videos = await fetchResultsWithRetry(taskId)
if (cancelledRef.current) return
if (videos === null) {
const msg = "视频已生成,但获取结果列表失败,请稍后在任务列表查看"
callbacks?.onTaskFailed?.(msg)
reject(new Error(msg))
reject(new Error("视频已生成,但获取结果列表失败,请稍后在任务列表查看"))
return
}
callbacks?.onTaskCompleted?.(videos)
resolve(videos)
return
}
@@ -132,15 +98,14 @@ export function useGenerationPolling({
task.error_info?.error_message ||
task.error_message ||
(task.status === "cancelled" ? "任务已取消" : "视频生成失败,请联系管理员或重试")
const msg = safeExtractError(rawMsg)
callbacks?.onTaskFailed?.(msg)
reject(new Error(msg))
reject(new Error(safeExtractError(rawMsg)))
return
}
const pct = Math.max(0, Math.min(99, Math.round(Number(task.progress) || 0)))
callbacks?.onTaskProgress?.(pct)
if (!callbacks && runId === 0) {
if (onTaskProgress) {
onTaskProgress(pct)
} else if (runId === 0) {
onProgress(pct)
}
const timer = setTimeout(poll, 2000)
@@ -151,17 +116,13 @@ export function useGenerationPolling({
const status = axios.isAxiosError(pollErr) ? pollErr.response?.status : undefined
if (status && status >= 400 && status < 500) {
done = true
const msg = extractErrorMessage(pollErr, status)
callbacks?.onTaskFailed?.(msg)
reject(new Error(msg))
reject(new Error(extractErrorMessage(pollErr, status)))
return
}
consecutiveErrors += 1
if (consecutiveErrors >= MAX_RETRYABLE_ERRORS) {
done = true
const msg = "任务状态查询连续失败,请稍后在任务列表查看结果"
callbacks?.onTaskFailed?.(msg)
reject(new Error(msg))
reject(new Error("任务状态查询连续失败,请稍后在任务列表查看结果"))
return
}
const timer = setTimeout(poll, 3000)
@@ -176,12 +137,12 @@ export function useGenerationPolling({
[onProgress, fetchResultsWithRetry],
)
/** 单任务轮询(单视频,兼容旧调用) */
/** 单任务轮询(兼容旧调用) */
const startPolling = useCallback(
(taskId: string) => {
cancelledRef.current = false
batchContextRef.current.clear()
pollSingleTask(taskId, 0)
const runId = 0
pollSingleTask(taskId, runId)
.then((videos) => {
if (cancelledRef.current) return
onProgress(100)
@@ -198,114 +159,48 @@ export function useGenerationPolling({
[pollSingleTask, onProgress, onComplete, onFailed],
)
/**
* 批量多任务轮询:
* - 每个任务独立进度/状态回传 onBatchTaskUpdate
* * 全部完成后按变体顺序聚合视频 onComplete
* - 部分失败:整体不 onFailed(第5步逐卡片展示失败+重试按钮);全部失败才 onFailed
*/
/** 批量多任务轮询:全部完成后聚合结果;任一失败即整体失败 */
const startPollingBatch = useCallback(
(tasks: { taskId: string; variantIndex: number }[]) => {
(taskIds: string[]) => {
cancelledRef.current = false
const runId = Date.now()
const progressMap = new Map<string, number>()
const resultMap = new Map<string, unknown[]>()
const failureMap = new Map<string, string>()
batchContextRef.current = new Map(tasks.map((t) => [t.taskId, t.variantIndex]))
const reportAggregateProgress = () => {
if (cancelledRef.current) return
const values = tasks.map((t) => progressMap.get(t.taskId) ?? 0)
const values = taskIds.map((id) => progressMap.get(id) ?? 0)
const avg = Math.round(values.reduce((a, b) => a + b, 0) / Math.max(values.length, 1))
onProgress(Math.min(avg, 99))
}
const checkAllSettled = () => {
if (resultMap.size + failureMap.size < tasks.length) return
if (resultMap.size === tasks.length) {
onProgress(100)
const ordered = tasks.map((t) => resultMap.get(t.taskId) || []).flat()
onComplete(ordered)
message.success(`全部 ${tasks.length} 个视频生成完成!`)
} else if (resultMap.size > 0) {
// 部分失败:成功的视频聚合进成片列表(可进封面),失败卡片带重试按钮
onProgress(100)
const ordered = tasks
.filter((t) => resultMap.has(t.taskId))
.map((t) => resultMap.get(t.taskId) || [])
.flat()
onComplete(ordered)
message.warning(
`${failureMap.size} 个视频生成失败,可点击卡片上的「重试此视频」,成功的视频可先进入下一步`,
)
} else {
const firstMsg = failureMap.get(tasks[0].taskId) || "全部视频生成失败"
onFailed(firstMsg)
}
}
const tasks = taskIds.map((taskId) =>
pollSingleTask(taskId, runId, (pct) => {
progressMap.set(taskId, pct)
reportAggregateProgress()
}).then((videos) => {
progressMap.set(taskId, 100)
reportAggregateProgress()
return videos
}),
)
tasks.forEach(({ taskId, variantIndex }) => {
onBatchTaskUpdate?.(taskId, {
taskId,
variantIndex,
status: "running",
progress: 0,
error: null,
videos: [],
Promise.all(tasks)
.then((results) => {
if (cancelledRef.current) return
onProgress(100)
const allVideos = results.flat()
onComplete(allVideos)
message.success(`全部 ${taskIds.length} 个视频生成完成!`)
})
pollSingleTask(taskId, runId, {
onTaskProgress: (pct) => {
progressMap.set(taskId, pct)
onBatchTaskUpdate?.(taskId, { status: "running", progress: pct })
reportAggregateProgress()
},
onTaskCompleted: (videos) => {
progressMap.set(taskId, 100)
resultMap.set(taskId, videos)
onBatchTaskUpdate?.(taskId, { status: "completed", progress: 100, videos })
reportAggregateProgress()
checkAllSettled()
},
onTaskFailed: (msg) => {
failureMap.set(taskId, msg)
onBatchTaskUpdate?.(taskId, { status: "failed", error: msg })
checkAllSettled()
},
}).catch(() => {
// 失败已在 onTaskFailed 处理,这里吞掉 Promise rejection
.catch((err: Error) => {
if (cancelledRef.current) return
console.error("[批量生成失败]", err.message)
onFailed(err.message)
message.error(err.message)
})
})
},
[pollSingleTask, onProgress, onComplete, onFailed, onBatchTaskUpdate],
[pollSingleTask, onProgress, onComplete, onFailed],
)
/** 单独重试失败任务(第5步卡片「重试此视频」):先调后端重试接口,再轮询 */
const retryTask = useCallback(
async (taskId: string) => {
if (cancelledRef.current) cancelledRef.current = false
const variantIndex = batchContextRef.current.get(taskId) ?? 0
onBatchTaskUpdate?.(taskId, { status: "running", progress: 0, error: null, videos: [] })
try {
await retryGenerationTaskApi(taskId)
} catch (err) {
// 后端不支持重试或任务不可重试:直接重新轮询(任务可能已被自动恢复)
console.warn("[重试任务接口调用失败,改为直接轮询]", err)
}
pollSingleTask(taskId, Date.now(), {
onTaskProgress: (pct) => onBatchTaskUpdate?.(taskId, { status: "running", progress: pct }),
onTaskCompleted: (videos) => {
onBatchTaskUpdate?.(taskId, { status: "completed", progress: 100, videos })
message.success(`视频 ${variantIndex + 1} 重试成功`)
},
onTaskFailed: (msg) => onBatchTaskUpdate?.(taskId, { status: "failed", error: msg }),
}).catch(() => {
/* 失败已在回调处理 */
})
forceTick((n) => n + 1)
return variantIndex
},
[pollSingleTask, onBatchTaskUpdate],
)
return { startPolling, startPollingBatch, retryTask, clearTimer }
return { startPolling, startPollingBatch, clearTimer }
}
@@ -0,0 +1,285 @@
/**
* 批量服务器预览 Hook(Issue #1677 多视频批量生成)
*
* 核心职责:
* 1. 调用 POST /generation/previewpreview_count=N)一次创建 N 个独立变体任务
* 2. 对每个变体 task_id 分别轮询 GET /generation/preview/{task_id}
* 3. 返回每个变体的状态/进度/视频URL,供网格播放器展示
*
* N=1 时不启用(走前端 Canvas 实时预览,零回归);
* N>1 时进入标题页自动触发;素材/配音等配置变化后重新触发。
*/
import { useState, useCallback, useRef, useEffect } from "react"
import { createPreview, getPreviewStatus } from "@/api/generation/preview"
import type { CreatePreviewRequest } from "@/api/generation/types"
export type VariantPreviewStatus = "loading" | "ready" | "failed"
export interface VariantPreview {
/** 变体序号(0-based */
index: number
taskId: string
status: VariantPreviewStatus
progress: number
videoUrl: string | null
error: string | null
}
interface UseBatchPreviewOptions {
/** 是否启用(仅 previewCount>1 且在标题页时启用) */
enabled: boolean
/** 构建预览请求参数(每次触发时调用,获取最新配置) */
buildRequest: () => CreatePreviewRequest
/** 批量预览任务创建成功回调(回传变体 taskId 列表与 source_edit_plan_id */
onPreviewTasksCreated?: (taskIds: string[], sourceEditPlanId?: string) => void
}
interface UseBatchPreviewReturn {
variants: VariantPreview[]
/** 整体状态:loading=任一进行中,ready=全部完成,failed=有失败 */
status: "idle" | "loading" | "ready" | "partial_failed" | "failed"
/** 总进度 0-100(各变体平均值) */
progress: number
/** 失败的变体数量 */
failedCount: number
/** 手动重新触发 */
trigger: () => void
}
const POLL_INTERVAL = 2000
const POLL_TIMEOUT = 180_000
const MAX_NETWORK_RETRIES = 2
/**
* 对配置参数做指纹,用于检测配置是否变化(标题文字/样式变化不触发重渲染,仅CSS浮层叠加)
*/
function buildFingerprint(req: CreatePreviewRequest): string {
// 不含 titles/title_config:标题文字与样式由 CSS 浮层实时叠加,变化不触发重渲染
return JSON.stringify({
t: req.template_id,
a: [...(req.asset_ids || [])].sort(),
r: req.video_ratio,
v: req.voice_library_id,
vs: req.voice_library_ids,
pc: req.preview_count,
b: req.bgm_config,
})
}
export function useBatchPreview({
enabled,
buildRequest,
onPreviewTasksCreated,
}: UseBatchPreviewOptions): UseBatchPreviewReturn {
const [variants, setVariants] = useState<VariantPreview[]>([])
const [status, setStatus] = useState<"idle" | "loading" | "ready" | "partial_failed" | "failed">(
"idle",
)
const requestSeqRef = useRef(0)
const pollTimersRef = useRef<ReturnType<typeof setTimeout>[]>([])
const timeoutTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const mountedRef = useRef(true)
const buildRequestRef = useRef(buildRequest)
buildRequestRef.current = buildRequest
const onCreatedRef = useRef(onPreviewTasksCreated)
onCreatedRef.current = onPreviewTasksCreated
const clearTimers = useCallback(() => {
pollTimersRef.current.forEach((t) => clearTimeout(t))
pollTimersRef.current = []
if (timeoutTimerRef.current) {
clearTimeout(timeoutTimerRef.current)
timeoutTimerRef.current = null
}
}, [])
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
clearTimers()
}
}, [clearTimers])
/** 更新单个变体状态 */
const patchVariant = useCallback((taskId: string, patch: Partial<VariantPreview>) => {
setVariants((prev) => prev.map((v) => (v.taskId === taskId ? { ...v, ...patch } : v)))
}, [])
/** 轮询单个变体任务 */
const pollVariant = useCallback(
async (taskId: string, seq: number, retries = 0) => {
if (seq !== requestSeqRef.current || !mountedRef.current) return
try {
const st = await getPreviewStatus(taskId)
if (seq !== requestSeqRef.current || !mountedRef.current) return
if (st.status === "completed" && st.video_url) {
patchVariant(taskId, {
status: "ready",
videoUrl: st.video_url,
progress: 100,
error: null,
})
return
}
if (st.status === "failed" || st.status === "cancelled") {
patchVariant(taskId, {
status: "failed",
error:
st.status === "cancelled" ? "预览任务已取消" : st.error_message || "预览渲染失败",
})
return
}
if (typeof st.progress === "number") {
patchVariant(taskId, { progress: Math.round(st.progress) })
}
const timer = setTimeout(() => pollVariant(taskId, seq), POLL_INTERVAL)
pollTimersRef.current.push(timer)
} catch (err) {
if (seq !== requestSeqRef.current || !mountedRef.current) return
if (retries < MAX_NETWORK_RETRIES) {
console.warn(`[BatchPreview] 变体 ${taskId} 轮询网络错误,第 ${retries + 1} 次重试`, err)
const timer = setTimeout(() => pollVariant(taskId, seq, retries + 1), POLL_INTERVAL * 2)
pollTimersRef.current.push(timer)
} else {
patchVariant(taskId, { status: "failed", error: "网络错误,无法获取预览状态" })
}
}
},
[patchVariant],
)
/** 创建批量预览任务并开始轮询 */
const trigger = useCallback(() => {
if (!enabled) return
const request = buildRequestRef.current()
if (!request.template_id || !request.asset_ids?.length) return
const count = request.preview_count && request.preview_count > 1 ? request.preview_count : 0
if (!count) return
clearTimers()
const seq = ++requestSeqRef.current
setStatus("loading")
setVariants(
Array.from({ length: count }, (_, i) => ({
index: i,
taskId: "",
status: "loading" as const,
progress: 0,
videoUrl: null,
error: null,
})),
)
createPreview(request)
.then((resp) => {
if (seq !== requestSeqRef.current || !mountedRef.current) return
const items = resp.items || []
const taskIds = items.map((it) => it.task_id).filter(Boolean)
if (taskIds.length === 0) {
setStatus("failed")
setVariants((prev) =>
prev.map((v) => ({ ...v, status: "failed", error: "未创建预览任务" })),
)
return
}
onCreatedRef.current?.(taskIds, resp.source_edit_plan_id)
// 用返回的 task_id 填充变体(按 variant_index 对齐)
setVariants((prev) =>
prev.map((v) => {
const item = items.find((it) => it.variant_index === v.index) || items[v.index]
return item ? { ...v, taskId: item.task_id } : v
}),
)
// 超时保护
timeoutTimerRef.current = setTimeout(() => {
if (seq !== requestSeqRef.current || !mountedRef.current) return
setVariants((prev) =>
prev.map((v) =>
v.status === "loading"
? { ...v, status: "failed", error: "预览渲染超时,请重试" }
: v,
),
)
}, POLL_TIMEOUT)
// 分别轮询每个变体
items.forEach((item) => {
if (item.task_id) pollVariant(item.task_id, seq)
})
})
.catch((err: unknown) => {
if (seq !== requestSeqRef.current || !mountedRef.current) return
console.error("[BatchPreview] 创建批量预览失败:", err)
const errData = (err as { response?: { data?: { detail?: string; message?: string } } })
?.response?.data
setStatus("failed")
setVariants((prev) =>
prev.map((v) => ({
...v,
status: "failed",
error: errData?.detail || errData?.message || "预览任务创建失败,请重试",
})),
)
})
}, [enabled, clearTimers, pollVariant])
/* ── 自动触发 + 配置变更检测 ── */
const request = enabled ? buildRequest() : null
const currentFingerprint = request
? request.template_id && request.asset_ids?.length && (request.preview_count || 1) > 1
? buildFingerprint(request)
: ""
: ""
const didInitRef = useRef(false)
useEffect(() => {
if (!enabled || !currentFingerprint) {
didInitRef.current = false
requestSeqRef.current += 1
clearTimers()
setStatus("idle")
setVariants([])
return
}
if (!didInitRef.current) {
didInitRef.current = true
trigger()
}
}, [enabled, currentFingerprint, trigger, clearTimers])
// 配置变更(素材/配音/数量)→ 重新渲染;标题文字变化不触发(CSS浮层实时叠加)
const prevFingerprintRef = useRef(currentFingerprint)
useEffect(() => {
if (!enabled || !currentFingerprint) return
const prev = prevFingerprintRef.current
prevFingerprintRef.current = currentFingerprint
if (!prev || prev === currentFingerprint) return
trigger()
}, [enabled, currentFingerprint, trigger])
/* ── 派生状态 ── */
const progress =
variants.length > 0
? Math.round(variants.reduce((sum, v) => sum + v.progress, 0) / variants.length)
: 0
const failedCount = variants.filter((v) => v.status === "failed").length
const readyCount = variants.filter((v) => v.status === "ready").length
useEffect(() => {
if (status !== "loading" || variants.length === 0) return
if (readyCount === variants.length) {
setStatus("ready")
} else if (readyCount + failedCount === variants.length && failedCount > 0) {
setStatus(failedCount === variants.length ? "failed" : "partial_failed")
}
}, [variants, status, readyCount, failedCount])
return { variants, status, progress, failedCount, trigger }
}
export default useBatchPreview
@@ -2,13 +2,13 @@
* 视频生成 Hook
* 封装视频生成的核心逻辑、状态管理、轮询等
*/
import { useState, useCallback, useEffect } from "react"
import { useState, useCallback } from "react"
import { message } from "antd"
import { type GeneratedVideo, getEditPlanClips, createClipsFromAssets } from "@/api/template-editor"
import { createGenerationTask } from "@/api/tasks/tasks"
import type { UseGenerateVideoProps } from "./generate-video/types"
import { getGenerationPhase } from "./generate-video/phase"
import { useGenerationPolling, type BatchTaskState } from "./generate-video/useGenerationPolling"
import { useGenerationPolling } from "./generate-video/useGenerationPolling"
import { validateGenerateInputs } from "./generate-video/buildPayload"
import { calculateResolution } from "../utils/calculateResolution"
import { extractBackendError, translateError } from "./generate-video/errorUtils"
@@ -22,32 +22,6 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
const [generated, setGenerated] = useState(false)
const [generateError, setGenerateError] = useState<string | null>(null)
const [generatedVideos, setGeneratedVideos] = useState<GeneratedVideo[]>([])
/** 批量模式:每个正式生成任务的独立状态(第5步逐卡片展示) */
const [batchTasks, setBatchTasks] = useState<BatchTaskState[]>([])
const handleBatchTaskUpdate = useCallback((taskId: string, patch: Partial<BatchTaskState>) => {
setBatchTasks((prev) => {
const list = prev || []
const idx = list.findIndex((t) => t.taskId === taskId)
if (idx === -1) {
return [
...list,
{
taskId,
variantIndex: patch.variantIndex ?? 0,
status: "running",
progress: 0,
error: null,
videos: [],
...patch,
},
]
}
const next = [...list]
next[idx] = { ...next[idx], ...patch }
return next
})
}, [])
const handleProgress = useCallback((p: number) => setProgress(p), [])
const handleComplete = useCallback(
@@ -55,19 +29,6 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
setGenerating(false)
setGenerated(true)
setGeneratedVideos(videos as GeneratedVideo[])
// 批量:成功任务的 videos 已通过 onBatchTaskUpdate 写入,这里同步兜底
setBatchTasks((prev) =>
(prev || []).map((t) =>
t.status === "completed" && t.videos.length === 0
? {
...t,
videos: (videos as GeneratedVideo[]).filter(
(v) => v.generation_task_id === t.taskId,
),
}
: t,
),
)
onGenerationSuccess?.()
},
[onGenerationSuccess],
@@ -77,30 +38,10 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
setGenerateError(errorMsg)
}, [])
/* 批量:任务状态变化时聚合已完成成片(含失败重试成功后补入),
按变体索引排序,供步骤6封面按勾选顺序逐个取视频 */
useEffect(() => {
if (batchTasks.length === 0) return
const byVariant = new Map<number, GeneratedVideo>()
batchTasks.forEach((t) => {
if (t.status === "completed" && t.videos && t.videos.length > 0) {
byVariant.set(t.variantIndex, t.videos[0] as GeneratedVideo)
}
})
const ordered = [...byVariant.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => v)
setGeneratedVideos((prev) => {
if (prev.length === ordered.length && prev.every((v, i) => v.id === ordered[i].id)) {
return prev
}
return ordered
})
}, [batchTasks])
const { startPolling, startPollingBatch, retryTask, clearTimer } = useGenerationPolling({
const { startPolling, startPollingBatch, clearTimer } = useGenerationPolling({
onProgress: handleProgress,
onComplete: handleComplete,
onFailed: handleFailed,
onBatchTaskUpdate: handleBatchTaskUpdate,
})
/* ── 生成视频 ──
@@ -116,7 +57,6 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
setProgress(0)
setGenerated(false)
setGenerateError(null)
setBatchTasks([])
clearTimer()
try {
@@ -230,8 +170,7 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
throw new Error("创建任务成功但未返回任务 ID,请稍后在任务列表查看")
}
if (taskIds.length > 1) {
// 批量:任务按创建顺序与勾选变体一一对应(后端按 count 顺序创建)
startPollingBatch(taskIds.map((taskId, i) => ({ taskId, variantIndex: indexes[i] ?? i })))
startPollingBatch(taskIds)
} else {
startPolling(taskIds[0])
}
@@ -257,14 +196,6 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
generate()
}, [generate])
/** 第5步:单独重试某个失败任务 */
const retryBatchTask = useCallback(
(taskId: string) => {
retryTask(taskId)
},
[retryTask],
)
const dismissError = useCallback(() => {
setGenerateError(null)
}, [])
@@ -309,8 +240,6 @@ export function useGenerateVideo(props: UseGenerateVideoProps) {
generatedVideos,
generate,
retry,
retryBatchTask,
batchTasks,
dismissError,
download,
share,
@@ -1,11 +1,6 @@
/**
* GeneratePage 步骤导航(Issue #1677 修正:固定 6 步,单视频与批量一致
* 步骤:模板(1) → 素材(2) → 配音(3) → 标题(4) → 确认生成(5) → 封面(6)
*
* - 步骤4底部按钮是「确认生成视频/确认生成 N 个视频」(由 GenerateStepActions 调
* onConfirmGenerate),创建成功后跳转步骤5;本 hook 的 goNext 只负责 1→2→3→4
* 和 5→6 的「下一步」。
* - 步骤5(确认生成进度页):渲染全部完成(generated)后「下一步」解锁进封面。
* GeneratePage 步骤导航(Issue #1677 改造后 5 步
* 步骤:模板(1) → 素材(2) → 配音(3) → 标题+预览+确认生成(4) → 封面(5)
*/
import { message } from "antd"
import type { TitleSettings } from "../types"
@@ -18,8 +13,14 @@ export interface UseStepNavigationOptions {
selectedMaterials: string[]
smartSelectedIds: string[]
titleSettings: TitleSettings
/** 是否已完成视频生成(步骤5全部渲染完成后才能进入封面 */
/** 预览是否已就绪(单视频=前端预览素材已加载;批量=服务器预览全部完成 */
previewReady: boolean
/** 是否已完成视频生成(步骤4确认生成后才能进入封面) */
generated: boolean
/** 批量模式下每个变体的标题 */
previewTitles: string[]
/** 批量模式勾选的变体数 */
selectedCount: number
/** Step1 点下一步时弹出数量选择弹窗 */
onOpenCountModal: () => void
}
@@ -37,7 +38,10 @@ export const useStepNavigation = (options: UseStepNavigationOptions): UseStepNav
materialMode,
selectedMaterials,
smartSelectedIds,
previewReady,
generated,
previewTitles,
selectedCount,
onOpenCountModal,
} = options
@@ -59,14 +63,27 @@ export const useStepNavigation = (options: UseStepNavigationOptions): UseStepNav
message.warning("请先进行智能匹配并选择素材")
return
}
// 步骤5(确认生成):全部渲染完成后才能下一步进封面
if (currentStep === 5) {
// Step4(标题+预览+确认生成):标题必填 + 预览必须已加载
if (currentStep === 4) {
const allTitlesFilled = previewTitles.every((t) => t && t.trim())
if (!allTitlesFilled) {
message.warning("请为每个视频输入标题")
return
}
if (selectedCount === 0) {
message.warning("请至少勾选一个视频")
return
}
if (!previewReady) {
message.warning("预览视频正在加载,请稍候")
return
}
if (!generated) {
message.warning("视频还在渲染中,请等待生成完成")
message.warning("请先点击「确认生成视频」完成渲染")
return
}
}
if (currentStep < 6) {
if (currentStep < 5) {
setCurrentStep((s) => s + 1)
}
}
@@ -20,8 +20,7 @@ import "@/pages/generate/components/Step2MaterialSelect"
import "@/pages/generate/components/Step4TitleSettings"
import "@/pages/generate/components/Step5VoiceSelect"
import "@/pages/generate/components/Step3VoiceWithMode"
import "@/pages/generate/components/CanvasPreviewGrid"
import "@/pages/generate/components/BatchGenerationGrid"
import "@/pages/generate/components/ServerPreviewGrid"
import "@/pages/generate/components/PreviewCountModal"
import "@/pages/generate/components/PreviewVideoPanel"
import "@/pages/generate/components/GenerateResultPanel"
@@ -49,6 +48,7 @@ describe("GeneratePage module smoke test", () => {
})
})
import "@/pages/generate/hooks/useGenerateVideo"
import "@/pages/generate/hooks/useBatchPreview"
import "@/pages/generate/hooks/useBatchCovers"
import "@/pages/generate/hooks/usePreviewAssets"
import "@/pages/generate/hooks/useSegmentScheduler"
+249 -461
View File
@@ -31,65 +31,25 @@ SCENE_CHANGE_THRESHOLD = 30 # 灰度差异阈值
MIN_KEYFRAME_INTERVAL_SEC = 1.0 # 最小关键帧间隔(秒)
MAX_KEYFRAMES = 30 # 最大关键帧数
MIN_KEYFRAMES = 5 # 最小关键帧数
FINGERPRINT_SAMPLE_INTERVAL_SEC = 1.0 # 指纹采样间隔(秒):密集均匀采样,保证两视频时序可对齐
FINGERPRINT_MAX_SAMPLES = 30 # 长视频采样数上限(超过后采样间隔自动放宽)
LONG_VIDEO_SEGMENT_SEC = 30 # 长视频每段秒数
LONG_VIDEO_DURATION_THRESHOLD_SEC = 180 # 3 分钟阈值
MIN_FRAMES_PER_SEGMENT = 2 # 长视频每段最少帧数
# ── 滑动窗口匹配常量Issue #1702 二次校准) ─────────────────────
# 阈值经 staging 真实数据两轮回归校准(worker 容器内离线实验):
# 第一轮(2026-09-05):同源对 <=12 命中 4/11,异源最小距离 24 → 定 12;
# 第二轮(2026-09-05,证据视频 B->A 仍漏检):扩大样本到该用户全部
# 15 个真实成片(13 个异源候选)实测:
# - 同源成片对(A 20s / B、C 各 11.75s1s 密集采样):
# B->A 中位数距离 14<=16 命中 8/11=0.73C->A 8/11=0.73
# - 异源成片对(13 个真实视频):每帧全局最近邻最小距离 18,
# <=16 命中帧数全部为 0(最近邻 18 仅个别帧,中位数 22~28)
# 12 漏掉同源降重对(降重滤镜/字幕/画面扰动把距离从 ~8 推到 14~16);
# 16 对同源命中 0.73+ 且与异源分布(最近邻 >=18)仍有 >=2bit 安全裕度,
# 异源 <=16 命中 0 帧,无误报空间。
PHASH_THRESHOLD = 16
SEGMENT_MATCH_THRESHOLD = PHASH_THRESHOLD # 片段匹配阈值与帧匹配统一(#1702:阈值常量统一来源)
MIN_CONSECUTIVE_MATCHES = 5 # 连续匹配默认门槛;短视频自适应 min(5, max(2, 分片数//2))
# ── 滑动窗口匹配常量 ────────────────────────────────────────────
SEGMENT_MATCH_THRESHOLD = 8 # 帧匹配汉明距离阈值
MIN_CONSECUTIVE_MATCHES = 5 # 最少连续匹配帧数
MAX_GAP = 2 # 允许的最大间隙帧数
NEIGHBOR_WINDOW = 1 # 分片时序对齐:允许 ±1 邻接偏移(1s 密集采样下即 ±1s,缓解切点不一致)
# ── 融合判定常量 ────────────────────────────────────────────────
PHASH_WEIGHT = 0.7 # pHash 权重
HISTOGRAM_WEIGHT = 0.3 # 直方图权重
MATCH_RATIO_THRESHOLD = 0.7 # 全片重复(is_duplicate至少 70% 帧匹配
PARTIAL_COVERAGE_THRESHOLD = 0.5 # 局部复用覆盖率 >=50% 也判全片重复
MATCH_RATIO_THRESHOLD = 0.7 # 至少 70% 帧匹配
DUPLICATE_THRESHOLD = 0.70 # 融合后相似度阈值
# ── 降重裁剪规避常量(Issue #1702) ─────────────────────────────
# 成片强制 2-5% random_edge_crop 降重只服务外部平台;自查重指纹取中心 90%
# 区域,使两次不同裁剪的同源画面 pHash 距离回到同分布。
FINGERPRINT_CENTER_CROP_RATIO = 0.90
# ── 感知哈希 & 颜色直方图工具函数 ────────────────────────────────
def center_crop_frame(image: np.ndarray, ratio: float = FINGERPRINT_CENTER_CROP_RATIO) -> np.ndarray:
"""取画面中心 ratio 比例区域(裁除四边边缘)。
查重指纹用:random_edge_crop 降重(2-5% 四边随机裁剪)会让同源画面 pHash
位翻转 12-16,污染自查重(Issue #1702)。算 pHash/颜色直方图前先居中裁除
边缘 10%,两次不同裁剪的同源画面中心区域基本重合,指纹不再被降重污染。
降重只服务外部平台,不影响内部查重。
"""
if image is None or image.size == 0:
return image
h, w = image.shape[:2]
ch, cw = int(h * ratio), int(w * ratio)
if ch <= 0 or cw <= 0 or (ch >= h and cw >= w):
return image
y0 = (h - ch) // 2
x0 = (w - cw) // 2
return image[y0 : y0 + ch, x0 : x0 + cw]
def compute_phash(image: np.ndarray, hash_size: int = 8) -> str:
"""计算图像的感知哈希(pHash),基于 DCT(离散余弦变换)。
@@ -141,17 +101,11 @@ def hamming_distance(hash1: str, hash2: str) -> int:
def compute_color_histogram(image: np.ndarray, bins: int = 32) -> list[float]:
"""Compute BGR color histogram for an image.
Issue #1702: 每个通道独立做 NORM_L1 归一化(通道内 Σ=1,是概率分布),
三通道拼接存储。Bhattacharyya 系数对拼接向量直接 Σ√(a*b) 会得到
3 通道之和(范围 [0,3],实测 ~14.9 是旧 L2 归一化的错误结果),
消费方 _bhattacharyya_coefficient 按通道数平均归一到 [0,1]。
"""
"""Compute color histogram for an image."""
hist = []
for i in range(3):
h = cv2.calcHist([image], [i], None, [bins], [0, 256])
h = cv2.normalize(h, h, norm_type=cv2.NORM_L1).flatten()
h = cv2.normalize(h, h).flatten()
hist.extend(h)
return hist
@@ -256,30 +210,6 @@ def detect_keyframe_timestamps(
return keyframe_times
def sample_fingerprint_timestamps(
duration: float,
*,
interval_sec: float = FINGERPRINT_SAMPLE_INTERVAL_SEC,
max_samples: int = FINGERPRINT_MAX_SAMPLES,
) -> list[float]:
"""指纹采样时间戳:固定间隔密集均匀采样(Issue #1702)。
动态场景检测抽帧(#1659)在两个同源视频上会各自取到不同时刻,切点/取帧
错位让对齐帧的 pHash 距离都很大(实测同源对最小距离 12 且配对时序错乱)。
改为固定 1s 间隔均匀采样后,复用片段的帧时刻天然对齐,配合 ±1 邻接窗口
即可检出同源/局部复用。长视频(>max_samples*interval)自动放宽间隔到
duration/max_samples,保证分片数有上限。
"""
if duration <= 0:
return []
step = interval_sec
n_uniform = int(duration / step)
if n_uniform > max_samples:
step = duration / max_samples
count = max(1, int(duration / step))
return [step * (i + 0.5) for i in range(count)]
# ── 数据类 ──────────────────────────────────────────────────────
@@ -367,33 +297,23 @@ def find_duplicate_segments(
target_chunks: list,
*,
match_threshold: int = SEGMENT_MATCH_THRESHOLD,
min_consecutive: Optional[int] = None,
min_consecutive: int = MIN_CONSECUTIVE_MATCHES,
max_gap: int = MAX_GAP,
neighbor_window: int = NEIGHBOR_WINDOW,
) -> list[DuplicateSegment]:
"""滑动窗口时序匹配:找出两组分片之间的重复片段Issue #1702 重构)
"""滑动窗口时序匹配:找出两组分片之间的重复片段。
算法:
1. 构建 query×target 全量汉明距离矩阵;每个 query chunk 保留所有
距离 <= match_threshold 的候选 target 分片(与帧匹配判定同一阈值)。
2. 时序一致贪心对齐:沿 query 时序推进,run 内优先选择与上一匹配帧
目标序号连贯(|delta| <= neighbor_window+1,允许 ±1 邻接/时序偏移
对齐——1s 密集采样下相邻帧 pHash 接近,最近邻在目标相邻帧间
正/反向跳变均属正常,缓解场景切割切点、取帧错位、局部倒退)的
候选;同距时偏好小索引(最早对齐位置)。
3. 连贯匹配中允许 <= max_gap 帧间隙桥接;断裂后另起新 run——天然
支持局部片段复用(复用片段可出现在任意时序位置,各成独立片段)。
4. 连续匹配帧数 >= min_consecutive 的 run 报为重复片段。短视频自适应:
min_consecutive = min(5, max(2, len(query_chunks)//2))n=1 时
不形成片段,由调用方匹配帧回退兜底。
1. 对每个 query chunk,找到 target 汉明距离最小的 chunk
2. 距离 <= match_threshold 视为匹配
3. 找连续匹配的 run(允许 max_gap 帧间隙)
4. 连续匹配数 >= min_consecutive 的 run 报告为重复片段
Args:
query_chunks: 查询视频的分片列表(FingerprintChunk 或 dict
target_chunks: 目标视频的分片列表
match_threshold: 汉明距离匹配阈值(统一常量 PHASH_THRESHOLD
min_consecutive: 最少连续匹配帧数None 时按短视频自适应
match_threshold: 汉明距离匹配阈值
min_consecutive: 最少连续匹配帧数
max_gap: 允许的最大间隙帧数
neighbor_window: 时序对齐允许的目标分片序号邻接窗口(正/反向均允许)
Returns:
DuplicateSegment 列表
@@ -401,94 +321,95 @@ def find_duplicate_segments(
if not query_chunks or not target_chunks:
return []
def _get(chunk, key):
def _get_phash(chunk) -> str:
if isinstance(chunk, dict):
return chunk[key]
return getattr(chunk, key)
return chunk["phash_binary"]
return chunk.phash_binary
n, m = len(query_chunks), len(target_chunks)
q_ph = [_get(c, "phash_binary") for c in query_chunks]
t_ph = [_get(c, "phash_binary") for c in target_chunks]
def _get_start(chunk) -> int:
if isinstance(chunk, dict):
return chunk["start_time_ms"]
return chunk.start_time_ms
# Step 1: 全量距离矩阵。每个 query chunk 保留所有 <= 阈值的候选 target
# 按距离升序;同距时小索引优先(取最早的对齐位置,贪心连贯推进时最保守,
# 不会越过复用片段末端;重复 hash 的连续帧由 Step 2 的连贯性窗口约束)。
candidates: list[list[tuple[int, int]]] = [] # 每 query 帧: [(target_idx, dist), ...]
for i in range(n):
dists = [hamming_distance(q_ph[i], t_ph[j]) for j in range(m)]
cand = [(j, d) for j, d in enumerate(dists) if d <= match_threshold]
cand.sort(key=lambda x: (x[1], x[0]))
candidates.append(cand)
def _get_end(chunk) -> int:
if isinstance(chunk, dict):
return chunk["end_time_ms"]
return chunk.end_time_ms
# 短视频自适应连续匹配门槛(Issue #1702 工单公式):
# MIN_CONSECUTIVE_MATCHES = min(5, max(2, 分片数//2))。
# n=1 时门槛为 2 不形成片段,由 _evaluate_candidate 的匹配帧回退
# temporal_coverage 按匹配帧占比估计)兜底检出,不回归。
if min_consecutive is None:
min_consecutive = min(MIN_CONSECUTIVE_MATCHES, max(2, n // 2))
# Step 1: 逐帧匹配
frame_matches: list[tuple[bool, int, int]] = [] # (is_match, min_dist, best_target_idx)
for qc in query_chunks:
qc_phash = _get_phash(qc)
best_dist = 64
best_idx = 0
for j, tc in enumerate(target_chunks):
d = hamming_distance(qc_phash, _get_phash(tc))
if d < best_dist:
best_dist = d
best_idx = j
frame_matches.append((best_dist <= match_threshold, best_dist, best_idx))
# Step 2: 时序一致贪心对齐。
# run 内偏好与上一匹配帧目标序号连贯(|delta| <= neighbor_window+1
# 支持 ±1 邻接窗口/时序偏移对齐,正反向抖动均允许)的候选;
# 无连贯候选时关闭旧 run。
# 这天然支持局部片段复用:同一 query 视频中多个复用片段各自形成独立 run。
frame_matches: list[tuple[bool, int, int]] = []
runs: list[tuple[int, int]] = []
run_start: Optional[int] = None
run_last_t: Optional[int] = None
# Step 2: 找连续匹配的 runs
runs: list[tuple[int, int]] = [] # list of (start_idx, end_idx)
run_start = None
gap_count = 0
def _matching_count(a: int, b: int) -> int:
return sum(1 for k in range(a, b + 1) if frame_matches[k][0])
def _close_run(a: int, b: int) -> None:
if b >= a and _matching_count(a, b) >= min_consecutive:
runs.append((a, b))
for i in range(n):
cand = candidates[i]
if run_last_t is None:
chosen = cand[0] if cand else None
else:
chosen = next(
(c for c in cand if abs(c[0] - run_last_t) <= neighbor_window + 1),
None,
)
if chosen is not None:
tidx, dist = chosen
frame_matches.append((True, dist, tidx))
for i, (is_match, _dist, _idx) in enumerate(frame_matches):
if is_match:
if run_start is None:
run_start = i
gap_count = 0
run_last_t = tidx
gap_count = 0 # 重置间隙
else:
frame_matches.append((False, match_threshold + 1, -1))
if run_start is not None:
gap_count += 1
if gap_count > max_gap:
# 非匹配帧从 i-gap_count+1 开始,run 结束于其前一帧
_close_run(run_start, i - gap_count)
run_start, run_last_t, gap_count = None, None, 0
# 中断当前 run
run_end = i - gap_count # 最后一个匹配帧的索引
# 计算 run 内的实际匹配帧数(总跨度 - 间隙数)
total_gaps = sum(1 for k in range(run_start, run_end + 1) if not frame_matches[k][0])
matching_count = (run_end - run_start + 1) - total_gaps
if matching_count >= min_consecutive:
runs.append((run_start, run_end))
run_start = None
gap_count = 0
# 处理末尾 run
if run_start is not None:
last_idx = n - 1
last_idx = len(frame_matches) - 1
# 回退找到最后一个匹配帧的位置(跳过尾部非匹配帧)
while last_idx >= run_start and not frame_matches[last_idx][0]:
last_idx -= 1
_close_run(run_start, last_idx)
if last_idx >= run_start:
# 计算 run 内的总间隙数
total_gaps = sum(1 for k in range(run_start, last_idx + 1) if not frame_matches[k][0])
matching_count = (last_idx - run_start + 1) - total_gaps
if matching_count >= min_consecutive:
runs.append((run_start, last_idx))
# Step 3: 构建 DuplicateSegment
segments: list[DuplicateSegment] = []
for start, end in runs:
query_start = _get_start(query_chunks[start])
query_end = _get_end(query_chunks[end])
# 取目标范围(按最佳匹配的目标 chunk 时间范围)
target_indices = [frame_matches[k][2] for k in range(start, end + 1) if frame_matches[k][0]]
t_min, t_max = min(target_indices), max(target_indices)
avg_dist = sum(frame_matches[k][1] for k in range(start, end + 1) if frame_matches[k][0]) / len(target_indices)
if target_indices:
t_min = min(target_indices)
t_max = max(target_indices)
target_start = _get_start(target_chunks[t_min])
target_end = _get_end(target_chunks[t_max])
else:
target_start = _get_start(target_chunks[0])
target_end = _get_end(target_chunks[-1])
avg_dist = sum(frame_matches[k][1] for k in range(start, end + 1)) / (end - start + 1)
segments.append(
DuplicateSegment(
query_start_ms=_get(query_chunks[start], "start_time_ms"),
query_end_ms=_get(query_chunks[end], "end_time_ms"),
target_start_ms=_get(target_chunks[t_min], "start_time_ms"),
target_end_ms=_get(target_chunks[t_max], "end_time_ms"),
query_start_ms=query_start,
query_end_ms=query_end,
target_start_ms=target_start,
target_end_ms=target_end,
avg_distance=avg_dist,
)
)
@@ -502,9 +423,7 @@ def find_duplicate_segments(
class VideoDeduplicator:
"""Video deduplication using multiple fingerprint methods."""
# Issue #1702: 阈值统一来源为模块常量 PHASH_THRESHOLD#1658 曾收紧到 8
# 后经 staging 真实同源/异源指纹分布重新校准,见 test_phash_threshold_calibration_1702)。
PHASH_THRESHOLD = PHASH_THRESHOLD
PHASH_THRESHOLD = 8 # Issue #1658: pHash 汉明距离阈值由 10 收紧到 8,降低不同视频误判率
HISTOGRAM_THRESHOLD = 0.85
@staticmethod
@@ -528,36 +447,27 @@ class VideoDeduplicator:
# 单帧不视为坏指纹(短视频或抽帧不足)
if len(phashes) == 1:
return False
# Issue #1702: 旧逻辑"所有 phash 完全相同即判黑屏"会误杀短视频——
# 11s 视频只有几个不同镜头时,相邻 1s 采样帧可能 phash 完全一致(内容
# 连续但非黑屏)。黑屏的特征是「大量帧全部无内容」,要求至少 8 帧
# 且相同帧占比 >=80% 才判坏;短视频(<8 帧)只有真正单值时交给
# _bhattacharyya/融合分兜底,不因"帧都一样"直接跳过。
if len(phashes) < 8:
return False
# 多帧但所有 phash 完全相同 → 黑屏/纯色视频
unique = set(phashes)
same_ratio = sum(1 for x in phashes if x == phashes[0]) / len(phashes)
if len(unique) == 1 and same_ratio >= 0.8:
if len(unique) == 1:
return True
# 多帧但所有唯一 phash 之间的汉明距离都极小(<3)且占比 >=80% → 近似黑屏
# 多帧但所有 phash 之间的汉明距离都极小(<3)→ 近似黑屏
phash_list = list(unique)
if len(phash_list) >= 2 and same_ratio >= 0.8:
all_distances = [
hamming_distance(phash_list[i], phash_list[j])
for i in range(len(phash_list))
for j in range(i + 1, len(phash_list))
]
if len(phash_list) >= 2:
all_distances = []
for i in range(len(phash_list)):
for j in range(i + 1, len(phash_list)):
all_distances.append(hamming_distance(phash_list[i], phash_list[j]))
if all_distances and max(all_distances) < 3:
return True
return False
def compute_fingerprint(self, video_path: str) -> VideoFingerprint:
"""Compute video fingerprint using dense uniform sampling.
"""Compute video fingerprint using dynamic keyframe detection.
Issue #1702: 使用 sample_fingerprint_timestamps() 固定 1s 间隔密集均匀
采样(替代动态场景检测抽帧),保证两个同源视频复用片段的帧时刻天然
对齐;每帧取中心 90% 区域(center_crop_frame)计算 pHash + color_histogram
绕开 random_edge_crop 降重裁剪污染;MD5 仍基于原始帧。
使用 detect_keyframe_timestamps() 检测内容感知关键帧,
在每个关键帧处取帧计算 pHash + color_histogram。
同时保留 MD5 计算和分片数据结构。
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
@@ -571,8 +481,8 @@ class VideoDeduplicator:
cap.release()
# 1. 固定间隔密集采样(Issue #1702:替代动态场景检测,保证跨视频时序对齐)
keyframe_times = sample_fingerprint_timestamps(duration)
# 1. 检测关键帧时间戳
keyframe_times = detect_keyframe_timestamps(video_path)
if not keyframe_times:
return VideoFingerprint(
@@ -596,15 +506,12 @@ class VideoDeduplicator:
if not ret:
continue
# MD5 计算(基于原始帧,指纹文件级去重不受裁剪影响)
# MD5 计算
_, buffer = cv2.imencode(".jpg", frame)
md5_hash.update(buffer)
# Issue #1702: pHash / 颜色直方图基于中心 90% 区域,绕开 random_edge_crop
# 降重裁剪对指纹的污染(降重只服务外部平台,不污染自查重)。
fp_frame = center_crop_frame(frame)
phash = compute_phash(fp_frame)
hist = compute_color_histogram(fp_frame)
phash = compute_phash(frame)
hist = compute_color_histogram(frame)
# 计算分片时间范围(从前一个关键帧到下一个关键帧的中点)
prev_boundary = keyframe_times[i - 1] * 1000 if i > 0 else 0
@@ -657,22 +564,12 @@ class VideoDeduplicator:
@staticmethod
def _bhattacharyya_coefficient(hist_a: list[float], hist_b: list[float]) -> float:
"""Bhattacharyya 系数(概率分布版,范围 [0,1]1=完全相同
Issue #1702: compute_color_histogram 输出 3 通道拼接、每通道独立 NORM_L1
(单通道 Σ=1,三通道拼接向量 Σ=3)。旧实现直接 Σ√(a*b) 对三通道拼接向量
算出 ~3(旧 L2 归一化更是算出 ~14.9),不是合法的概率系数。
这里按两个直方图各自的总量归一:BC = Σ√(a*b) / √(Σa·Σb)。
- 单通道概率分布(Σa=Σb=1):分母 1,与旧测试/教科书定义一致;
- 三通道拼接(Σa=Σb=3):分母 3,结果在 [0,1]。
"""
"""Bhattacharyya 系数:Σ √(a[i] * b[i]),范围 [0, 1]1=完全相同。"""
min_len = min(len(hist_a), len(hist_b))
a = [max(0.0, float(x)) for x in hist_a[:min_len]]
b = [max(0.0, float(x)) for x in hist_b[:min_len]]
# max(0.0, ...) 防御上游异常负值导致 sqrt domain error
coeff = sum(math.sqrt(ai * bi) for ai, bi in zip(a, b, strict=False))
norm = math.sqrt(sum(a) * sum(b))
return float(coeff / norm) if norm > 0 else 0.0
a = hist_a[:min_len]
b = hist_b[:min_len]
# 纯标准库计算(不依赖 numpy);max(0.0, ...) 防御上游异常负值导致 sqrt domain error
return float(sum(math.sqrt(max(0.0, ai * bi)) for ai, bi in zip(a, b, strict=False)))
@staticmethod
def _compute_histogram_similarity(
@@ -714,72 +611,6 @@ class VideoDeduplicator:
hist_similarity = VideoDeduplicator._compute_histogram_similarity(hist_a, hist_b) if hist_b else 0.5
return PHASH_WEIGHT * phash_similarity + HISTOGRAM_WEIGHT * hist_similarity
@staticmethod
def _evaluate_candidate(
fingerprint: VideoFingerprint,
existing_phashes: list[str],
existing_histograms: list,
existing_chunk_objects: list,
*,
query_duration_sec: float,
) -> dict:
"""评估新视频指纹与单个候选视频的相似度(Issue #1702 共享逻辑)。
指标:
- min_distances / frame_match_rate:每个新分片到候选视频全局最近邻的汉明距离,
分母取两视频分片数的较小值(支持局部片段复用:短视频复用长视频片段时不被长视频分母稀释)。
- temporal_coverage:时序一致连续匹配片段总时长 / 新视频时长(局部复用主指标)。
- fusionpHash 中位数距离 + 颜色直方图的加权融合分。
Returns:
{frame_match_rate, temporal_coverage, segments, median_distance,
fusion, matching_frames, min_distances}
"""
query_phashes = fingerprint.keyframe_phashes or []
if not query_phashes or not existing_phashes:
return {
"frame_match_rate": 0.0,
"temporal_coverage": 0.0,
"segments": [],
"median_distance": 64,
"fusion": 0.0,
"matching_frames": 0,
"min_distances": [],
}
min_distances = [min(hamming_distance(ph, ep) for ep in existing_phashes) for ph in query_phashes]
matching_frames = sum(1 for d in min_distances if d <= PHASH_THRESHOLD)
# 分母取 min(两视频分片数):局部复用时(如 B 的 5 片复用 A 9 片中的若干片)
# 命中帧占比不因候选视频更长而被稀释。
frame_match_rate = matching_frames / min(len(query_phashes), len(existing_phashes))
segments = find_duplicate_segments(fingerprint.chunks, existing_chunk_objects)
duration_ms = query_duration_sec * 1000 if query_duration_sec else 0
if duration_ms > 0 and segments:
covered_ms = sum(s.query_end_ms - s.query_start_ms for s in segments)
temporal_coverage = min(covered_ms / duration_ms, 1.0)
elif matching_frames > 0:
# 无连续片段(时序连贯性不足)时,按匹配帧占比估计覆盖:
# 密集 1s 采样下每个分片≈1s 等权时间片,匹配帧数≈命中秒数。
temporal_coverage = min(frame_match_rate, 1.0)
else:
temporal_coverage = 0.0
median_distance = statistics.median(min_distances) if min_distances else 64
fusion = VideoDeduplicator._compute_fusion_score(
median_distance, fingerprint.color_histograms, existing_histograms
)
return {
"frame_match_rate": frame_match_rate,
"temporal_coverage": temporal_coverage,
"segments": segments,
"median_distance": median_distance,
"fusion": fusion,
"matching_frames": matching_frames,
"min_distances": min_distances,
}
def check_duplicate(
self,
fingerprint: VideoFingerprint,
@@ -789,7 +620,6 @@ class VideoDeduplicator:
scope: str = "project",
user_id: str = "",
duration_sec: float = 0,
exclude_video_id: str | None = None,
) -> Optional[dict]:
"""检查视频是否与已有视频重复。
@@ -806,9 +636,6 @@ class VideoDeduplicator:
scope: "project" 项目内查重(默认),"user" 跨项目全局查重
user_id: 用户 IDscope="user" 时使用)
duration_sec: 视频时长(秒),用于时长预过滤 ±15%
exclude_video_id: 排除的视频 ID(查重自身时用)。recompute-dedup
重算时视频记录已存在,不排除会自匹配(距离 0 分最高)导致
duplicate_of 指向自己(Issue #1702 连带修复)。
Returns:
重复信息字典(含 duplicate, duplicate_of, reason, similarity, duplicate_segments),
@@ -816,22 +643,13 @@ class VideoDeduplicator:
"""
video_repo = SQLAlchemyGeneratedVideoRepository(session)
if scope == "user" and user_id:
# Issue #1702: 不做 ±15% 时长预过滤。旧逻辑按 duration_sec 缩小候选窗口,
# 但局部片段复用的两个视频时长必然不同(证据视频 20s vs 11s,差 42%),
# ±15% 窗口让同源视频互相不可见 → is_duplicate 恒 False。
# 全量遍历同用户视频(与 compute_duplicate_rate 口径一致),异源视频由
# fusion/temporal_coverage 阈值天然过滤(校准:异源最小汉明距离 24)。
existing_videos = video_repo.list_by_user(user_id)
dur_min = duration_sec * 0.85 if duration_sec > 0 else 0
dur_max = duration_sec * 1.15 if duration_sec > 0 else 0
existing_videos = video_repo.list_by_user(user_id, duration_min=dur_min, duration_max=dur_max)
else:
existing_videos = video_repo.list_by_project(project_id)
best_score = 0.0
best_result: Optional[dict] = None
for existing in existing_videos:
# 排除自身(recompute 时当前视频已在候选列表里,否则自匹配距离 0 必最高分)
if exclude_video_id and existing.id == exclude_video_id:
continue
if not existing.video_fingerprint:
continue
@@ -859,70 +677,61 @@ class VideoDeduplicator:
if not existing_phashes:
continue
# 直方图 / 分片对象(chunk 表优先,回退 JSON 字段;JSON NULL 显式回退空列表)
# 计算每个新关键帧到已有关键帧的最小汉明距离
min_distances = []
for phash in fingerprint.keyframe_phashes:
distances = [hamming_distance(phash, ep) for ep in existing_phashes]
min_distances.append(min(distances))
# 帧匹配比例检查
matching_frames = sum(1 for d in min_distances if d < self.PHASH_THRESHOLD)
match_ratio = matching_frames / len(min_distances) if min_distances else 0
if match_ratio < MATCH_RATIO_THRESHOLD:
continue
# 中位数距离
median_distance = statistics.median(min_distances) if min_distances else 64
if median_distance >= self.PHASH_THRESHOLD:
continue
# 直方图融合(chunk 表优先,回退 JSON 字段;JSON NULL 显式回退空列表)
if chunk_data:
existing_histograms = [c["color_histogram"] for c in chunk_data if c.get("color_histogram")]
existing_chunk_objects = chunk_data
else:
existing_histograms = ef.get("color_histograms") or []
existing_chunk_objects = [
{"phash_binary": pp, "start_time_ms": 0, "end_time_ms": 0} for pp in existing_phashes
]
# Issue #1702: 统一评估每个候选(含局部片段复用),不再用
# "frame_match_rate<0.7 整条跳过" 的硬门槛——局部复用(如 B 结尾 2s
# ≈ A 中间 2s)帧比例天然低,但 coverage 能检出。
ev = self._evaluate_candidate(
fingerprint,
existing_phashes,
existing_histograms,
existing_chunk_objects,
query_duration_sec=fingerprint.duration,
)
logger.debug(
"check_duplicate candidate=%s min_distances=%s frame_match_rate=%.3f "
"temporal_coverage=%.3f median=%.1f fusion=%.3f segments=%d",
existing.id,
ev["min_distances"],
ev["frame_match_rate"],
ev["temporal_coverage"],
ev["median_distance"],
ev["fusion"],
len(ev["segments"]),
combined_score = self._compute_fusion_score(
median_distance, fingerprint.color_histograms, existing_histograms
)
# 全片重复判定:融合分过阈 且(帧匹配比例 >=70% 或 局部覆盖 >=50%
is_full_duplicate = ev["fusion"] >= DUPLICATE_THRESHOLD and (
ev["frame_match_rate"] >= MATCH_RATIO_THRESHOLD or ev["temporal_coverage"] >= PARTIAL_COVERAGE_THRESHOLD
if combined_score < DUPLICATE_THRESHOLD:
continue
# 滑动窗口时序匹配:获取具体重复片段
existing_chunk_objects = (
chunk_data
if chunk_data
else [{"phash_binary": p, "start_time_ms": 0, "end_time_ms": 0} for p in existing_phashes]
)
if is_full_duplicate and ev["fusion"] > best_score:
best_score = ev["fusion"]
best_result = {
"duplicate": True,
"duplicate_of": existing.id,
"reason": "phash_histogram_fusion",
"similarity": ev["fusion"],
"duplicate_segments": [
{
"query_start_ms": s.query_start_ms,
"query_end_ms": s.query_end_ms,
"target_start_ms": s.target_start_ms,
"target_end_ms": s.target_end_ms,
"avg_distance": round(s.avg_distance, 2),
}
for s in ev["segments"]
],
}
segments = find_duplicate_segments(fingerprint.chunks, existing_chunk_objects)
return {
"duplicate": True,
"duplicate_of": existing.id,
"reason": "phash_histogram_fusion",
"similarity": combined_score,
"duplicate_segments": [
{
"query_start_ms": s.query_start_ms,
"query_end_ms": s.query_end_ms,
"target_start_ms": s.target_start_ms,
"target_end_ms": s.target_end_ms,
"avg_distance": round(s.avg_distance, 2),
}
for s in segments
],
}
if best_result:
return best_result
logger.info(
"check_duplicate no match (project=%s scope=%s): %d candidates evaluated, best_fusion=%.3f",
project_id,
scope,
len(existing_videos),
best_score,
)
return None
def check_batch_duplicate(
@@ -954,9 +763,6 @@ class VideoDeduplicator:
video_repo = SQLAlchemyGeneratedVideoRepository(session)
batch_videos = video_repo.list_by_batch(batch_id)
best_score = 0.0
best_result: Optional[dict] = None
for existing in batch_videos:
if existing.id == current_video_id:
continue
@@ -990,59 +796,59 @@ class VideoDeduplicator:
if not existing_phashes:
continue
min_distances = []
for phash in fingerprint.keyframe_phashes:
distances = [hamming_distance(phash, ep) for ep in existing_phashes]
min_distances.append(min(distances))
# 帧匹配比例检查
matching_frames = sum(1 for d in min_distances if d < self.PHASH_THRESHOLD)
match_ratio = matching_frames / len(min_distances) if min_distances else 0
if match_ratio < MATCH_RATIO_THRESHOLD:
continue
median_distance = statistics.median(min_distances) if min_distances else 64
if median_distance >= self.PHASH_THRESHOLD:
continue
# 直方图融合(chunk 表优先,回退 JSON 字段;JSON NULL 显式回退空列表)
if chunk_data:
existing_histograms = [c["color_histogram"] for c in chunk_data if c.get("color_histogram")]
existing_chunk_objects = chunk_data
else:
existing_histograms = ef.get("color_histograms") or []
existing_chunk_objects = [
{"phash_binary": pp, "start_time_ms": 0, "end_time_ms": 0} for pp in existing_phashes
]
ev = self._evaluate_candidate(
fingerprint,
existing_phashes,
existing_histograms,
existing_chunk_objects,
query_duration_sec=fingerprint.duration,
)
logger.debug(
"check_batch_duplicate candidate=%s min_distances=%s frame_match_rate=%.3f "
"temporal_coverage=%.3f median=%.1f fusion=%.3f segments=%d",
existing.id,
ev["min_distances"],
ev["frame_match_rate"],
ev["temporal_coverage"],
ev["median_distance"],
ev["fusion"],
len(ev["segments"]),
combined_score = self._compute_fusion_score(
median_distance, fingerprint.color_histograms, existing_histograms
)
is_full_duplicate = ev["fusion"] >= DUPLICATE_THRESHOLD and (
ev["frame_match_rate"] >= MATCH_RATIO_THRESHOLD or ev["temporal_coverage"] >= PARTIAL_COVERAGE_THRESHOLD
if combined_score < DUPLICATE_THRESHOLD:
continue
# 滑动窗口时序匹配
existing_chunk_objects = (
chunk_data
if chunk_data
else [{"phash_binary": p, "start_time_ms": 0, "end_time_ms": 0} for p in existing_phashes]
)
if is_full_duplicate and ev["fusion"] > best_score:
best_score = ev["fusion"]
best_result = {
"duplicate": True,
"duplicate_of": existing.id,
"reason": "batch_phash_histogram_fusion",
"similarity": ev["fusion"],
"duplicate_segments": [
{
"query_start_ms": s.query_start_ms,
"query_end_ms": s.query_end_ms,
"target_start_ms": s.target_start_ms,
"target_end_ms": s.target_end_ms,
"avg_distance": round(s.avg_distance, 2),
}
for s in ev["segments"]
],
}
segments = find_duplicate_segments(fingerprint.chunks, existing_chunk_objects)
return {
"duplicate": True,
"duplicate_of": existing.id,
"reason": "batch_phash_histogram_fusion",
"similarity": combined_score,
"duplicate_segments": [
{
"query_start_ms": s.query_start_ms,
"query_end_ms": s.query_end_ms,
"target_start_ms": s.target_start_ms,
"target_end_ms": s.target_end_ms,
"avg_distance": round(s.avg_distance, 2),
}
for s in segments
],
}
if best_result:
return best_result
logger.info("check_batch_duplicate no match (batch=%s): best_fusion=%.3f", batch_id, best_score)
return None
def compute_duplicate_rate(
@@ -1091,7 +897,8 @@ class VideoDeduplicator:
max_duplicate_rate = 0.0
max_visual_similarity = 0.0
match_count = 0
evaluated = 0
total_duration_ms = fingerprint.duration if fingerprint.duration else 0
for existing in existing_videos:
if current_video_id and existing.id == current_video_id:
@@ -1126,63 +933,57 @@ class VideoDeduplicator:
if not existing_phashes or not fingerprint.keyframe_phashes:
continue
# 直方图 / 分片对象(chunk 表优先,回退 JSON 字段;JSON NULL 显式回退空列表)
min_distances = []
for phash in fingerprint.keyframe_phashes:
distances = [hamming_distance(phash, ep) for ep in existing_phashes]
min_distances.append(min(distances))
# frame_match_rate
total_frames = len(min_distances)
if total_frames == 0:
continue
matching_frames = sum(1 for d in min_distances if d < self.PHASH_THRESHOLD)
frame_match_rate = matching_frames / total_frames
# 帧匹配比例太低则跳过
if frame_match_rate < 0.3:
continue
# temporal_coverage_rate via find_duplicate_segments
existing_chunk_objects = (
chunk_data
if chunk_data
else [{"phash_binary": p, "start_time_ms": 0, "end_time_ms": 0} for p in existing_phashes]
)
segments = find_duplicate_segments(fingerprint.chunks, existing_chunk_objects)
if total_duration_ms > 0 and segments:
covered_ms = sum(s.query_end_ms - s.query_start_ms for s in segments)
temporal_coverage_rate = min(covered_ms / total_duration_ms, 1.0)
else:
temporal_coverage_rate = 0.0
# duplicate_rate = 0.4 * frame_match_rate + 0.6 * temporal_coverage_rate
dup_rate = (frame_match_rate * 0.4 + temporal_coverage_rate * 0.6) * 100
# visual_similarity (融合相似度,归一化 0~1)
median_distance = statistics.median(min_distances) if min_distances else 64
if chunk_data:
existing_histograms = [c["color_histogram"] for c in chunk_data if c.get("color_histogram")]
existing_chunk_objects = chunk_data
else:
# JSON NULL 显式回退空列表
existing_histograms = ef.get("color_histograms") or []
existing_chunk_objects = [
{"phash_binary": pp, "start_time_ms": 0, "end_time_ms": 0} for pp in existing_phashes
]
# Issue #1702: 统一评估;frame_match_rate 分母为 min(两视频分片数),
# temporal_coverage 时长量纲在 _evaluate_candidate 内统一为毫秒。
ev = self._evaluate_candidate(
fingerprint,
existing_phashes,
existing_histograms,
existing_chunk_objects,
query_duration_sec=fingerprint.duration,
)
evaluated += 1
logger.debug(
"compute_duplicate_rate candidate=%s min_distances=%s frame_match_rate=%.3f "
"temporal_coverage=%.3f median=%.1f fusion=%.3f segments=%d",
existing.id,
ev["min_distances"],
ev["frame_match_rate"],
ev["temporal_coverage"],
ev["median_distance"],
ev["fusion"],
len(ev["segments"]),
)
visual_sim = self._compute_fusion_score(median_distance, fingerprint.color_histograms, existing_histograms)
# Issue #1702: 去掉 "frame_match_rate<0.3 整条跳过" 硬门槛——
# 局部片段复用帧比例天然低;coverage 为主指标,0 匹配自然得 0 分。
# duplicate_rate = 0.4 * frame_match_rate + 0.6 * temporal_coverage
dup_rate = (min(ev["frame_match_rate"], 1.0) * 0.4 + ev["temporal_coverage"] * 0.6) * 100
# 全片重复计数与 check_duplicate 判定口径一致
if ev["fusion"] >= DUPLICATE_THRESHOLD and (
ev["frame_match_rate"] >= MATCH_RATIO_THRESHOLD or ev["temporal_coverage"] >= PARTIAL_COVERAGE_THRESHOLD
):
# 判定是否为重复(融合分数超过阈值)
if visual_sim >= DUPLICATE_THRESHOLD:
match_count += 1
if dup_rate > max_duplicate_rate:
max_duplicate_rate = dup_rate
max_visual_similarity = ev["fusion"]
max_visual_similarity = visual_sim
logger.info(
"compute_duplicate_rate done (project=%s scope=%s): evaluated=%d max_rate=%.2f%% "
"max_visual_sim=%.3f matches=%d",
project_id,
scope,
evaluated,
max_duplicate_rate,
max_visual_similarity,
match_count,
)
return {
"duplicate_rate": round(max(max_duplicate_rate, 0.0), 2),
"visual_similarity": round(max_visual_similarity, 4),
@@ -1198,20 +999,18 @@ def _save_fingerprint_chunks(
session: Session,
) -> None:
"""将指纹分片数据批量写入 video_fingerprint_chunks 表。幂等:已有数据时跳过。"""
# 幂等检查:已有分片数据则跳过
existing_count = (
session.query(VideoFingerprintChunkModel).filter(VideoFingerprintChunkModel.video_id == video_id).count()
)
if existing_count > 0:
logger.debug("Fingerprint chunks already exist for video %s (%d chunks), skipping", video_id, existing_count)
return
if not fingerprint.chunks:
logger.warning("No chunks in fingerprint for video %s, skipping chunk save", video_id)
return
# Issue #1702: recompute-dedup 重算时指纹算法已变(中心裁剪 + 新阈值),
# 旧分片必须替换而非跳过(旧实现"有数据就跳过"导致重算不刷新分片表)。
deleted = (
session.query(VideoFingerprintChunkModel)
.filter(VideoFingerprintChunkModel.video_id == video_id)
.delete(synchronize_session=False)
)
if deleted:
logger.info("Replaced %d stale fingerprint chunks for video %s", deleted, video_id)
chunk_models = fingerprint.to_chunk_models(video_id, project_id, user_id)
session.bulk_save_objects(chunk_models)
logger.info("Saved %d fingerprint chunks for video %s", len(chunk_models), video_id)
@@ -1233,17 +1032,9 @@ def check_duplicate_task(self: Task, generated_video_id: str) -> dict:
raise ValueError(f"Generated video {generated_video_id} not found")
local_path = os.path.join(temp_dir, f"{generated_video_id}.mp4")
# Issue #1702: recompute 走的是 OSS 重新下载路径(正常生成流程用本地渲染文件,
# 不经此任务)。成片真实 OSS key 是生成时的
# generated/projects/{pid}/tasks/{task_id}/rendered_*.mp4(见 generation.py
# _upload_and_record),旧代码硬编码 projects/{pid}/generated/{vid}/{vid}.mp4
# 这个从不存在的 key,导致所有 recompute 任务下载 404、查重数据永远无法重算。
# 优先从 file_url 解析真实 key,旧 key 模式仅作回退。
download_key = getattr(video, "file_url", "") or ""
if not download_key:
download_key = f"projects/{video.project_id}/generated/{generated_video_id}/{generated_video_id}.mp4"
logger.warning("video %s has no file_url, falling back to legacy key %s", generated_video_id, download_key)
storage_service.download_file(download_key, local_path)
storage_service.download_file(
f"projects/{video.project_id}/generated/{generated_video_id}/{generated_video_id}.mp4", local_path
)
fingerprint = deduplicator.compute_fingerprint(local_path)
@@ -1254,10 +1045,7 @@ def check_duplicate_task(self: Task, generated_video_id: str) -> dict:
session,
scope="user",
user_id=video.user_id,
# Issue #1702: fingerprint.duration 单位已经是秒,旧代码 /1000 导致
# ±15% 时长预过滤窗口缩到 ~0.013sscope=user 的跨项目查重永远返回 None。
duration_sec=fingerprint.duration if fingerprint.duration else 0,
exclude_video_id=generated_video_id,
duration_sec=fingerprint.duration / 1000 if fingerprint.duration else 0,
)
video.video_fingerprint = fingerprint.to_dict()
@@ -92,8 +92,7 @@ def create_video_record_and_dedup(
logger.warning("Failed to save fingerprint chunks for %s: %s", video_id, chunk_err)
# (a) 历史成片查重(跨项目全局 + 时长预过滤)
# Issue #1702: fingerprint.duration 单位是秒,旧代码 /1000 让时长预过滤失效
duration_sec = fingerprint.duration if fingerprint.duration else 0
duration_sec = fingerprint.duration / 1000 if fingerprint.duration else 0
duplicate_result = deduplicator.check_duplicate(
fingerprint,
project_id,
@@ -101,7 +100,6 @@ def create_video_record_and_dedup(
scope="user",
user_id=user_id,
duration_sec=duration_sec,
exclude_video_id=video_id,
)
# (b) 批次内查重(仅当有 batch_id 时)
+2 -10
View File
@@ -22,18 +22,10 @@ celery_app.conf.imports = (
)
# Celery Beat 定时任务调度
# 注:worker 单实例内嵌 beatentrypoint-worker.sh -B),定时任务不会重复执行
celery_app.conf.beat_schedule = {
# pending 任务超时清理:worker 停止消费后,卡 pending 的任务 15 分钟内释放限流名额
"cleanup-stale-pending-tasks": {
"task": "worker.cleanup_stale_pending_tasks",
"schedule": 300.0, # 每 5 分钟(秒)
"options": {"expires": 240}, # 4 分钟过期,避免堆积
},
# running 孤儿任务巡检:容器重启/进程被杀后卡 running 的任务,20 分钟无更新则判失败
"cleanup-stale-running-tasks": {
"task": "worker.cleanup_stale_running_tasks",
"schedule": 300.0, # 每 5 分钟(秒)
"options": {"expires": 240},
"schedule": 600.0, # 每 10 分钟(秒)
"options": {"expires": 300}, # 5 分钟过期,避免堆积
},
}
+8 -33
View File
@@ -7,34 +7,11 @@ from worker_app.db import SessionLocal
logger = logging.getLogger(__name__)
# 孤儿任务超时阈值:渲染任务超过此时间未更新则视为卡死
ORPHAN_TASK_TIMEOUT_MINUTES = 10
def cleanup_stale_running_with_session(repo, timeout_minutes: int) -> int:
"""清理超时未更新的 running GenerationTask(可注入 repo 的纯核心,便于单测)。
Returns:
清理的任务数量
"""
return repo.cleanup_stale_running(timeout_minutes)
def cleanup_stale_pending_with_session(repo, timeout_minutes: int) -> int:
"""清理超时 pending GenerationTask(可注入 repo 的纯核心,便于单测)。
Returns:
清理的任务数量
"""
return repo.cleanup_stale_pending(timeout_minutes)
# 孤儿任务超时阈值:running 任务超过此时间无进度更新则视为卡死。
# 依据:worker.generate_video 硬超时 time_limit=11 分钟,正常任务不可能超过;
# 20 分钟阈值覆盖硬超时 + 重试 + 余量,绝不误杀正常任务。
ORPHAN_TASK_TIMEOUT_MINUTES = 20
# Pending 任务超时阈值:任务创建后超过此时间仍未被 worker 拉取,
# 说明 worker 已停止消费(容器异常/卡死),清掉释放限流名额。
# 依据:满队列(20 pending)× 平均 2 分钟 / 并发 4 ≈ 10 分钟,15 分钟留余量。
PENDING_TASK_TIMEOUT_MINUTES = 15
# Pending 任务超时阈值:pending 任务在队列中等待超过此时间则自动清理
PENDING_TASK_TIMEOUT_MINUTES = 30
def cleanup_orphan_tasks(timeout_minutes: int = ORPHAN_TASK_TIMEOUT_MINUTES) -> int: # pragma: no cover
@@ -55,11 +32,9 @@ def cleanup_orphan_tasks(timeout_minutes: int = ORPHAN_TASK_TIMEOUT_MINUTES) ->
try:
session = SessionLocal()
try:
repo = SQLAlchemyGenerationTaskRepository(session)
count = cleanup_stale_running_with_session(repo, timeout_minutes)
finally:
session.close()
repo = SQLAlchemyGenerationTaskRepository(session)
count = repo.cleanup_stale_running(timeout_minutes)
session.close()
if count > 0:
logger.warning("清理了 %d 个超时的孤儿 GenerationTask(超过 %d 分钟未更新)", count, timeout_minutes)
else:
@@ -130,7 +105,7 @@ def cleanup_stale_pending_tasks(timeout_minutes: int = PENDING_TASK_TIMEOUT_MINU
session = SessionLocal()
try:
repo = SQLAlchemyGenerationTaskRepository(session)
count = cleanup_stale_pending_with_session(repo, timeout_minutes)
count = repo.cleanup_stale_pending(timeout_minutes)
if count > 0:
logger.warning("清理了 %d 个超时的 pending GenerationTask(超过 %d 分钟未处理)", count, timeout_minutes)
else:
+4 -38
View File
@@ -1,18 +1,14 @@
"""定期清理任务 — Celery Beat 调度。
包含:
- cleanup_stale_pending_tasks: 定期清理卡在 pending 超时的 generation_tasksworker 停止消费时占位)
- cleanup_stale_running_tasks: 定期清理卡在 running 超时的 generation_tasks(容器重启/进程被杀后的孤儿)
- cleanup_stale_pending_tasks: 定期清理卡在 pending 超时的 generation_tasks
"""
import logging
from celery import shared_task
from worker_app.tasks._startup import (
ORPHAN_TASK_TIMEOUT_MINUTES,
PENDING_TASK_TIMEOUT_MINUTES,
cleanup_orphan_tasks,
cleanup_stale_jobs,
cleanup_stale_pending_tasks,
)
@@ -23,12 +19,12 @@ logger = logging.getLogger(__name__)
def scheduled_cleanup_stale_pending(timeout_minutes: int = PENDING_TASK_TIMEOUT_MINUTES) -> dict:
"""Celery Beat 调度的定期任务:清理超时的 pending 任务。
5 分钟执行一次(由 celery_app.py 的 beat_schedule 配置),
10 分钟执行一次(由 celery_app.py 的 beat_schedule 配置),
查找所有 status='pending' 且 created_at < NOW() - timeout_minutes
的 generation_tasks,批量更新为 failed,释放限流名额
的 generation_tasks,批量更新为 failed。
Args:
timeout_minutes: 超时时间(分钟),默认 15 分钟
timeout_minutes: 超时时间(分钟),默认 30 分钟
Returns:
{"cleaned": int}
@@ -37,33 +33,3 @@ def scheduled_cleanup_stale_pending(timeout_minutes: int = PENDING_TASK_TIMEOUT_
if count > 0:
logger.info("[Beat] 清理了 %d 个超时 pending 任务(超时阈值 %d 分钟)", count, timeout_minutes)
return {"cleaned": count}
@shared_task(name="worker.cleanup_stale_running_tasks")
def scheduled_cleanup_stale_running(timeout_minutes: int = ORPHAN_TASK_TIMEOUT_MINUTES) -> dict:
"""Celery Beat 调度的定期任务:清理超时的 running 孤儿任务。
每 5 分钟执行一次。worker_ready 信号只在 worker 启动时清一次,
若 worker 没重启但任务卡死(上传挂起、进程 OOM 被内核杀掉等),
任务会永久卡在 running 占位。此任务做持续兜底:
查找 status='running' 且 updated_at < NOW() - timeout_minutes 的任务,
标记为 failed(原因:容器重启/超时中断),同时清理 Job 表孤儿。
Args:
timeout_minutes: 超时时间(分钟),默认 20 分钟
worker.generate_video 硬超时 11 分钟,正常任务不可能超过 20 分钟)
Returns:
{"generation_tasks": int, "jobs": int}
"""
gen_count = cleanup_orphan_tasks(timeout_minutes)
job_count = cleanup_stale_jobs(timeout_minutes)
total = gen_count + job_count
if total > 0:
logger.warning(
"[Beat] 清理孤儿任务: running GenerationTask=%d, Job=%d(超时阈值 %d 分钟)",
gen_count,
job_count,
timeout_minutes,
)
return {"generation_tasks": gen_count, "jobs": job_count}
@@ -138,52 +138,6 @@ class SQLAlchemyGenerationTaskRepository:
.count()
)
def count_running_by_user(self, user_id: str) -> int:
"""统计指定用户处于 running 状态的任务数(用于限流提示展示)。"""
return (
self.session.query(GenerationTaskModel)
.filter(
GenerationTaskModel.created_by_user_id == user_id,
GenerationTaskModel.status == GenerationTaskStatus.RUNNING.value,
)
.count()
)
def count_running_total(self) -> int:
"""统计全局处于 running 状态的任务数(worker 实际在执行的任务数)。"""
return (
self.session.query(GenerationTaskModel)
.filter(GenerationTaskModel.status == GenerationTaskStatus.RUNNING.value)
.count()
)
def estimate_avg_duration_seconds(self, limit: int = 20, default_seconds: float = 120.0) -> float:
"""估算最近完成任务的平均耗时(秒),用于 429 限流提示的等待预估。
取最近 N 条 completed 任务的 (completed_at - started_at) 平均值;
无足够历史数据时返回 default_seconds。
用 Python 侧计算差值,避免 SQLite/PostgreSQL 方言差异。
"""
rows = (
self.session.query(GenerationTaskModel.started_at, GenerationTaskModel.completed_at)
.filter(
GenerationTaskModel.status == GenerationTaskStatus.COMPLETED.value,
GenerationTaskModel.started_at.isnot(None),
GenerationTaskModel.completed_at.isnot(None),
)
.order_by(GenerationTaskModel.completed_at.desc())
.limit(limit)
.all()
)
durations = [
(completed - started).total_seconds()
for started, completed in rows
if completed and started and (completed - started).total_seconds() > 0
]
if not durations:
return default_seconds
return sum(durations) / len(durations)
def list_recent_by_user(self, user_id: str, limit: int = 5) -> list[GenerationTask]:
models = (
self.session.query(GenerationTaskModel)
@@ -20,12 +20,6 @@ class GenerationTaskRepository(Protocol):
def count_pending_total(self) -> int: ...
def count_running_by_user(self, user_id: str) -> int: ...
def count_running_total(self) -> int: ...
def estimate_avg_duration_seconds(self, limit: int = 20, default_seconds: float = 120.0) -> float: ...
def list_recent_by_user(self, user_id: str, limit: int = 5) -> list[GenerationTask]: ...
def list_by_source_edit_plan(self, plan_id: str) -> list[GenerationTask]: ...
+13 -16
View File
@@ -85,18 +85,17 @@ class TestIsBadFingerprint:
assert VideoDeduplicator._is_bad_fingerprint(["abcdef0123456789"]) is False
def test_all_identical_phashes_is_bad(self):
""">=8 帧且所有 phash 完全相同 → 黑屏/纯色视频#1702:短帧不误杀)"""
phashes = ["aaaaaaaaaaaaaaaa"] * 10
"""多帧但所有 phash 完全相同 → 黑屏/纯色视频。"""
phashes = ["aaaaaaaaaaaaaaaa"] * 5
assert VideoDeduplicator._is_bad_fingerprint(phashes) is True
def test_short_identical_phashes_not_bad(self):
"""<8 帧完全相同不判坏——短视频内容连续时相邻采样帧 phash 天然相同(#1702"""
assert VideoDeduplicator._is_bad_fingerprint(["bbbbbbbbbbbbbbbb"] * 5) is False
assert VideoDeduplicator._is_bad_fingerprint(["bbbbbbbbbbbbbbbb", "bbbbbbbbbbbbbbbb"]) is False
def test_two_identical_phashes_is_bad(self):
"""帧完全相同也视为坏指纹"""
assert VideoDeduplicator._is_bad_fingerprint(["bbbbbbbbbbbbbbbb", "bbbbbbbbbbbbbbbb"]) is True
def test_all_very_similar_phashes_is_bad(self):
""">=8 帧 phash 之间的汉明距离都 < 3 且高占比 → 近似黑屏。"""
phashes = ["0000000000000000"] * 8 + ["0000000000000001", "0000000000000002"]
"""帧 phash 之间的汉明距离都 < 3 → 近似黑屏。"""
phashes = ["0000000000000000", "0000000000000001", "0000000000000002"]
assert VideoDeduplicator._is_bad_fingerprint(phashes) is True
def test_diverse_phashes_is_good(self):
@@ -123,9 +122,7 @@ class TestIsBadFingerprint:
"""已知黑屏视频的 phash 特征(全零或均匀分布)。"""
assert VideoDeduplicator._is_bad_fingerprint(["0000000000000000"] * 10) is True
assert VideoDeduplicator._is_bad_fingerprint(["ffffffffffffffff"] * 8) is True
assert VideoDeduplicator._is_bad_fingerprint(["9999999999999966"] * 8) is True
# <8 帧不判坏(#1702 短视频保护)
assert VideoDeduplicator._is_bad_fingerprint(["9999999999999966"] * 5) is False
assert VideoDeduplicator._is_bad_fingerprint(["9999999999999966"] * 6) is True
# ── Helper ──────────────────────────────────────────────────────
@@ -154,13 +151,13 @@ class TestCheckDuplicateBadFingerprint:
deduplicator = VideoDeduplicator()
mock_session = MagicMock()
black_screen = _make_existing_video("vid-black", "md5_black", ["aaaaaaaaaaaaaaaa"] * 10)
black_screen = _make_existing_video("vid-black", "md5_black", ["aaaaaaaaaaaaaaaa"] * 5)
mock_repo = MagicMock()
mock_repo.list_by_user.return_value = [black_screen]
fingerprint = VideoFingerprint(
md5="md5_normal",
keyframe_phashes=["aaaaaaaaaaaaaaaa"] * 10,
keyframe_phashes=["aaaaaaaaaaaaaaaa"] * 5,
color_histograms=[],
duration=10.0,
resolution=(1280, 720),
@@ -209,7 +206,7 @@ class TestCheckDuplicateBadFingerprint:
deduplicator = VideoDeduplicator()
mock_session = MagicMock()
black_screen = _make_existing_video("vid-black", "same_md5", ["aaaaaaaaaaaaaaaa"] * 10)
black_screen = _make_existing_video("vid-black", "same_md5", ["aaaaaaaaaaaaaaaa"] * 5)
mock_repo = MagicMock()
mock_repo.list_by_user.return_value = [black_screen]
@@ -286,8 +283,8 @@ class TestComputeDuplicateRateBadFingerprint:
mock_session = MagicMock()
videos = [
_make_existing_video("vid-b1", "md5_b1", ["aaaaaaaaaaaaaaaa"] * 10),
_make_existing_video("vid-b2", "md5_b2", ["cccccccccccccccc"] * 5), # hamming(a,c)=32 > PHASH_THRESHOLD
_make_existing_video("vid-b1", "md5_b1", ["aaaaaaaaaaaaaaaa"] * 5),
_make_existing_video("vid-b2", "md5_b2", ["bbbbbbbbbbbbbbbb"] * 5),
]
mock_repo = MagicMock()
mock_repo.list_by_user.return_value = videos
-548
View File
@@ -1,548 +0,0 @@
"""Issue #1702 — 查重率恒为 0% 修复:单测.
覆盖验收要求:
1. 同源不同裁剪的两个视频能检出非 0 相似度(指纹中心裁剪绕开降重 + 阈值校准)
2. 局部片段复用(B 结尾 2s ≈ A 中间 2s)能检出
3. 异源视频不误报(相似度接近 0
4. N=1 现有流程不回归
5. P1 确定性 bug:时长预过滤单位 /1000、直方图归一化、temporal_coverage 量纲、阈值比较统一
6. P0:±1 邻接对齐、短视频自适应连续门槛
7. P20 匹配也要落日志
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
sys.modules.setdefault("cv2", MagicMock())
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "apps" / "worker"))
sys.path.insert(0, str(ROOT / "packages"))
from video_processing.dedup import ( # noqa: E402
PHASH_THRESHOLD,
SEGMENT_MATCH_THRESHOLD,
FingerprintChunk,
VideoDeduplicator,
VideoFingerprint,
find_duplicate_segments,
)
# ── helpers ────────────────────────────────────────────────────
def _h(d: int) -> str:
"""64-bit phash with exactly d bits set vs zero hash."""
bits = ["0"] * 64
for i in range(d):
bits[i] = "1"
return f"{int(''.join(bits), 2):016x}"
def _chunk(phash: str, t0: float, t1: float):
return FingerprintChunk(
start_time_ms=int(t0 * 1000),
end_time_ms=int(t1 * 1000),
phash_binary=phash,
color_histogram=[],
frame_count=1,
)
def _fingerprint(phashes, duration, chunks=None, md5="fp-md5-x"):
return VideoFingerprint(
md5=md5,
keyframe_phashes=list(phashes),
color_histograms=[],
duration=duration,
resolution=(1280, 720),
chunks=chunks or [],
)
def _video(vid, phashes, duration=10.0, project_id="proj1"):
from packages.domain import GeneratedVideo
return GeneratedVideo(
id=vid,
project_id=project_id,
generation_task_id=f"task-{vid}",
name=f"video-{vid}.mp4",
file_url=f"https://example.com/{vid}.mp4",
file_size=1000,
duration=duration,
width=1280,
height=720,
fps=25.0,
video_fingerprint={"md5": f"md5-{vid}", "keyframe_phashes": list(phashes)},
)
def _rate(deduplicator, fp, videos, session=None):
session_magic = MagicMock()
# 分片表无数据 -> 回退 JSON keyframe_phashes
session_magic.query.return_value.filter.return_value.order_by.return_value.all.return_value = []
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
repo = MockRepo.return_value
repo.list_by_project.return_value = videos
repo.list_by_user.return_value = videos
return deduplicator.compute_duplicate_rate(fp, "proj1", "new-vid", session_magic, scope="project")
def _check(deduplicator, fp, videos, scope="project", **kw):
session_magic = MagicMock()
session_magic.query.return_value.filter.return_value.order_by.return_value.all.return_value = []
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
repo = MockRepo.return_value
repo.list_by_project.return_value = videos
repo.list_by_user.return_value = videos
return deduplicator.check_duplicate(fp, "proj1", session_magic, scope=scope, **kw)
# ── P0-1/P0-2: 同源不同裁剪(距离 6~10)检出非 0 ──────────────
class TestSameSourceDifferentCrop:
"""同源成片:random_edge_crop 后 pHash 距离 6~10,应检出非 0 相似度。"""
def test_same_source_high_similarity_detected(self):
ddp = VideoDeduplicator()
# 新视频 5 个分片,每个 phash 与已有视频对应分片距离 6(< 阈值)
base = [_h(0) for _ in range(5)]
new = [_h(6) for _ in range(5)]
existing = _video("v-old", base, duration=11.0)
chunks = [_chunk(h, i * 2.2, (i + 1) * 2.2) for i, h in enumerate(new)]
fp = _fingerprint(new, 11.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
assert result["duplicate_rate"] > 0
assert result["visual_similarity"] > 0
def test_same_source_distance_at_threshold_still_detected(self):
"""距离正好等于阈值(<=)也要算匹配——阈值比较统一为 <=。"""
assert PHASH_THRESHOLD <= 16, "阈值应经真实数据校准保持在能检出同源裁剪/降重对的范围(#1702 二次校准为 16)"
ddp = VideoDeduplicator()
base = [_h(0) for _ in range(6)]
new = [_h(PHASH_THRESHOLD) for _ in range(6)]
existing = _video("v-old", base, duration=12.0)
chunks = [_chunk(h, i * 2, (i + 1) * 2) for i, h in enumerate(new)]
fp = _fingerprint(new, 12.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
assert result["duplicate_rate"] > 0
# ── P0-2: 局部片段复用(B 结尾 2s ≈ A 中间 2s) ────────────────
class TestPartialReuse:
def test_partial_reuse_tail_overlap_detected(self):
"""新视频 6 片,最后 2 片命中已有视频中间 2 片(距离 4),其余不匹配。
旧逻辑 frame_match_rate=2/6≈0.33<0.3 硬跳过边界)+ MIN_CONSECUTIVE=5
导致完全检不出;新逻辑 coverage 为主指标 + 自适应门槛应检出。
"""
ddp = VideoDeduplicator()
# 已有 8 片:索引 3、4 是被复用的镜头
old = [_h(20 + i) for i in range(8)]
# 新视频 6 片:最后 2 片对应 old[3], old[4],距离 4;其余距离 30
new = [_h(50 + i) for i in range(4)] + [_h(4)] * 2
# 让 new[4] 与 old[3] 距离 4、new[5] 与 old[4] 距离 4(构造近似)
new[4] = f"{int('1' * 4 + '0' * 60, 2):016x}"
new[5] = f"{int('1' * 4 + '0' * 60, 2):016x}"
old[3] = _h(0)
old[4] = _h(0)
existing = _video("v-old", old, duration=16.0)
chunks = [_chunk(h, i * 2, (i + 1) * 2) for i, h in enumerate(new)]
fp = _fingerprint(new, 12.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
# 局部复用:duplicate_rate 必须非 0
assert result["duplicate_rate"] > 0
def test_short_video_adaptive_consecutive_threshold(self):
"""11s/5 片短视频:MIN_CONSECUTIVE 自适应 min(5, max(2, 5//2))=2
2 片连续命中即报片段(旧值 5 让短视频永远无法报片段)。"""
q = [
FingerprintChunk(0, 2000, "f" * 16, []),
FingerprintChunk(2000, 4000, "0" * 16, []),
FingerprintChunk(4000, 6000, f"{int('11110000', 2):016x}", []),
]
t = [
FingerprintChunk(0, 2000, "f" * 16, []),
FingerprintChunk(2000, 4000, "0" * 16, []),
FingerprintChunk(4000, 6000, "e" * 16, []),
]
# 3 片视频自适应门槛 = min(5, max(2, 3//2)) = 2
segs = find_duplicate_segments(q, t)
assert len(segs) >= 1
# ── P0-3: ±1 邻接窗口对齐 ─────────────────────────────────────
class TestNeighborAlignment:
def test_neighbor_window_absorbs_boundary_jitter(self):
"""切点错位导致目标索引偏移 ±1 时,连续匹配不应被中断。"""
q = [FingerprintChunk(i * 1000, (i + 1) * 1000, f"{i:016x}", []) for i in range(4)]
# 目标:前 3 片与 q 相同,但第 3 片最佳匹配偏移 +1(t[4]),t[3] 是无关内容
t_hashes = [f"{i:016x}" for i in range(3)] + ["f" * 16, f"{3:016x}"]
t = [FingerprintChunk(i * 1000, (i + 1) * 1000, h, []) for i, h in enumerate(t_hashes)]
segs = find_duplicate_segments(q, t)
# q[0],q[1] 精确匹配 t[0],t[1]q[2]->t[2]q[3]->t[4](步进 2,窗口 ±1 内)
assert len(segs) >= 1
assert segs[0].query_end_ms >= 3000
# ── P0-5 / 验收:异源不误报 ───────────────────────────────────
class TestDifferentSourceNoFalsePositive:
def test_unrelated_videos_near_zero(self):
ddp = VideoDeduplicator()
# 异源:所有分片距离 >= 20
old = [_h(40 + i * 3 % 20) for i in range(6)]
new = [_h(0 + i) for i in range(6)]
existing = _video("v-old", old, duration=12.0)
chunks = [_chunk(h, i * 2, (i + 1) * 2) for i, h in enumerate(new)]
fp = _fingerprint(new, 12.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
assert result["duplicate_rate"] == 0
assert result["visual_similarity"] < 0.7
assert result["match_count"] == 0
def test_check_duplicate_returns_none_for_unrelated(self):
ddp = VideoDeduplicator()
old = [_h(40 + i) for i in range(6)]
new = [_h(i) for i in range(6)]
existing = _video("v-old", old, duration=12.0)
fp = _fingerprint(new, 12.0)
result = _check(ddp, fp, [existing])
assert result is None
# ── N=1 不回归 ────────────────────────────────────────────────
class TestSingleChunkNoRegression:
def test_single_chunk_identical_detected(self):
ddp = VideoDeduplicator()
h = _h(2)
existing = _video("v-old", [h], duration=3.0)
chunks = [_chunk(h, 0, 3000)]
fp = _fingerprint([h], 3.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
assert result["duplicate_rate"] > 0
def test_single_chunk_md5_exact_match(self):
ddp = VideoDeduplicator()
existing = _video("v-old", [_h(0)], duration=3.0)
existing.video_fingerprint["md5"] = "same"
fp = _fingerprint([_h(0)], 3.0, md5="same")
result = _check(ddp, fp, [existing])
assert result is not None
assert result["reason"] == "exact_md5_match"
# ── P1-6: 时长预过滤单位 bug ──────────────────────────────────
class TestDurationPrefilterUnit:
def test_user_scope_skips_duration_prefilter(self):
"""Issue #1702: scope=user 跨项目查重不做 ±15% 时长预过滤。
旧逻辑 duration/1000 单位 bug 先修成秒,但 ±15% 窗口与局部片段复用
根本矛盾——复用片段的两个视频时长必然不同(证据视频 20s vs 11s 差 42%),
窗口内找不到对方导致 is_duplicate 恒 False。最终口径:scope=user 全量
遍历同用户视频(与 compute_duplicate_rate 一致),不传 duration_min/max。
"""
ddp = VideoDeduplicator()
fp = _fingerprint([_h(0)], 13.5)
session_magic = MagicMock()
session_magic.query.return_value.filter.return_value.order_by.return_value.all.return_value = []
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
repo = MockRepo.return_value
repo.list_by_user.return_value = []
ddp.check_duplicate(fp, "proj1", session_magic, scope="user", user_id="u1", duration_sec=fp.duration)
args, kwargs = repo.list_by_user.call_args
# 全量查询:不带任何时长过滤参数(局部复用必须跨时长比较)
assert "duration_min" not in kwargs
assert "duration_max" not in kwargs
assert args == ("u1",) or args == ()
# ── P1-7: 颜色直方图归一化 ────────────────────────────────────
class TestHistogramNormalization:
def test_bhattacharyya_coefficient_in_unit_range(self):
"""Bhattacharyya 系数必须在 [0,1](旧 L2 + 3 通道拼接算出 ~14.9)。"""
# 3 通道拼接、每通道概率分布(Σ=1)
hist_a = [0.5, 0.5] + [0.0] * 94 + [0.5, 0.5] + [0.0] * 94 + [0.5, 0.5] + [0.0] * 94
# 长度裁剪到 96(3 通道 × 32 bins
hist_a = ([0.5, 0.5] + [0.0] * 30) * 3
hist_b = ([0.5, 0.5] + [0.0] * 30) * 3
coeff = VideoDeduplicator._bhattacharyya_coefficient(hist_a, hist_b)
assert 0.0 <= coeff <= 1.0
assert coeff > 0.99 # 完全相同 -> 1.0
def test_bhattacharyya_disjoint_hist_low(self):
hist_a = ([1.0] + [0.0] * 31) * 3
hist_b = ([0.0] * 31 + [1.0]) * 3
coeff = VideoDeduplicator._bhattacharyya_coefficient(hist_a, hist_b)
assert coeff < 0.05
# ── P1-8: temporal_coverage 量纲 ──────────────────────────────
class TestTemporalCoverageUnits:
def test_coverage_uses_milliseconds(self):
"""命中片段 6s / 视频 12s -> coverage=0.5;旧 bug 把 duration(秒)当毫秒,
covered_ms(6000)/duration(12) = 500 -> min(1.0)=1.0 误判 100% 覆盖。"""
ddp = VideoDeduplicator()
old = [_h(0) for _ in range(6)]
new = [_h(0) for _ in range(3)] + [_h(30) for _ in range(3)]
existing = _video("v-old", old, duration=12.0)
# 新视频 12s,前 6s(3 片)与 old 相同
chunks = [_chunk(h, i * 2, (i + 1) * 2) for i, h in enumerate(new)]
fp = _fingerprint(new, 12.0, chunks=chunks)
result = _rate(ddp, fp, [existing], MagicMock())
# coverage 应约 0.53 片 × 2s = 6s / 12s),duplicate_rate ≈ (0.5*0.4 + 0.5*0.6)*100 = 50
assert 30 < result["duplicate_rate"] < 70
# ── P1-9: 阈值比较统一 ────────────────────────────────────────
class TestThresholdConsistency:
def test_frame_and_segment_thresholds_same_source(self):
assert SEGMENT_MATCH_THRESHOLD == PHASH_THRESHOLD
assert VideoDeduplicator.PHASH_THRESHOLD == PHASH_THRESHOLD
# ── P2: 0 匹配也要有日志痕迹 ──────────────────────────────────
class TestZeroMatchLogging:
def test_no_match_emits_info_log(self, caplog):
ddp = VideoDeduplicator()
old = [_h(40 + i) for i in range(5)]
existing = _video("v-old", old, duration=10.0)
fp = _fingerprint([_h(i) for i in range(5)], 10.0)
with caplog.at_level(logging.INFO, logger="video_processing.dedup"):
result = _check(ddp, fp, [existing])
assert result is None
assert any("no match" in r.message for r in caplog.records)
# ── recompute 任务下载路径(#1702 连带修复:旧硬编码 key 404) ─────
class TestRecomputeDownloadPath:
"""recompute-dedup 走 check_duplicate_task,需要从 OSS 重新下载成片。
旧代码硬编码 projects/{pid}/generated/{vid}/{vid}.mp4(从不存在),
真实 key 在 file_urlgenerated/projects/{pid}/tasks/{tid}/rendered_*.mp4。
"""
def test_task_downloads_from_file_url(self):
import inspect
import video_processing.dedup as dedup_mod
source = inspect.getsource(dedup_mod.check_duplicate_task)
# 下载 key 必须来自 video.file_url
assert 'getattr(video, "file_url"' in source or "video.file_url" in source
# 旧的硬编码 key 只能作为回退存在,不能是主路径
assert "falling back to legacy key" in source
# download_file 接收的是派生 key 而非硬编码 f-string
assert "storage_service.download_file(download_key" in source
assert '/generated/{generated_video_id}/{generated_video_id}.mp4"' not in source.replace(
'download_key = f"projects/{video.project_id}/generated/{generated_video_id}/{generated_video_id}.mp4"',
"",
)
# ── check_duplicate 排除自身(#1702 连带修复:recompute 自匹配) ─────
class TestCheckDuplicateExcludesSelf:
def test_exclude_video_id_skips_self_match(self):
"""recompute 时当前视频已在候选列表:自匹配距离 0 分会让 duplicate_of
指向自己。exclude_video_id 必须跳过自身,返回真实的其他匹配或 None。
"""
ddp = VideoDeduplicator()
h = _h(0)
# 候选列表里同时放「自己」(完全相同)和一个异源视频
self_video = _video("v-self", [h], duration=10.0)
other_video = _video("v-other", [_h(40 + i) for i in range(3)], duration=10.0)
fp = _fingerprint([h], 10.0)
session = MagicMock()
session.query.return_value.filter.return_value.order_by.return_value.all.return_value = []
# 不传 exclude → 自匹配命中(错误行为复现)
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
MockRepo.return_value.list_by_project.return_value = [self_video, other_video]
result = ddp.check_duplicate(fp, "proj1", session)
assert result is not None and result["duplicate_of"] == "v-self"
# 传 exclude_video_id → 跳过自己,异源不匹配 → None
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
MockRepo.return_value.list_by_project.return_value = [self_video, other_video]
result = ddp.check_duplicate(fp, "proj1", session, exclude_video_id="v-self")
assert result is None
# 排除自己后,真实同源其他视频仍能检出
real_dup = _video("v-real", [h], duration=10.0)
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
MockRepo.return_value.list_by_project.return_value = [self_video, real_dup]
result = ddp.check_duplicate(fp, "proj1", session, exclude_video_id="v-self")
assert result is not None and result["duplicate_of"] == "v-real"
# ── 阈值 16 二次校准 + 时序抖动对齐(#1702 第二轮真实数据校准) ──────
class TestThreshold16Calibration:
"""二次校准:staging 15 个真实成片实测——同源降重对中位数距离 14、
<=16 命中 8/11=0.73;异源 13 个候选每帧全局最近邻最小距离 18、<=16
命中全 0。阈值 16 检出同源且异源零误报(>=2bit 安全裕度)。"""
def test_threshold_calibrated_to_16(self):
assert PHASH_THRESHOLD == 16
@staticmethod
def _variant(phash: str, d: int) -> str:
"""在 phash 基础上翻转恰好 d 个低位 bit → 与原哈希汉明距离恰为 d。"""
v = int(phash, 16)
for b in range(d):
v ^= 1 << b
return f"{v:016x}"
def test_distance_18_unrelated_not_matched(self):
"""距离 18(异源实测最小最近邻距离)不判匹配,距离 16 判匹配。"""
ddp = VideoDeduplicator()
# 多样化 base(相邻帧各不相同,避免黑屏过滤器)
base = [_h(i + 4) for i in range(8)]
near = [self._variant(h, 16) for h in base] # 同源降重:每帧距离恰 16
far = [self._variant(h, 18) for h in base] # 异源边界:每帧距离恰 18
fp_near = _fingerprint(near, 8.0, chunks=[_chunk(h, i, i + 1) for i, h in enumerate(near)])
fp_far = _fingerprint(far, 8.0, chunks=[_chunk(h, i, i + 1) for i, h in enumerate(far)])
r_near = _rate(ddp, fp_near, [_video("v-base", base, duration=8.0)])
r_far = _rate(ddp, fp_far, [_video("v-base", base, duration=8.0)])
assert r_near["duplicate_rate"] > 0, "距离16的同源降重对必须检出"
assert r_far["duplicate_rate"] == 0.0, "距离18的异源对不得误报"
assert r_far["match_count"] == 0
def test_deduped_pair_frame_match_rate_over_threshold(self):
"""真实场景比例:11 帧中 8 帧距离 <=160.73 >= 0.7),
其余 3 帧异源距离(>=18)——frame_match_rate 必须过 0.7 门槛。"""
ddp = VideoDeduplicator()
base = [_h(i + 4) for i in range(11)]
near = [self._variant(h, 14) for h in base[:8]] # 中位数 14 的同源降重帧
# 异源帧用完全不同前缀(与 base 距离 >=30
far = [_h(52 + i) for i in range(3)]
query = near + far
fp = _fingerprint(query, 11.0, chunks=[_chunk(h, i, i + 1) for i, h in enumerate(query)])
r = _rate(ddp, fp, [_video("v-base", base, duration=11.0)])
# frame_match_rate=8/11=0.73、时序片段覆盖 ~0.73
# → duplicate_rate = 0.4*0.73+0.6*0.73 ≈ 73%(空直方图回退下 fusion=0.6965
# 略低于 is_duplicate 的 0.70 判定阈值,故此处断言查重率而非 match_count
# 真实视频带颜色直方图时 fusion≈0.80staging A-C 实测 is_duplicate=True
assert r["duplicate_rate"] >= 70.0
class TestTemporalJitterAlignment:
"""时序对齐允许目标索引正/反向 ±(neighbor_window+1) 抖动。
密集 1s 采样下相邻帧 pHash 接近,全局最近邻会在目标相邻帧间
正负 1 跳变(场景切割/取帧错位/局部倒退);旧逻辑只允许正向
delta,把同源连续匹配拆碎,min_consecutive 门槛够不上而漏检。
"""
def test_backward_jitter_keeps_run_continuous(self):
"""匹配目标索引序列 0,1,2,1,2,3(含一次 -1 倒退)应保持同一 run。"""
from video_processing.dedup import find_duplicate_segments
# 构造 target 相邻帧 pHash 相同(距离0),query 帧的最近邻在
# target[1]/target[2] 之间抖动;全部 <= 阈值
t_hash = _h(0)
other = _h(40)
# target: 帧0-3 相同场景,帧4+ 异源
t_chunks = [_chunk(t_hash, i, i + 1) for i in range(4)] + [_chunk(other, i, i + 1) for i in range(4, 8)]
# query 6 帧同场景(最近邻会落到 target 0~3,索引可正可负)
q_chunks = [_chunk(t_hash, i, i + 1) for i in range(6)]
segments = find_duplicate_segments(q_chunks, t_chunks)
assert segments, "含 ±1 时序抖动的连续匹配必须形成片段"
# 6 帧匹配 >= min_consecutive(min(5,max(2,6//2))=5),报为一个片段
assert len(segments) == 1
seg = segments[0]
assert seg.query_end_ms - seg.query_start_ms >= 5000
def test_large_backward_jump_breaks_run(self):
"""目标索引倒退 > neighbor_window+1(如从 5 跳回 0)不属于抖动,
不桥接为同一片段;孤立短匹配 < min_consecutive 不报片段。"""
from video_processing.dedup import find_duplicate_segments
# 异源段:9-bit 不重叠段(相邻段隔 3 bit),跨段距离 18~24 > 阈值 16
def _bit_seg(start):
bits = ["0"] * 64
for b in range(9):
bits[start + b] = "1"
return f"{int(''.join(bits), 2):016x}"
t_hash = _bit_seg(0) # 复用场景:bit 0-8
t_other = [_bit_seg(22 + 4 * i) for i in range(4)] # target 异源段
q_other = [_bit_seg(40 + 4 * i) for i in range(3)] # query 异源段
# target: 帧0 同场景;帧1-4 异源;帧5-6 同场景
t_chunks = (
[_chunk(t_hash, 0, 1)]
+ [_chunk(t_other[i - 1], i, i + 1) for i in range(1, 5)]
+ [_chunk(t_hash, i, i + 1) for i in range(5, 7)]
)
# query: 帧0 匹配 target[0];帧1-3 异源(与 target 任何帧距离 >16);帧4-5 匹配 target[5,6]
q_chunks = (
[_chunk(t_hash, 0, 1)]
+ [_chunk(q_other[i - 1], i, i + 1) for i in range(1, 4)]
+ [_chunk(t_hash, i, i + 1) for i in range(4, 6)]
)
segments = find_duplicate_segments(q_chunks, t_chunks)
# 两段各 1、2 帧 < min_consecutive=5 → 不报片段(大跳跃不桥接)
assert segments == []
+6 -6
View File
@@ -358,11 +358,11 @@ class TestVideoDeduplicatorCheckDuplicate:
finally:
self._restore_repo(mod, orig)
def test_highest_score_match_returned(self, deduplicator, mock_session):
"""Issue #1702: 遍历所有候选取融合分最高者(旧逻辑首个过阈即返回)。"""
# vid-1: 距离=1 bit0x03 XOR 0x01 = 0x02 → 1 bit),通过阈值
def test_first_match_returned(self, deduplicator, mock_session):
"""返回第一个通过阈值的匹配(非最优匹配)。"""
# vid-1: 距离=2 bits0x03 XOR 0x01 = 0x02 → 1 bit),通过阈值
vid1 = self._make_existing_video("vid-1", "md5_1", phashes=["0000000000000003"])
# vid-2: 距离=0 bits(完全匹配),融合分更高
# vid-2: 距离=0 bits(完全匹配)
vid2 = self._make_existing_video("vid-2", "md5_2", phashes=["0000000000000001"])
mock_repo = MagicMock()
@@ -380,8 +380,8 @@ class TestVideoDeduplicatorCheckDuplicate:
try:
result = deduplicator.check_duplicate(fingerprint, "proj-1", mock_session)
assert result is not None
# 两个候选都过阈,返回融合分最高的 vid-2(距离 0 < 1
assert result["duplicate_of"] == "vid-2"
# 返回第一个通过阈值的匹配(vid-1 距离=1 < 10
assert result["duplicate_of"] == "vid-1"
finally:
self._restore_repo(mod, orig)
+7 -10
View File
@@ -185,14 +185,11 @@ class TestBhattacharyyaCoefficient:
"""_bhattacharyya_coefficient Bhattacharyya 系数测试."""
def test_identical_histograms(self):
"""完全相同的直方图系数为1.0(#1702:按 Σ 归一,概率分布语义)。"""
hist = [0.5, 0.5, 0.0, 0.0] # Σ=1 的概率分布
"""完全相同的直方图系数为1.0."""
hist = [0.5, 0.5, 0.0, 0.3]
bc = VideoDeduplicator._bhattacharyya_coefficient(hist, hist)
assert bc == pytest.approx(1.0)
# 非归一化输入也归一到 1.0(三通道拼接 Σ=3 的等价情形)
hist3 = [0.5, 0.5, 0.0, 0.3]
bc3 = VideoDeduplicator._bhattacharyya_coefficient(hist3, hist3)
assert bc3 == pytest.approx(1.0)
# Σ √(a[i]*a[i]) = Σ a[i] = 1.0 (normalized)
assert bc == pytest.approx(sum(h for h in hist))
def test_zero_histograms(self):
"""全零直方图系数为0."""
@@ -205,10 +202,10 @@ class TestBhattacharyyaCoefficient:
assert bc == pytest.approx(0.0)
def test_different_lengths(self):
"""不同长度直方图取最小长度对齐,并按各自总量归一(#1702 概率分布语义)。"""
# 对齐到前 2 维:coeff = 2norm = √(Σa·Σb) = √(2·2) = 2 → 1.0
"""不同长度直方图取最小长度对齐."""
bc = VideoDeduplicator._bhattacharyya_coefficient([1.0, 1.0, 0.0, 0.0], [1.0, 1.0])
assert bc == pytest.approx(1.0)
# 对齐到前2维: √(1*1) + √(1*1) = 2.0
assert bc == pytest.approx(2.0)
def test_known_value(self):
"""已知值验证."""
+23 -26
View File
@@ -103,7 +103,6 @@ from video_processing.dedup import ( # noqa: E402
MIN_CONSECUTIVE_MATCHES,
MIN_KEYFRAME_INTERVAL_SEC,
MIN_KEYFRAMES,
PHASH_THRESHOLD,
PHASH_WEIGHT,
SCENE_CHANGE_THRESHOLD,
SEGMENT_MATCH_THRESHOLD,
@@ -270,17 +269,22 @@ class TestFindDuplicateSegments:
注意:使用不同的 hash 对,确保后半部分帧距离 > 阈值。
"""
same_hash = "aaaaaaaaaaaaaaaa"
# 4 帧匹配,后面 6 帧用与匹配哈希距离 32 的不匹配哈希(> PHASH_THRESHOLD=16
nomatch_hash = "cccccccccccccccc" # hamming(aaaa, cccc)=32
# 4 帧匹配,后面 6 帧各自不同(在 query 和 target 中使用不同 hash
chunks_a = [_make_chunk(i * 1000, (i + 1) * 1000, same_hash) for i in range(4)] + [
_make_chunk(i * 1000, (i + 1) * 1000, nomatch_hash) for i in range(4, 10)
_make_chunk(i * 1000, (i + 1) * 1000, "bbbbbbbbbbbbbbbb") for i in range(4, 10)
]
chunks_b = [_make_chunk(i * 1000, (i + 1) * 1000, same_hash) for i in range(4)] + [
_make_chunk(i * 1000, (i + 1) * 1000, nomatch_hash) for i in range(4, 10)
_make_chunk(i * 1000, (i + 1) * 1000, "cccccccccccccccc") for i in range(4, 10)
]
# hamming(aaaa..., cccc...) = 32 > PHASH_THRESHOLD(16),后半段不匹配;
# 前 4 帧匹配 < min_consecutive=5,不形成片段
# hamming("bbbb...", "cccc...") should be > 8 (SEGMENT_MATCH_THRESHOLD)
# b=1011, c=1100 → 4 bits differ per hex digit × 16 digits = 64 bits total? No...
# Actually: hamming_distance("bbbbbbbbbbbbbbbb", "cccccccccccccccc")
# b=0xb=1011, c=0xc=1100 → XOR=0111=0x7 → 3 bits per digit × 16 = 48
# That's > 8 so won't match
segments = find_duplicate_segments(chunks_a, chunks_b)
# 只有 4 帧匹配(< min_consecutive=5),所以不报告
assert segments == []
def test_max_gap_behavior(self):
@@ -289,12 +293,10 @@ class TestFindDuplicateSegments:
关键:间隙帧必须在 query 和 target 中使用不同 hash,使其真正不匹配。
"""
match_hash = "aaaaaaaaaaaaaaaa"
# 间隙/尾部哈希与 match_hash 及彼此之间汉明距离均 >64 (> PHASH_THRESHOLD=16)
# 确保在 ±(neighbor_window+1) 时序抖动对齐窗口内也不会误匹配
gap_hash_a = "ffffffffffffffff" # hamming(a,f)=128
gap_hash_b = "9999999999999999" # hamming(a,9)=128, hamming(f,9)=128
tail_hash_a = "7777777777777777" # hamming(a,7)=192
tail_hash_b = "1111111111111111" # hamming(a,1)=192, hamming(7,1)=128
gap_hash_a = "bbbbbbbbbbbbbbbb" # query 端
gap_hash_b = "cccccccccccccccc" # target 端(与 query 端距离 > 8
tail_hash_a = "dddddddddddddddd"
tail_hash_b = "eeeeeeeeeeeeeeee"
# 5 帧匹配, 1 帧间隙, 3 帧匹配, 5 帧不匹配
hashes_a = [match_hash] * 5 + [gap_hash_a] + [match_hash] * 3 + [tail_hash_a] * 5
@@ -316,10 +318,10 @@ class TestFindDuplicateSegments:
def test_max_gap_exceeded(self):
"""间隙超过 max_gap → 分成两段."""
match_hash = "aaaaaaaaaaaaaaaa"
gap_hash_a = "ffffffffffffffff" # hamming(a,f)=128
gap_hash_b = "9999999999999999" # hamming(a,9)=128
tail_hash_a = "7777777777777777" # hamming(a,7)=192
tail_hash_b = "1111111111111111" # hamming(a,1)=192
gap_hash_a = "bbbbbbbbbbbbbbbb"
gap_hash_b = "cccccccccccccccc"
tail_hash_a = "dddddddddddddddd"
tail_hash_b = "eeeeeeeeeeeeeeee"
# 5 帧匹配, 3 帧间隙 (> max_gap=2), 5 帧匹配, 5 帧不匹配
hashes_a = [match_hash] * 5 + [gap_hash_a] * 3 + [match_hash] * 5 + [tail_hash_a] * 5
@@ -482,10 +484,8 @@ class TestBackwardCompatibility:
chunks_b = [{"phash_binary": "aaaaaaaaaaaaaaaa", "start_time_ms": 0, "end_time_ms": 5000}]
segments = find_duplicate_segments(chunks_a, chunks_b)
# Issue #1702: 自适应门槛 min(5, max(2, 1//2))=21 帧不成段;
# N=1 的检出由 _evaluate_candidate 匹配帧回退兜底(见 test_dedup_1702)。
# 这里只要求不崩溃。
assert isinstance(segments, list)
# 1 帧 < min_consecutive=5,不会报重复
assert segments == []
# ── TestConstants ───────────────────────────────────────────────
@@ -495,11 +495,8 @@ class TestConstants:
"""常量值验证 — 使用已在模块顶部导入的常量,避免重新 import."""
def test_segment_match_threshold(self):
# Issue #1702 二次校准:阈值经 staging 真实数据两轮回归——
# 第一轮同源 4/11、异源 min=24 定 12;第二轮扩样本(15 个真实成片)
# 同源降重对中位数距离 14、<=16 命中 8/11=0.73,异源 13 个候选
# <=16 命中全 0、最近邻最小距离 18 → 校准为 16。
assert SEGMENT_MATCH_THRESHOLD == PHASH_THRESHOLD == 16
# 从已导入的 find_duplicate_segments 默认参数间接验证
assert SEGMENT_MATCH_THRESHOLD == 8
def test_min_consecutive_matches(self):
assert MIN_CONSECUTIVE_MATCHES == 5
+8 -40
View File
@@ -132,14 +132,9 @@ class TestCheckDuplicateScopeUser:
class TestDurationPrefilter:
"""Issue #1702: scope=user 跨项目查重不做时长预过滤
"""test_duration_prefilter:时长 ±15% 过滤."""
局部片段复用的两个视频时长必然不同(证据视频 20s vs 11s,差 42%),
旧的 ±15% 窗口会让同源视频互相不可见 → is_duplicate 恒 False。
全量遍历同用户视频,异源视频由 fusion/temporal_coverage 阈值天然过滤。
"""
def test_user_scope_no_duration_filter(self):
def test_duration_prefilter_passes_correct_range(self):
from video_processing.dedup import VideoDeduplicator
deduplicator = VideoDeduplicator()
@@ -158,13 +153,12 @@ class TestDurationPrefilter:
duration_sec=30.0,
)
# scope=user 全量遍历:位置参数只传 user_id,kwargs 不含时长过滤
# Should pass duration_min=25.5, duration_max=34.5 (30 ± 15%)
call_args = mock_repo.list_by_user.call_args
assert call_args[0] == ("user1",)
assert "duration_min" not in call_args[1]
assert "duration_max" not in call_args[1]
assert call_args[1]["duration_min"] == pytest.approx(25.5, abs=0.1)
assert call_args[1]["duration_max"] == pytest.approx(34.5, abs=0.1)
def test_user_scope_no_duration_filter_when_zero(self):
def test_no_duration_prefilter_when_zero(self):
from video_processing.dedup import VideoDeduplicator
deduplicator = VideoDeduplicator()
@@ -184,34 +178,8 @@ class TestDurationPrefilter:
)
call_args = mock_repo.list_by_user.call_args
assert "duration_min" not in call_args[1]
assert "duration_max" not in call_args[1]
def test_project_scope_also_no_duration_filter(self):
"""scope=project 走 list_by_project,本来就不做时长过滤。"""
from video_processing.dedup import VideoDeduplicator
deduplicator = VideoDeduplicator()
fingerprint = _make_fingerprint(duration_ms=30000)
session = MagicMock()
with patch("video_processing.dedup.SQLAlchemyGeneratedVideoRepository") as MockRepo:
mock_repo = MockRepo.return_value
mock_repo.list_by_project.return_value = []
deduplicator.check_duplicate(
fingerprint,
"proj1",
session,
scope="project",
user_id="user1",
duration_sec=30.0,
)
mock_repo.list_by_project.assert_called_once()
call_args = mock_repo.list_by_project.call_args
assert call_args[0] == ("proj1",)
assert "duration_min" not in call_args[1]
assert "duration_max" not in call_args[1]
assert call_args[1]["duration_min"] == 0
assert call_args[1]["duration_max"] == 0
class TestComputeDuplicateRateFormula:
+16 -26
View File
@@ -3,7 +3,7 @@
覆盖:
- 分片策略:60秒视频 → 30片,120秒视频 → 24片
- VideoFingerprint.to_chunk_models() 输出正确
- _save_fingerprint_chunks 替换语义(Issue #1702:重算时先删旧分片再写入
- _save_fingerprint_chunks 幂等性(已有数据跳过
- to_dict() 向后兼容
"""
@@ -169,15 +169,11 @@ class TestVideoFingerprintToChunkModels:
assert models == []
class TestSaveFingerprintChunksReplace:
"""测试 _save_fingerprint_chunks 替换语义(Issue #1702)。
class TestSaveFingerprintChunksIdempotent:
"""测试 _save_fingerprint_chunks 幂等性。"""
重算查重时指纹算法已升级(中心裁剪 + 新采样/阈值),旧分片必须先删除
再写入新分片,否则 recompute-dedup 永远读到旧指纹、修复对存量视频不生效。
"""
def test_save_replaces_existing(self):
"""已有分片数据时:先删除旧分片,再写入新分片。"""
def test_save_skips_existing(self):
"""已有分片数据时跳过写入。"""
fp = VideoFingerprint(
md5="abc",
keyframe_phashes=["a1b2"],
@@ -190,22 +186,16 @@ class TestSaveFingerprintChunksReplace:
)
session = MagicMock()
# Mock: 删除旧分片返回 3(旧算法留下的 3 条分片
session.query.return_value.filter.return_value.delete.return_value = 3
# Mock: 已有 1 条分片数据
session.query.return_value.filter.return_value.count.return_value = 1
_save_fingerprint_chunks(fp, video_id="v1", project_id="p1", user_id="u1", session=session)
# 必须先执行删除
session.query.return_value.filter.return_value.delete.assert_called_once()
# 新分片必须写入
session.bulk_save_objects.assert_called_once()
saved_models = session.bulk_save_objects.call_args[0][0]
assert len(saved_models) == 1
assert saved_models[0].video_id == "v1"
assert saved_models[0].phash_binary == "a1b2"
# bulk_save_objects 不应被调用
session.bulk_save_objects.assert_not_called()
def test_save_writes_new(self):
"""分片时直接写入。"""
"""无分片数据时写入。"""
fp = VideoFingerprint(
md5="abc",
keyframe_phashes=["a1b2"],
@@ -218,12 +208,12 @@ class TestSaveFingerprintChunksReplace:
)
session = MagicMock()
# Mock: 无分片
session.query.return_value.filter.return_value.delete.return_value = 0
# Mock: 无分片数据
session.query.return_value.filter.return_value.count.return_value = 0
_save_fingerprint_chunks(fp, video_id="v1", project_id="p1", user_id="u1", session=session)
session.query.return_value.filter.return_value.delete.assert_called_once()
# bulk_save_objects 应被调用一次
session.bulk_save_objects.assert_called_once()
saved_models = session.bulk_save_objects.call_args[0][0]
assert len(saved_models) == 1
@@ -231,7 +221,7 @@ class TestSaveFingerprintChunksReplace:
assert saved_models[0].phash_binary == "a1b2"
def test_save_skips_no_chunks(self):
"""指纹无 chunks 时跳过(不删不写)"""
"""指纹无 chunks 时跳过。"""
fp = VideoFingerprint(
md5="abc",
keyframe_phashes=[],
@@ -242,11 +232,11 @@ class TestSaveFingerprintChunksReplace:
)
session = MagicMock()
session.query.return_value.filter.return_value.count.return_value = 0
_save_fingerprint_chunks(fp, video_id="v1", project_id="p1", user_id="u1", session=session)
# 无 chunks:不查询、不删除、不写入
session.query.assert_not_called()
# bulk_save_objects 不应被调用
session.bulk_save_objects.assert_not_called()
@@ -102,7 +102,6 @@ from video_processing.dedup import ( # noqa: E402
DUPLICATE_THRESHOLD,
HISTOGRAM_WEIGHT,
MATCH_RATIO_THRESHOLD,
PHASH_THRESHOLD,
PHASH_WEIGHT,
VideoDeduplicator,
)
@@ -129,17 +128,11 @@ _ZERO_HIST = [0.0] * 96 # 全黑视频的全零直方图(有效数据)
class TestThresholdCalibration:
"""pHash 阈值校准(#1658 收紧到 8,#1702 两轮真实数据重校准 12→16)。
"""pHash 阈值由 10 收紧到 8Issue #1658)。"""
#1702 第一轮 staging 离线实验:同帧两次 2-5% 随机裁剪距离 4~10;同源成片
(密集 1s 采样)<=12 命中 4/11、异源成片最小距离 24 → 初定 12。
#1702 第二轮(证据视频 B->A 仍漏检)扩样本到该用户 15 个真实成片实测:
同源降重对中位数距离 14、<=16 命中 8/11=0.73;异源 13 个候选 <=16 命中
全 0、每帧全局最近邻最小距离 18 → 校准为 16(与异源仍有 >=2bit 裕度)。
"""
def test_phash_threshold_is_calibrated(self):
assert VideoDeduplicator.PHASH_THRESHOLD == PHASH_THRESHOLD == 16
def test_phash_threshold_is_8(self):
"""PHASH_THRESHOLD 必须为 8(旧值 10 会放过 8~9 汉明距离的不同视频)。"""
assert VideoDeduplicator.PHASH_THRESHOLD == 8
def test_match_ratio_threshold_constant(self):
assert MATCH_RATIO_THRESHOLD == 0.7
@@ -151,22 +144,22 @@ class TestThresholdCalibration:
assert PHASH_WEIGHT == 0.7
assert HISTOGRAM_WEIGHT == 0.3
def test_threshold_matching_semantics(self):
"""阈值比较统一为 <=(帧匹配与片段匹配同一口径)
def test_threshold_tightening_excludes_distance_8_and_9(self):
"""距离 8、9 的帧:旧阈值 10 下算匹配,新阈值 8 下不算匹配
场景:5 个关键帧距离为 [10, 14, 16, 18, 26]。
- <=16#1702 二次校准阈值):3 帧匹配 → 0.6 < 0.7,被帧比例门槛
拦截(异源安全边界:真实数据异源最近邻最小距离 18,<=16 命中 0
- 距离正好 16 的同源降重帧应算匹配(< 与 <= 口径统一)
场景:5 个关键帧距离为 [7, 7, 7, 9, 9]。
- 旧阈值 105 帧全部 < 10 → match_ratio = 1.0(误放过)
- 新阈值 8:仅 3 帧 < 8 → match_ratio = 0.6 < 0.7(正确跳过
"""
distances = [10, 14, 16, 18, 26]
matched = sum(1 for d in distances if d <= VideoDeduplicator.PHASH_THRESHOLD)
assert matched == 3
assert matched / len(distances) == 0.6
assert matched / len(distances) < MATCH_RATIO_THRESHOLD
distances = [7, 7, 7, 9, 9]
# 异源安全边界(实测最小距离 18)及以上绝不匹配
assert not any(d <= VideoDeduplicator.PHASH_THRESHOLD for d in (18, 24, 26, 30))
matched_old = sum(1 for d in distances if d < 10)
assert matched_old == 5 # 旧行为:全匹配 → 误判风险
matched_new = sum(1 for d in distances if d < VideoDeduplicator.PHASH_THRESHOLD)
assert matched_new == 3
assert matched_new / len(distances) == 0.6
assert matched_new / len(distances) < MATCH_RATIO_THRESHOLD # 被帧比例门槛拦截
# ── TestComputeFusionScore:统一融合得分方法 ────────────────────
@@ -1,315 +0,0 @@
"""Issue #1709 任务容错:孤儿任务恢复 + 429 限流结构化提示。
覆盖:
1. 仓储层:count_running_by_user/count_running_total 计数正确(预览/正式任务都计入)
2. 仓储层:estimate_avg_duration_seconds 耗时估算(有历史/无历史)
3. 限流核心:build_rate_limit_detail 返回结构化 code/message/排队数/预计等待
4. worker 侧:cleanup_stale_running/pending 核心函数——中断任务被重置为 failed
且原因写明(容器重启/超时中断),正常任务不受影响
"""
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "worker"))
# 预注入 mock worker_app.db,防止真实数据库连接初始化(与其他 worker 测试同模式)
_mock_db = MagicMock()
_mock_db.SessionLocal = MagicMock()
sys.modules.setdefault("worker_app.db", _mock_db)
from app.core import task_enqueue # noqa: E402
from sqlalchemy import create_engine, text # noqa: E402
from sqlalchemy.orm import sessionmaker # noqa: E402
from worker_app.tasks import _startup # noqa: E402
from packages.adapters.sqlalchemy_impl.generation_task_repository import ( # noqa: E402
SQLAlchemyGenerationTaskRepository,
)
from packages.adapters.sqlalchemy_impl.models import Base # noqa: E402
from packages.domain import GenerationTask, GenerationTaskStatus # noqa: E402
def _repository():
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
return SQLAlchemyGenerationTaskRepository(session), session, engine
def _make_task(**kwargs) -> GenerationTask:
defaults = dict(
project_id="proj-1",
asset_library_id="lib-1",
created_by_user_id="user-1",
)
defaults.update(kwargs)
return GenerationTask.create(**defaults)
def _age_task(engine, task_id, *, updated_minutes=None, created_minutes=None):
"""用 SQL 直接把 updated_at/created_at 改到过去(模拟孤儿任务)。"""
sets, params = [], {"id": task_id}
if updated_minutes is not None:
sets.append("updated_at = :uts")
params["uts"] = datetime.now(timezone.utc) - timedelta(minutes=updated_minutes)
if created_minutes is not None:
sets.append("created_at = :cts")
params["cts"] = datetime.now(timezone.utc) - timedelta(minutes=created_minutes)
with engine.connect() as conn:
conn.execute(text(f"UPDATE generation_tasks SET {', '.join(sets)} WHERE id = :id"), params)
conn.commit()
# ---------------------------------------------------------------------------
# 1. running 计数(限流"渲染中"数量)
# ---------------------------------------------------------------------------
def test_count_running_by_user_mix_statuses():
"""count_running_by_user 只统计该用户 running,不含 pending/completed/failed。"""
repo, _, _ = _repository()
t1 = _make_task(project_id="p1")
repo.create(t1) # pending
t2 = _make_task(project_id="p2")
repo.create(t2)
t2.mark_processing()
repo.update(t2)
t3 = _make_task(project_id="p3")
repo.create(t3)
t3.mark_processing()
repo.update(t3)
t4 = _make_task(project_id="p4")
repo.create(t4)
t4.mark_processing()
repo.update(t4)
t4.mark_completed()
repo.update(t4)
t5 = _make_task(project_id="p5", created_by_user_id="user-2")
repo.create(t5)
t5.mark_processing()
repo.update(t5)
assert repo.count_running_by_user("user-1") == 2
assert repo.count_running_by_user("user-2") == 1
assert repo.count_running_total() == 3
def test_count_running_total_empty():
repo, _, _ = _repository()
assert repo.count_running_total() == 0
assert repo.count_running_by_user("nobody") == 0
def test_preview_tasks_counted_in_running():
"""预览任务(is_preview=True,工单实测卡 80% 的那种)同样计入 running。"""
repo, _, _ = _repository()
t = _make_task(is_preview=True)
repo.create(t)
t.mark_processing()
repo.update(t)
assert repo.count_running_by_user("user-1") == 1
assert repo.count_running_total() == 1
# ---------------------------------------------------------------------------
# 2. 平均耗时估算(429 等待预估依据)
# ---------------------------------------------------------------------------
def _complete_task(repo, engine, task, duration_seconds: float):
repo.create(task)
task.mark_processing()
repo.update(task)
task.mark_completed()
repo.update(task)
now = datetime.now(timezone.utc)
with engine.connect() as conn:
conn.execute(
text("UPDATE generation_tasks SET started_at = :s, completed_at = :c WHERE id = :id"),
{"s": now - timedelta(seconds=duration_seconds), "c": now, "id": task.id},
)
conn.commit()
def test_estimate_avg_duration_with_history():
"""有历史完成任务时返回平均耗时(秒)。"""
repo, _, engine = _repository()
_complete_task(repo, engine, _make_task(project_id="p1"), 60.0)
_complete_task(repo, engine, _make_task(project_id="p2"), 180.0)
avg = repo.estimate_avg_duration_seconds(default_seconds=120.0)
assert 119.0 < avg < 121.0 # (60+180)/2 = 120
def test_estimate_avg_duration_no_history_returns_default():
"""无历史数据时返回默认值。"""
repo, _, _ = _repository()
assert repo.estimate_avg_duration_seconds(default_seconds=90.0) == 90.0
# ---------------------------------------------------------------------------
# 3. build_rate_limit_detail 结构化提示(前端区分"排队"与"创建失败"
# ---------------------------------------------------------------------------
def test_user_rate_limit_detail_structure():
"""429 用户限流:返回 USER_QUEUE_FULL + 排队/渲染数 + 预计等待。"""
repo, _, _ = _repository()
for i in range(2): # 2 个渲染中
t = _make_task(project_id=f"rp{i}")
repo.create(t)
t.mark_processing()
repo.update(t)
exc = task_enqueue.UserPendingLimitExceeded(user_id="user-1", pending_count=3, limit=3)
detail = task_enqueue.build_rate_limit_detail(exc, repo, scope="user")
assert detail["code"] == task_enqueue.ERROR_CODE_USER_QUEUE_FULL
assert detail["queued_count"] == 3
assert detail["running_count"] == 2
assert detail["limit"] == 3
assert detail["estimated_wait_seconds"] > 0
assert "排队" in detail["message"]
assert "user-1" not in detail["message"] # 不泄露内部 ID
def test_global_rate_limit_detail_structure():
"""503 全局繁忙:返回 SYSTEM_QUEUE_FULL。"""
repo, _, _ = _repository()
exc = task_enqueue.GlobalQueueFull(pending_count=20, limit=20)
detail = task_enqueue.build_rate_limit_detail(exc, repo, scope="global")
assert detail["code"] == task_enqueue.ERROR_CODE_SYSTEM_QUEUE_FULL
assert detail["queued_count"] == 20
assert detail["limit"] == 20
assert detail["estimated_wait_seconds"] > 0
assert "系统繁忙" in detail["message"]
def test_wait_estimate_uses_concurrency():
"""等待预估:排队 8 个 / 并发 4 = 2 批 × 平均耗时。"""
class FakeRepo:
def estimate_avg_duration_seconds(self, limit=20, default_seconds=120.0):
return 100.0
wait = task_enqueue._estimate_wait_seconds(8, FakeRepo())
assert wait == 200 # ceil(8/4)=2 批 × 100 秒
def test_wait_estimate_repo_without_methods_uses_default():
"""仓储没有新方法(旧 mock/鸭子类型)时用默认 120 秒兜底,不抛错。"""
class LegacyRepo:
"""只实现旧接口的仓储(模拟未升级的调用方)。"""
def count_pending_total(self):
return 0
wait = task_enqueue._estimate_wait_seconds(4, LegacyRepo())
assert wait == 120 # ceil(4/4)=1 批 × 120 默认
def test_rate_limit_detail_running_count_falls_back_to_zero():
"""仓储不支持 running 计数时,running_count 优雅降级为 0。"""
class LegacyRepo:
def count_pending_total(self):
return 0
exc = task_enqueue.GlobalQueueFull(pending_count=20, limit=20)
detail = task_enqueue.build_rate_limit_detail(exc, LegacyRepo(), scope="global")
assert detail["running_count"] == 0
assert detail["code"] == task_enqueue.ERROR_CODE_SYSTEM_QUEUE_FULL
# ---------------------------------------------------------------------------
# 4. worker 清理核心:中断任务被重置(worker 重启/超时恢复)
# ---------------------------------------------------------------------------
def test_worker_cleanup_resets_interrupted_running_task():
"""模拟 worker 重启:running 超 20 分钟无更新的任务被重置为 failed,原因写明。"""
repo, _, engine = _repository()
t = _make_task(is_preview=True) # 预览任务
repo.create(t)
t.mark_processing() # running
repo.update(t)
_age_task(engine, t.id, updated_minutes=25) # 25 分钟无进度更新
cleaned = _startup.cleanup_stale_running_with_session(repo, 20)
assert cleaned == 1
saved = repo.get(t.id)
assert saved.status == GenerationTaskStatus.FAILED
assert "中断" in saved.error_message
assert saved.error_info.get("error_type") == "WorkerInterrupted"
assert saved.completed_at is not None
def test_worker_cleanup_keeps_healthy_running_task():
"""正常运行中(5 分钟前有更新)的任务不被误杀。"""
repo, _, engine = _repository()
t = _make_task()
repo.create(t)
t.mark_processing()
repo.update(t)
_age_task(engine, t.id, updated_minutes=5)
assert _startup.cleanup_stale_running_with_session(repo, 20) == 0
assert repo.get(t.id).status == GenerationTaskStatus.RUNNING
def test_worker_cleanup_resets_stale_pending_task():
"""卡 pending 超 15 分钟(worker 停止消费)的任务被重置,释放限流名额。"""
repo, _, engine = _repository()
t = _make_task(is_preview=True)
repo.create(t) # 一直 pending
_age_task(engine, t.id, created_minutes=20)
cleaned = _startup.cleanup_stale_pending_with_session(repo, 15)
assert cleaned == 1
saved = repo.get(t.id)
assert saved.status == GenerationTaskStatus.FAILED
assert saved.error_info.get("error_type") == "PendingTimeout"
# 释放名额后 pending 计数归零,新请求不再被 429 误伤
assert repo.count_pending_total() == 0
def test_worker_cleanup_pending_keeps_recent():
"""刚创建 3 分钟的 pending 任务不清理。"""
repo, _, engine = _repository()
t = _make_task()
repo.create(t)
_age_task(engine, t.id, created_minutes=3)
assert _startup.cleanup_stale_pending_with_session(repo, 15) == 0
assert repo.get(t.id).status == GenerationTaskStatus.PENDING
def test_worker_cleanup_multiple_orphans_all_reset():
"""3 个卡死 running 任务(工单实测:3 个预览卡 80% 超 10 小时)全部恢复。"""
repo, _, engine = _repository()
ids = []
for i in range(3):
t = _make_task(project_id=f"p{i}", is_preview=True)
repo.create(t)
t.mark_processing()
repo.update(t)
_age_task(engine, t.id, updated_minutes=600) # 10 小时
ids.append(t.id)
cleaned = _startup.cleanup_stale_running_with_session(repo, 20)
assert cleaned == 3
for tid in ids:
assert repo.get(tid).status == GenerationTaskStatus.FAILED