Files
short-drama-agent-front/src/features/production/useQuality.ts
T

326 lines
18 KiB
TypeScript

import { videoOperationAllowed } from './video-permissions'
import { computed, onScopeDispose, watch } from 'vue'
import { useWorkflowExecution } from '../workflows/execution'
import { isQualityBatchResult } from './quality'
import { projectsApi } from '../projects/api'
import { hasRunningWorkflow } from '../workflows/selectors'
import { getOperation, runOperation } from '../workflows/operations'
import { productionApi } from './api'
import { qualityApi } from './quality-api'
import {
isVisualValidation,
clearVideoQualification,
clearVideoConflict,
qualityKey,
qualitySession,
qualityTargets,
validQualityInput
} from './quality'
import type { QualityAction, QualityInput, QualityReceipt, QualityTarget, RepairAttempt } from './quality.types'
/** 校验有限修复回执的每轮结论,避免结构缺失时误报成功。 */
function validAttempts(attempts: RepairAttempt[]) {
return (
Array.isArray(attempts) &&
attempts.length > 0 &&
attempts.every(
item =>
typeof item.keyframeId === 'string' && typeof item.passed === 'boolean' && Array.isArray(item.issues)
)
)
}
/**
* 只读预检后显式启动质量操作,按原目标保存回执与后台状态。
* @param props 当前项目、目标和阻断状态
* @param visible 弹窗是否仍可见
* @param changed 原项目资产刷新通知
* @param started 后台启动编号通知
* @returns 质量会话、任务状态与执行入口
*/
export function useQuality(
props: { projectId: string; target: QualityTarget | null; disabled: boolean },
visible: () => boolean,
changed: () => void,
started: (executionId: string) => void = () => {}
) {
/** 原项目与目标共同隔离结果。 */
const key = computed(() => qualityKey(props.projectId, props.target))
/** 当前目标的会话回执。 */
const session = computed(() => qualitySession(key.value))
/** 当前项目的短操作锁。 */
const operation = computed(() => getOperation(props.projectId))
/** 按项目恢复后台句柄,关闭弹窗仍继续观察。 */
const execution = useWorkflowExecution(
computed(() => props.projectId),
'keyframe-quality'
)
/** 已结束任务只写入其原始范围的回执。 */
const handled = new Set<string>()
/** 后台任务阻止重复启动。 */
const blocked = computed(
() => props.disabled || operation.value.pending || execution.active.value || !props.target || !props.projectId
)
/** 完成后由 metadata 恢复原目标;当前目标变化不改变任务归属。 */
watch(
() => execution.query.data.value,
record => {
if (
!record ||
record.projectId !== props.projectId ||
record.workflowName !== 'keyframe-quality' ||
!['completed', 'failed'].includes(record.status) ||
handled.has(record.id)
)
return
handled.add(record.id)
const metadata = record.metadata
const episodeNo = metadata?.episodeNo
if (typeof episodeNo !== 'number') return
const target: QualityTarget = {
kind: 'batch',
episodeNo,
title: '',
...(typeof metadata?.shotId === 'string' ? { shotId: metadata.shotId } : {})
}
const original = qualitySession(qualityKey(record.projectId, target))
if (record.status === 'failed') original.error = record.error || '首帧质量后台任务失败,请核对已完成资产。'
else if (
isQualityBatchResult(record.result) &&
record.result.results.every(item => !target.shotId || item.shotId === target.shotId) &&
(typeof metadata?.limit !== 'number' || record.result.targetCount <= metadata.limit)
)
original.receipt = { kind: 'batch', result: record.result }
else original.error = '后台最终回执不完整或范围不匹配,请核对资产,不要重复生成。'
changed()
}
)
let disposed = false
onScopeDispose(() => {
disposed = true
})
/**
* 确认之后重读状态并只提交一次,固定原目标与费用范围。
* @param action 已确认的质量操作
* @param input 已确认的参数
* @returns 操作结束通知,后台生成由持久化任务继续跟踪
*/
async function run(action: QualityAction, input: QualityInput) {
if (blocked.value || !visible() || !props.target || !validQualityInput(input)) return
const target = { ...props.target }
if (
(target.kind === 'batch') !== (action === 'batch') ||
(target.kind === 'video' && action === 'repair' && input.maxRepairAttempts <= 0)
)
return
if (
target.kind === 'batch' &&
(input.episodeNo !== target.episodeNo ||
input.shotId !== target.shotId ||
(target.shotId && input.limit !== 1))
)
return
const projectId = props.projectId
// 固定本次确认的参数,预检期间的表单变化不能扩大已确认的生成范围。
input = {
...input,
allowedTexts: input.allowedTexts?.slice(),
generationOptions: input.generationOptions ? { ...input.generationOptions } : undefined
}
const originalKey = key.value
const receiptTarget = qualitySession(originalKey)
receiptTarget.receipt = null
receiptTarget.error = ''
if (target.kind === 'video' && action === 'validate') delete receiptTarget.videoValidation
const stillCurrent = () => !disposed && key.value === originalKey && visible()
const ok = await runOperation(
projectId,
action === 'batch'
? '首帧质量生成'
: action === 'repair'
? target.kind === 'video'
? '创建视频修复候选'
: '首帧自动修复'
: '视觉质量校验',
async () => {
const [project, readiness, checkpoints] = await Promise.all([
projectsApi.detail(projectId),
productionApi.keyframeReadiness(projectId, target.kind === 'batch' ? input.force : true),
projectsApi.checkpoints(projectId)
])
if (project.id !== projectId || project.status !== 'completed')
throw new Error('剧本未完成或项目已变化,未提交质量任务。')
if (hasRunningWorkflow(checkpoints)) throw new Error('项目还有后台任务,请结束后再执行质量检查。')
if (
!Array.isArray(readiness.items) ||
readiness.items.length !== readiness.total ||
new Set(readiness.items.map(item => item.shotId)).size !== readiness.total
)
throw new Error('镜头就绪列表不完整,请刷新。')
let receipt: QualityReceipt
if (target.kind === 'batch') {
const targets = qualityTargets(readiness, input)
if (!targets.length)
throw new Error(
readiness.stalePrimaryKeyframe > 0
? '当前范围没有可执行的首帧质量镜头,请刷新就绪状态。'
: '当前集没有符合条件的镜头;请补齐设计与参考图,或明确选择重做有效首帧。'
)
// 逐镜只读检查已选的小批量;任何模型能力不足都不启动本批付费流水线。
const capabilities = await Promise.all(
targets.map(item => qualityApi.capability(item.shotId, undefined, input.provider))
)
const invalid = capabilities.find(item => item.valid !== true)
if (invalid) throw new Error(invalid.message || '当前图片模型不支持所需参考图。')
const assets = await Promise.all(targets.map(item => productionApi.listKeyframes(item.shotId)))
if (
assets.some((items, index) =>
items.some(
item =>
item.shotId !== targets[index]?.shotId ||
['pending', 'generating'].includes(item.status)
)
)
)
throw new Error('本批镜头有进行中的生图任务或资产归属异常,请先刷新核对。')
if (!stillCurrent()) throw new Error('已离开原操作目标,未提交质量任务。')
const result = await qualityApi.generate(projectId, input)
if (
!result ||
result.projectId !== projectId ||
typeof result.executionId !== 'string' ||
!result.executionId ||
result.status !== 'running' ||
!Number.isSafeInteger(result.total) ||
result.total < 0 ||
result.total > input.limit
)
throw new Error('后台启动回执不完整,请刷新状态,不要重复提交。')
await execution.track(result.executionId, projectId)
if (!disposed && props.projectId === projectId) started(result.executionId)
return
} else {
if (!readiness.items.some(item => item.shotId === target.shotId))
throw new Error('指定镜头不属于当前项目,未提交质量任务。')
if (target.kind === 'video') {
const videos = await productionApi.listVideos(target.shotId)
const video = videos.find(item => item.id === target.assetId && item.shotId === target.shotId)
if (
!video ||
video.status !== 'completed' ||
!video.videoUrl ||
!video.durationSeconds ||
video.durationSeconds <= 0
)
throw new Error('视频未完成、缺少视频地址或有效时长,不能执行抽样校验。')
if (video.motionPlanStale || video.qualityTerminalStatus === 'stale_motion_plan')
clearVideoQualification(projectId, target.shotId, target.assetId)
if (!videoOperationAllowed(video, action === 'repair' ? 'repair' : 'validate'))
throw new Error(video.staleReason || '当前候选暂时不能执行这项检查,请刷新状态后再试。')
if (action === 'repair') {
if (videos.some(item => ['pending', 'queued', 'running'].includes(item.status)))
throw new Error('此镜头仍有活动视频任务,请结束后再修复。')
if (!stillCurrent()) throw new Error('已离开原操作目标,未提交质量任务。')
const result = await qualityApi
.repairVideo(target.shotId, target.assetId, input.maxRepairAttempts)
.catch(cause => {
clearVideoConflict(cause, projectId, target.shotId, target.assetId)
throw cause
})
if (
!result ||
result.shotId !== target.shotId ||
result.sourceVideoId !== target.assetId ||
!result.candidate ||
result.candidate.shotId !== target.shotId ||
result.candidate.id === target.assetId ||
result.candidate.isPrimary ||
!Number.isSafeInteger(result.repairAttempt) ||
result.repairAttempt <= 0 ||
!Array.isArray(result.repairInstructions)
)
throw new Error('视频修复任务回执不完整,请先刷新视频记录,勿重复提交。')
receipt = { kind: 'video-repair', result }
} else {
if (!stillCurrent()) throw new Error('已离开原操作目标,未提交质量任务。')
const result = await qualityApi
.validateVideo(target.shotId, target.assetId, input.allowedTexts ?? [])
.catch(cause => {
clearVideoConflict(cause, projectId, target.shotId, target.assetId)
throw cause
})
if (
!isVisualValidation(result) ||
result.shotId !== target.shotId ||
result.videoId !== target.assetId ||
!Array.isArray(result.sampleFrames) ||
typeof result.isPrimary !== 'boolean'
)
throw new Error('视频检查结果不完整或与所选视频不一致,请刷新检查记录。')
receiptTarget.videoValidation = result
receipt = {
kind: 'video',
result,
promoted: !video.isPrimary && result.passed && result.isPrimary
}
}
} else {
const keyframes = await productionApi.listKeyframes(target.shotId)
const image = keyframes.find(
item => item.id === target.assetId && item.shotId === target.shotId
)
if (!image || image.status !== 'completed' || !image.imageUrl)
throw new Error('首帧尚未完成或缺少图片,不能执行质量检查。')
if (keyframes.some(item => ['pending', 'generating'].includes(item.status)))
throw new Error('此镜头仍在生图,请结束后再校验或修复。')
if (action === 'repair' && input.maxRepairAttempts > 0) {
const capability = await qualityApi.capability(target.shotId)
if (capability.valid !== true)
throw new Error(capability.message || '当前图片模型不满足参考图限制。')
}
if (!stillCurrent()) throw new Error('已离开原操作目标,未提交质量任务。')
if (action === 'repair') {
const result = await qualityApi.repair(target.shotId, target.assetId, {
maxRepairAttempts: input.maxRepairAttempts,
allowedTexts: input.allowedTexts,
width: input.width,
height: input.height
})
if (
!result ||
result.shotId !== target.shotId ||
result.initialKeyframeId !== target.assetId ||
typeof result.passed !== 'boolean' ||
typeof result.primaryChanged !== 'boolean' ||
!validAttempts(result.attempts)
)
throw new Error('修复回执不完整,请先核对首帧与主图状态,不要重复生图。')
receipt = { kind: 'repair', result }
} else {
const result = await qualityApi.validateKeyframe(
target.shotId,
target.assetId,
input.allowedTexts ?? []
)
if (
!isVisualValidation(result) ||
result.shotId !== target.shotId ||
result.keyframeId !== target.assetId ||
!result.validationTaskId
)
throw new Error('首帧检查结果不完整或与所选图片不一致,请刷新检查记录。')
receipt = { kind: 'keyframe', result }
}
}
}
receiptTarget.receipt = receipt
}
)
if (!ok) receiptTarget.error = getOperation(projectId).error
// 已提交请求即使切换页面也归原会话;只刷新仍在查看的原项目。
if (!disposed && props.projectId === projectId) changed()
}
return { key, session, operation, execution, blocked, run }
}