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

250 lines
14 KiB
TypeScript

import { computed, onScopeDispose } from 'vue'
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,
qualityKey,
qualitySession,
qualityTargets,
validQualityInput,
sessionVideoValidation
} 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)
)
)
}
/** 统一质量操作:只读预检 → 显式付费请求 → 按原目标保存回执,不自动重试。 */
export function useQuality(
props: { projectId: string; target: QualityTarget | null; disabled: boolean },
visible: () => boolean,
changed: () => void
) {
const key = computed(() => qualityKey(props.projectId, props.target))
const session = computed(() => qualitySession(key.value))
const operation = computed(() => getOperation(props.projectId))
const blocked = computed(() => props.disabled || operation.value.pending || !props.target || !props.projectId)
let disposed = false
onScopeDispose(() => {
disposed = true
})
/** 确认之后重新读取后端状态;打开弹窗和查看结果不会调用此函数。 */
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) return
const projectId = props.projectId
// 固定本次确认的参数,预检期间的表单变化不能扩大已确认的生成范围。
input = { ...input, allowedTexts: input.allowedTexts?.slice() }
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)))
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 ||
!Array.isArray(result.results) ||
![result.targetCount, result.passed, result.repairFailed, result.failed, result.selected].every(
value => Number.isSafeInteger(value) && value >= 0
) ||
result.targetCount > input.limit ||
result.results.length !== result.targetCount ||
result.passed + result.repairFailed + result.failed !== result.targetCount ||
result.results.some(
item =>
!readiness.items.some(
shot => shot.shotId === item.shotId && shot.episodeNo === input.episodeNo
) || typeof item.success !== 'boolean'
)
)
throw new Error('质量流水线回执不完整,请先核对资产,不要重复提交。')
receipt = { kind: 'batch', result }
} 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 (action === 'repair') {
if (sessionVideoValidation(projectId, target.shotId, target.assetId)?.passed !== false)
throw new Error('请先完成视频质量校验;只有未通过的视频才能创建修复候选。')
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
)
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 ?? []
)
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, blocked, run }
}