/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ // 体验中心视频页(WP A1-12)schema 驱动的纯函数:模式 / 图片槽 / 参数合成 / 请求体 / 草稿。 // 无 React / i18n 依赖,可直接 node --test。schema 见 controller/creation_models.go。 import { getDefaultValues, getParamDefault, paramsForMode, snapValues, } from '../../components/creation/params/constraints.js'; export const DRAFT_STORAGE_KEY = 'video_generation_draft_v3'; const LEGACY_DRAFT_KEY = 'video_generation_draft_v2'; export const MODE_ORDER = [ 'text2video', 'image2video', 'first_last_frame', 'reference2video', ]; /** 模式显示名(i18n key)。 */ export const MODE_LABEL_KEYS = { text2video: '文生视频', image2video: '图生视频', first_last_frame: '首尾帧生视频', reference2video: '参考图生视频', }; /** 视频请求(VideoGenerateRequest)认识的 schema 参数;其余参数不渲染也不提交。 */ export const REQUEST_PARAM_KEYS = new Set([ 'aspect_ratio', 'resolution', 'duration', 'generate_audio', 'watermark', 'seed', 'negative_prompt', 'camera', 'return_last_frame', 'prompt_extend', ]); export const EMPTY_IMAGES = Object.freeze({ first_frame: null, last_frame: null, reference_images: [], }); export const DEFAULT_VIDEO_FORM = Object.freeze({ mode: 'text2video', selectedTemplate: '', prompt: '', modelName: '', params: {}, images: EMPTY_IMAGES, // 按模型记忆的参数(切换模型时优先级第 2 位,方案 §4.3) paramMemory: {}, }); export const modelNameOf = (model) => { if (!model) return ''; if (typeof model === 'string') return model; return model.model || model.model_name || model.id || ''; }; /** schema 中可渲染 / 可提交的参数。 */ export const requestParamsOf = (model) => ((model && model.params) || []).filter( (p) => p && p.key && REQUEST_PARAM_KEYS.has(p.key), ); /** 当前模式下可渲染 / 可提交的参数(schema 参数的 modes 不含当前模式时隐藏且不提交)。 */ export const requestParamsForMode = (model, mode) => paramsForMode(requestParamsOf(model), mode || 'text2video'); /** 模式列表:可用模式 + 因系统配置禁用的模式(带原因),按固定顺序。 */ export const modeOptionsOf = (model) => { if (!model) return []; const enabled = new Set(model.modes || []); const disabled = {}; (model.disabled_modes || []).forEach((d) => { if (d && d.mode && !enabled.has(d.mode)) disabled[d.mode] = d.reason || ''; }); const all = new Set([...enabled, ...Object.keys(disabled)]); const order = (m) => { const i = MODE_ORDER.indexOf(m); return i < 0 ? MODE_ORDER.length : i; }; return [...all] .sort((a, b) => order(a) - order(b)) .map((mode) => ({ mode, disabled: !enabled.has(mode), reason: disabled[mode] || '', })); }; export const isModeEnabled = (model, mode) => Boolean(model && (model.modes || []).includes(mode)); const inputUsedBy = (input, mode) => Boolean(input && Array.isArray(input.modes) && input.modes.includes(mode)); /** 当前模型 × 模式使用的图片输入:{ first_frame, last_frame, reference_images(max) }。 */ export const activeInputsOf = (model, mode) => { const inputs = (model && model.inputs) || {}; const out = { first_frame: false, last_frame: false, reference_max: 0 }; if (!isModeEnabled(model, mode)) return out; out.first_frame = inputUsedBy(inputs.first_frame, mode); out.last_frame = inputUsedBy(inputs.last_frame, mode); if (inputUsedBy(inputs.reference_images, mode)) { const max = Number(inputs.reference_images.max); out.reference_max = Number.isFinite(max) && max > 0 ? max : 1; } return out; }; const isReady = (slot) => Boolean(slot && slot.ref && (slot.status || 'ready') === 'ready'); /** * 面板要渲染的图片槽。当前模式用到的槽正常显示;用不到但已有图片的槽保留并标为 unused * (方案 §4.3:新模型用不到的图片不删除,置灰标注,切回去自动恢复)。 * * @returns {Array<{ key: string, index?: number, label: string, labelIndex?: number, * slot: object|null, active: boolean }>} */ export const imageSlotsOf = (model, mode, images = EMPTY_IMAGES) => { const active = activeInputsOf(model, mode); const list = []; const inputs = (model && model.inputs) || {}; if (active.first_frame || images.first_frame) { list.push({ key: 'first_frame', label: (inputs.first_frame && inputs.first_frame.label) || '首帧', slot: images.first_frame || null, active: active.first_frame, }); } if (active.last_frame || images.last_frame) { list.push({ key: 'last_frame', label: (inputs.last_frame && inputs.last_frame.label) || '尾帧', slot: images.last_frame || null, active: active.last_frame, }); } const refs = images.reference_images || []; const refActive = active.reference_max > 0; refs.forEach((slot, index) => { list.push({ key: 'reference_images', index, label: '参考图', labelIndex: index + 1, slot, // 超过当前模型上限的参考图同样不提交 active: refActive && index < active.reference_max, }); }); if (refActive && refs.length < active.reference_max) { list.push({ key: 'reference_images', index: refs.length, label: '参考图', labelIndex: refs.length + 1, slot: null, active: true, }); } return list; }; /** 当前模式真正会提交的图片槽。 */ export const activeImageSlots = (model, mode, images) => imageSlotsOf(model, mode, images).filter((s) => s.active && s.slot); /** * 提交前的阻断原因(i18n key + 插值),无阻断返回 null。 * 只检查与图片相关的条件;提示词 / 模型 / 并发 / 余额由调用方检查。 */ export const imageBlockReason = (model, mode, images = EMPTY_IMAGES) => { if (!model) return null; if (!isModeEnabled(model, mode)) { return { key: '当前模型不支持该生成模式,请切换模式' }; } const slots = activeImageSlots(model, mode, images); if (slots.some((s) => s.slot.status === 'uploading')) { return { key: '图片上传中,请稍候' }; } if (slots.some((s) => s.slot.status === 'error')) { return { key: '图片上传失败,请重试或移除' }; } if (slots.some((s) => s.slot.status === 'expired')) { return { key: '原图已失效,请重新上传' }; } const active = activeInputsOf(model, mode); if (active.first_frame && !isReady(images.first_frame)) { return { key: mode === 'image2video' ? '请上传首帧图片' : '缺少首帧' }; } if (active.last_frame && !isReady(images.last_frame)) { return { key: '缺少尾帧' }; } if ( active.reference_max > 0 && !slots.some((s) => s.key === 'reference_images' && isReady(s.slot)) ) { return { key: '请至少上传一张参考图' }; } return null; }; /** * 切换模型后的模式:当前模式可用则保持;否则在可用模式里优先保留已上传的图片(首帧 → 图生), * 再退回文生视频 / 第一个可用模式。 */ export const pickModeForModel = (model, mode, images = EMPTY_IMAGES) => { if (!model) return mode || 'text2video'; if (isModeEnabled(model, mode)) return mode; const modes = model.modes || []; if ( images.first_frame && images.last_frame && modes.includes('first_last_frame') ) { return 'first_last_frame'; } if (images.first_frame && modes.includes('image2video')) return 'image2video'; if ( (images.reference_images || []).length && modes.includes('reference2video') ) { return 'reference2video'; } if (modes.includes('text2video')) return 'text2video'; return modes[0] || 'text2video'; }; /** * 合成某模型的参数取值(方案 §4.3 优先级): * 1. 本次会话用户手动设置的值(sessionValues);2. 该模型上次使用时记住的值(memory); * 3. schema 默认值。不合法的值吸附到最近的合法值。 * * @returns {{ values: object, adjustments: Array<{key, from, to}> }} */ export const composeParams = ( model, { sessionValues = {}, memory = {} } = {}, ) => { const params = requestParamsOf(model); const merged = getDefaultValues(params); params.forEach((p) => { if (memory && memory[p.key] !== undefined) merged[p.key] = memory[p.key]; if (sessionValues && sessionValues[p.key] !== undefined) { merged[p.key] = sessionValues[p.key]; } }); const { values, adjustments } = snapValues( params, merged, (model && model.constraints) || [], ); // 只保留 schema 内的键:其它模型的参数不随请求提交 const out = {}; params.forEach((p) => { if (values[p.key] !== undefined) out[p.key] = values[p.key]; }); return { values: out, adjustments }; }; /** * 复用参数 / 再生成 / 换种子再来:任务快照对请求参数是权威的。只按快照参数合成, * 快照缺省的可选参数(随机种子、空负向提示词等)取 schema 默认值,不合并此前的会话值 * 与按模型记忆(否则上一次"换种子"的固定种子会泄漏到本次请求)。 * @returns {{ values: object, adjustments: Array<{key, from, to}> }} */ export const composePrefillParams = (model, snapshotParams) => composeParams(model, { sessionValues: { ...(snapshotParams || {}) }, memory: {}, }); const isRandomSeed = (v) => v === undefined || v === null || v === '' || Number.isNaN(Number(v)); /** * 构造 POST /api/video/generate 请求体(不含 model)。 * - 参数只取 schema 内、请求认识、且适用于当前模式(modes)的键;未设置的取 schema 默认值。 * - 比例 / 音频同时写入旧字段别名(ratio / audio),兼容旧转换器路径。 * - 图片按模式放入 image / last_image / reference_images;当前模式用不到的图片不提交。 */ export const buildVideoRequest = (model, form) => { const mode = form.mode || 'text2video'; const values = form.params || {}; const payload = { mode, prompt: form.prompt || '' }; requestParamsForMode(model, mode).forEach((p) => { const v = values[p.key] !== undefined ? values[p.key] : getParamDefault(p); switch (p.key) { case 'seed': if (!isRandomSeed(v)) payload.seed = Math.trunc(Number(v)); break; case 'negative_prompt': case 'camera': if (typeof v === 'string' && v.trim()) payload[p.key] = v.trim(); break; case 'aspect_ratio': if (v !== undefined && v !== null && v !== '') { payload.aspect_ratio = String(v); payload.ratio = String(v); } break; case 'generate_audio': if (typeof v === 'boolean') { payload.generate_audio = v; payload.audio = v; } break; case 'duration': { const n = Number(v); if (Number.isFinite(n) && n > 0) payload.duration = n; break; } default: if (v !== undefined && v !== null && v !== '') payload[p.key] = v; } }); const images = form.images || EMPTY_IMAGES; const active = activeInputsOf(model, mode); if (active.first_frame && isReady(images.first_frame)) { payload.image = images.first_frame.ref; } if (active.last_frame && isReady(images.last_frame)) { payload.last_image = images.last_frame.ref; } if (active.reference_max > 0) { const refs = (images.reference_images || []) .slice(0, active.reference_max) .filter(isReady) .map((s) => s.ref); if (refs.length) payload.reference_images = refs; } return payload; }; // --------------------------------------------------------------------------- // 再生成:把任务详情的 request(ExperienceVideoRequestDTO)回填为表单 // --------------------------------------------------------------------------- const isDisplayableURL = (v) => /^(https?:|data:|blob:)/i.test(String(v || '')); const taskImageSlot = (ref, display, id) => { const value = typeof ref === 'string' ? ref.trim() : ''; if (!value) return null; const isAsset = value.startsWith('asset://'); const preview = isDisplayableURL(display) ? display : isDisplayableURL(value) ? value : null; return { id, status: 'ready', ref: value, previewUrl: preview, source: isAsset ? 'asset' : 'task', identityType: isAsset ? 'real_person' : 'aigc', }; }; const isBool = (v) => typeof v === 'boolean'; const nonEmptyString = (v) => typeof v === 'string' && v.trim() !== ''; /** * 任务详情 request → 表单回填值(未按 schema 吸附,调用方再走 composeParams)。 * 字段映射见 controller/video_generation.go ExperienceVideoRequestDTO: * image_ref|image → 首帧,last_image_ref|last_image → 尾帧, * reference_image_refs[i]|reference_images[i] → 参考图;*_ref 为提交值,无 *_ref 时退回展示地址。 * * @returns {{ modelName, mode, prompt, params, images }} */ export const formFromTaskRequest = (request, { newId } = {}) => { const req = request || {}; let seq = 0; const makeId = newId || (() => `slot-task-${Date.now().toString(36)}-${seq++}`); const params = {}; const aspect = req.aspect_ratio || req.ratio; if (nonEmptyString(aspect)) params.aspect_ratio = aspect; if (nonEmptyString(req.resolution)) params.resolution = req.resolution; if (Number(req.duration) > 0) params.duration = Number(req.duration); if (isBool(req.generate_audio)) params.generate_audio = req.generate_audio; else if (isBool(req.audio)) params.generate_audio = req.audio; // watermark / audio 为 omitempty:缺省即 false params.watermark = req.watermark === true; if (typeof req.seed === 'number' && Number.isFinite(req.seed)) { params.seed = req.seed; } if (nonEmptyString(req.negative_prompt)) { params.negative_prompt = req.negative_prompt; } if (nonEmptyString(req.camera)) params.camera = req.camera; if (isBool(req.return_last_frame)) { params.return_last_frame = req.return_last_frame; } if (isBool(req.prompt_extend)) params.prompt_extend = req.prompt_extend; const refs = Array.isArray(req.reference_image_refs) ? req.reference_image_refs : []; const displays = Array.isArray(req.reference_images) ? req.reference_images : []; const refList = refs.length ? refs : displays; const images = { first_frame: taskImageSlot(req.image_ref || req.image, req.image, makeId()), last_frame: taskImageSlot( req.last_image_ref || req.last_image, req.last_image, makeId(), ), reference_images: refList .map((ref, i) => taskImageSlot(ref, displays[i], makeId())) .filter(Boolean), }; return { modelName: typeof req.model === 'string' ? req.model : '', mode: MODE_ORDER.includes(req.mode) ? req.mode : '', prompt: typeof req.prompt === 'string' ? req.prompt : '', params, images, }; }; /** 估价请求的 params(只带定价相关参数)。 */ export const quoteParamsOf = (payload) => { const out = {}; ['duration', 'resolution', 'aspect_ratio'].forEach((k) => { if (payload[k] !== undefined) out[k] = payload[k]; }); return out; }; // --------------------------------------------------------------------------- // 草稿(localStorage v3,读写全部 try/catch) // --------------------------------------------------------------------------- const PERSISTABLE_SLOT_FIELDS = [ 'id', 'ref', 'previewUrl', 'name', 'source', 'identityType', ]; const persistSlot = (slot, keepInline) => { if (!isReady(slot)) return null; if (!keepInline && String(slot.ref).startsWith('data:')) return null; const out = { status: 'ready' }; PERSISTABLE_SLOT_FIELDS.forEach((k) => { if (slot[k] !== undefined && slot[k] !== null) out[k] = slot[k]; }); // 内联图片的预览就是它自己,不重复存 if (String(out.ref).startsWith('data:') && out.previewUrl === out.ref) { delete out.previewUrl; } return out; }; export const serializeDraft = (form, { keepInline = true } = {}) => { const images = form.images || EMPTY_IMAGES; return JSON.stringify({ mode: form.mode, selectedTemplate: form.selectedTemplate || '', prompt: form.prompt || '', modelName: form.modelName || '', params: form.params || {}, paramMemory: form.paramMemory || {}, images: { first_frame: persistSlot(images.first_frame, keepInline), last_frame: persistSlot(images.last_frame, keepInline), reference_images: (images.reference_images || []) .map((s) => persistSlot(s, keepInline)) .filter(Boolean), }, }); }; const restoreSlot = (slot) => { if (!slot || typeof slot !== 'object' || typeof slot.ref !== 'string') { return null; } const out = { ...slot, status: 'ready' }; if (!out.previewUrl && out.ref.startsWith('data:')) out.previewUrl = out.ref; if (!out.id) out.id = `slot-${Math.random().toString(36).slice(2, 10)}`; return out; }; const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v); export const parseDraft = (raw) => { if (!raw) return null; const data = JSON.parse(raw); if (!isPlainObject(data)) return null; const images = isPlainObject(data.images) ? data.images : {}; return { ...DEFAULT_VIDEO_FORM, mode: MODE_ORDER.includes(data.mode) ? data.mode : 'text2video', selectedTemplate: typeof data.selectedTemplate === 'string' ? data.selectedTemplate : '', prompt: typeof data.prompt === 'string' ? data.prompt : '', modelName: typeof data.modelName === 'string' ? data.modelName : '', params: isPlainObject(data.params) ? data.params : {}, paramMemory: isPlainObject(data.paramMemory) ? data.paramMemory : {}, images: { first_frame: restoreSlot(images.first_frame), last_frame: restoreSlot(images.last_frame), reference_images: Array.isArray(images.reference_images) ? images.reference_images.map(restoreSlot).filter(Boolean) : [], }, }; }; /** 读取草稿;v3 不存在时只从 v2 迁移提示词与模板(旧参数口径不同,不迁移)。 */ export const loadDraft = (storage) => { try { const v3 = parseDraft(storage.getItem(DRAFT_STORAGE_KEY)); if (v3) return v3; } catch (e) { // 草稿损坏时忽略 } try { const raw = storage.getItem(LEGACY_DRAFT_KEY); const v2 = raw ? JSON.parse(raw) : null; if (isPlainObject(v2)) { return { ...DEFAULT_VIDEO_FORM, prompt: typeof v2.prompt === 'string' ? v2.prompt : '', selectedTemplate: typeof v2.selectedTemplate === 'string' ? v2.selectedTemplate : '', }; } } catch (e) { // 忽略 } return { ...DEFAULT_VIDEO_FORM }; }; /** 保存草稿;配额不足时退而不存内联 base64 图片,仍失败则放弃。 */ export const saveDraft = (storage, form) => { try { storage.setItem(DRAFT_STORAGE_KEY, serializeDraft(form)); return true; } catch (e) { try { storage.setItem( DRAFT_STORAGE_KEY, serializeDraft(form, { keepInline: false }), ); return true; } catch (e2) { return false; } } }; // --------------------------------------------------------------------------- // 轮询退避 // --------------------------------------------------------------------------- export const POLL_STEPS_MS = [3000, 5000, 10000]; export const POLL_HIDDEN_MS = 30000; /** 第 n 次(从 0 起)连续无变化轮询后的间隔;页面隐藏时降频。 */ export const pollDelay = (step, hidden) => { if (hidden) return POLL_HIDDEN_MS; return POLL_STEPS_MS[Math.min(step, POLL_STEPS_MS.length - 1)]; };