nex_animation/frontend/src/stores/models.ts

284 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 模型注册表(/api/providers)统一入口。
*
* 平台的真实能力由注册表决定:可用的 provider/model、支持的分辨率、
* 生成模式、单镜时长区间、帧率(ComfyUI 工作流的 config.fps)……
* 各页面表单必须以下面这些函数为唯一取值来源,禁止再写死 provider 名、
* 分辨率档位和帧率列表——否则用户能选出模型根本不支持的组合,
* 生成结果要么被后端悄悄降档,要么直接 400。
*
* React 侧的写法:注册表放在 zustand 里(页面靠 useRegistry() 订阅加载状态),
* 下面这些派生函数一律在渲染期同步读快照,保持「纯函数」调用形态,
* 视图里因此不需要 useEffect 去算分辨率档位。
*/
import { create } from 'zustand'
import * as api from '../api/client'
import { systemMeta } from './system'
export type ModelRow = {
id: number
provider: string
model: string
display_name: string
media_type: string
adapter: string
enabled: boolean
is_default: boolean
available: boolean
uses_mock?: boolean
modes?: string[]
resolutions?: string[]
/** 放大交付档位:模型按原生像素出片,合成端放大到这些档位(不额外花卡时) */
upscale_to?: string[]
aspect_ratios?: string[]
min_duration?: number
max_duration?: number
max_reference_images?: number
requires_reference?: boolean
notes?: string
config?: Record<string, any>
}
export type ModelRegistry = {
rows: ModelRow[]
defaults: Record<string, string>
loaded: boolean
busy: boolean
error: string
set: (patch: Partial<ModelRegistry>) => void
}
export const useModelsStore = create<ModelRegistry>((set) => ({
rows: [], defaults: {}, loaded: false, busy: false, error: '',
set: (patch) => set(patch)
}))
/** 渲染期订阅注册表(rows 变化时表单档位才会重算) */
export const useRegistry = <T,>(pick: (s: ModelRegistry) => T): T => useModelsStore(pick)
/** 派生函数的统一取数入口:同步读快照,不产生订阅 */
const S = () => useModelsStore.getState()
/** 拉取注册表(默认缓存;页面刷新按钮可传 force) */
export async function loadModels(force = false): Promise<ModelRow[]> {
const set = useModelsStore.getState().set
if (S().loaded && !force) return S().rows
set({ busy: true })
try {
const data = await api.get('/api/providers')
set({
rows: (data?.providers || []) as ModelRow[],
defaults: data?.defaults || {},
loaded: true,
error: ''
})
} catch (exc: any) {
set({ error: exc?.message || String(exc) })
} finally {
set({ busy: false })
}
return S().rows
}
export const isMock = (row?: ModelRow | null) =>
!!row && (row.uses_mock === true || String(row.adapter || '').startsWith('mock') || row.provider === 'mock')
/** 唯一标识:provider|model,表单直接绑定这个串,保存时拆回两个字段 */
export const refOf = (row?: ModelRow | null) => (row ? `${row.provider}|${row.model}` : '')
export function parseRef(ref?: string | null): [string, string] {
if (!ref) return ['', '']
const [provider, ...rest] = String(ref).split('|')
return [provider || '', rest.join('|') || '']
}
/**
* 某个媒体类型的可选模型。
* - 默认只给「已启用」的行,注册表还没加载时返回空(调用方显示「读取中」)
* - includeMock=true 时把 mock 演练通道排在最后,并保留标签提示
*/
export function modelsOf(mediaType: string, includeMock = true): ModelRow[] {
const rows = S().rows.filter((r) => r.media_type === mediaType && r.enabled)
const real = rows.filter((r) => !isMock(r))
const mocks = rows.filter(isMock)
return includeMock ? [...real, ...mocks] : real
}
/**
* 平台默认模型(优先 /api/providers.defaults,其次 is_default,再次首个可用)。
* includeMock=false 时只在真实能力里挑,供「不能选演练通道」的业务表单使用。
*/
export function defaultFor(mediaType: string, includeMock = true): ModelRow | null {
const rows = modelsOf(mediaType, includeMock)
const dp = S().defaults[`${mediaType}_provider`] || ''
const dm = S().defaults[`${mediaType}_model`] || ''
return (dp && rows.find((r) => r.provider === dp && r.model === dm))
|| rows.find((r) => r.is_default && r.available)
|| rows.find((r) => r.available)
|| rows.find((r) => r.is_default)
|| rows[0] || null
}
export function findByRef(ref?: string | null): ModelRow | null {
const [p, m] = parseRef(ref)
if (!p) return null
return S().rows.find((r) => r.provider === p && r.model === m) || null
}
export function findByPair(provider?: string | null, model?: string | null): ModelRow | null {
if (!provider) return null
if (model) return S().rows.find((r) => r.provider === provider && r.model === model) || null
return modelsOf('video').find((r) => r.provider === provider) || null
}
/** 项目当前配置的默认视频模型(provider+model 任一为空时回落到平台默认) */
export function projectVideoModel(project?: any): ModelRow | null {
return findByPair(project?.default_provider, project?.default_model)
|| defaultFor('video')
}
export type Caps = {
known: boolean
label: string
resolutions: string[]
upscaleTo: string[]
aspectRatios: string[]
modes: string[]
fps: number
minDuration: number
maxDuration: number
maxReferenceImages: number
requiresReference: boolean
adapter: string
mock: boolean
}
const EMPTY_CAPS: Caps = {
known: false, label: '', resolutions: [], upscaleTo: [], aspectRatios: [], modes: [], fps: 0,
minDuration: 0, maxDuration: 0, maxReferenceImages: 0, requiresReference: false,
adapter: '', mock: false
}
/** 读取一个模型的真实能力;ComfyUI 的帧率写在工作流 config 里 */
export function capsOf(provider?: string | null, model?: string | null): Caps {
const row = findByPair(provider, model)
if (!row) return { ...EMPTY_CAPS }
return {
known: true,
label: row.display_name || `${row.provider} · ${row.model}`,
resolutions: [...(row.resolutions || [])],
upscaleTo: [...(row.upscale_to || [])],
aspectRatios: [...(row.aspect_ratios || [])],
modes: [...(row.modes || [])],
fps: Number(row.config?.fps || 0),
minDuration: Number(row.min_duration || 0),
maxDuration: Number(row.max_duration || 0),
maxReferenceImages: Number(row.max_reference_images || 0),
requiresReference: row.requires_reference === true,
adapter: String(row.adapter || ''),
mock: isMock(row)
}
}
export const capsOfRef = (ref?: string | null) => capsOf(...parseRef(ref))
/**
* 分辨率下拉:与 /api/meta 档位取交集(注册表没声明就退回全量)。
*
* 交的是「原生档位 ∪ 放大交付档位」:MiniMax H3 原生只到 768p,官方交付口径就是
* 原生出片 + 超分放大,所以 1080p 可以选,但必须标出来是怎么来的——
* 用户以为选 1080p 会多花一倍卡时,就不选了;以为是原生 1080p,又会嫌画质不够。
*/
export function resolutionChoices(provider?: string | null, model?: string | null): { value: string; label: string; canvas: number[]; upscaled?: boolean }[] {
const all = (systemMeta()?.options?.resolution || []) as any[]
const caps = capsOf(provider, model)
const native = caps.resolutions
const upscaledOnly = caps.upscaleTo.filter((v) => !native.includes(v))
const allowed = native.length || upscaledOnly.length ? [...native, ...upscaledOnly] : []
const list = allowed.length ? all.filter((o) => allowed.includes(o.value)) : all
const rows = (list.length ? list : all).map((o) => ({
...o,
upscaled: upscaledOnly.includes(o.value),
label: upscaledOnly.includes(o.value) ? `${o.label}(原生 ${native[native.length - 1] || '720p'} 出片·放大交付)` : o.label
}))
// 档位按像素从小到大排,别让「放大交付」的档位混在原生档位中间
return rows.sort((a, b) => (a.canvas?.[0] || 0) - (b.canvas?.[0] || 0))
}
/** 可交付档位(原生 ∪ 放大交付):判断「这个档位能不能选」一律用它 */
export function deliveryResolutions(provider?: string | null, model?: string | null): string[] {
const caps = capsOf(provider, model)
return [...new Set([...caps.resolutions, ...caps.upscaleTo])]
}
/** 帧率下拉:跟随模型工作流的固定帧率,注册表没声明时退回常用档位 */
export function fpsChoices(provider?: string | null, model?: string | null): number[] {
const fps = capsOf(provider, model).fps
return fps > 0 ? [fps] : [24, 25, 30]
}
/* ===== 图像母版专用档位(平台资产库 / 项目资产库共用) ===== */
/** 图像档位 → 长边像素;后端 comfy_image 把宽高钳制在 256~2048 并对齐 32 */
const IMAGE_TIER_EDGE: Record<string, number> = { '512p': 512, '768p': 768, '1024p': 1024, '2k': 2048, '4k': 2048 }
/** 图像模型的分辨率档位:注册表声明什么就给什么,没声明时退回 1024p / 2k */
export function imageTiers(provider?: string | null, model?: string | null): { value: string; label: string; edge: number }[] {
const declared = capsOf(provider, model).resolutions
const list = declared.length ? declared : ['1024p', '2k']
return list.map((value) => ({ value, label: value.toUpperCase(), edge: IMAGE_TIER_EDGE[value] || 1024 }))
}
/** 画幅下拉:注册表声明优先,未声明时退回 /api/meta 的通用画幅 */
export function imageAspectChoices(provider?: string | null, model?: string | null): { value: string; label: string }[] {
const allowed = capsOf(provider, model).aspectRatios
const all = (systemMeta()?.options?.aspect_ratio || []) as any[]
if (allowed.length) {
const picked = all.filter((o) => allowed.includes(o.value))
return (picked.length ? picked : allowed).map((o) => (typeof o === 'string' ? { value: o, label: o } : o))
}
return all
}
/**
* 档位 + 画幅 → 真实输出像素。
* 以前资产库把 1024×576(场景)/ 768×1024(人物)写死在提交逻辑里,
* 用户在界面上既看不到也改不了,这里统一由注册表档位算出来。
*/
export function imageCanvas(tier?: string | null, aspect?: string | null): { width: number; height: number } {
const edge = Math.min(2048, IMAGE_TIER_EDGE[String(tier || '')] || 1024)
const parts = String(aspect || '16:9').split(':').map((n) => Number(n) || 0)
const aw = parts[0] > 0 ? parts[0] : 16
const ah = parts[1] > 0 ? parts[1] : 9
const align = (n: number) => Math.max(256, Math.min(2048, Math.floor(n / 32) * 32))
return aw >= ah
? { width: align(edge), height: align((edge * ah) / aw) }
: { width: align((edge * aw) / ah), height: align(edge) }
}
/** 表单里用一句话说明当前档位是否被模型支持 */
export function capabilityHint(provider?: string | null, model?: string | null,
resolution?: string | null, fps?: number | null, aspectRatio?: string | null): string[] {
const caps = capsOf(provider, model)
const warn: string[] = []
// 「跟随平台默认」= 没有显式 provider,后端会回落到注册表默认模型,不是错误;
// 注册表还没拉到时同样不能报错,否则每个表单打开都会闪一条红色误报。
if (!provider || !S().loaded) return []
if (!caps.known) return ['注册表里还没有这个模型,保存后派发会失败,请先在模型中心注册。']
if (caps.mock) return ['当前选的是 mock 演练通道,只产出占位视频,不能用于正式出片。']
const deliverable = [...caps.resolutions, ...caps.upscaleTo]
if (deliverable.length && resolution && !deliverable.includes(resolution)) {
warn.push(`该模型只支持 ${deliverable.join(' / ')},当前 ${resolution} 会被降档或报错。`)
} else if (resolution && caps.upscaleTo.includes(resolution) && !caps.resolutions.includes(resolution)) {
warn.push(`${resolution} 是放大交付档:模型按原生 ${caps.resolutions[caps.resolutions.length - 1] || '720p'} 出片,`
+ `合成端放大到 ${resolution} 交付,卡时与原生档一致。`)
}
if (caps.aspectRatios.length && aspectRatio && !caps.aspectRatios.includes(aspectRatio)) {
warn.push(`该模型只支持画幅 ${caps.aspectRatios.join(' / ')}。`)
}
if (caps.fps > 0 && fps && caps.fps !== Number(fps)) {
warn.push(`该模型固定 ${caps.fps}fps,改帧率只会影响时间线与质检口径,画面仍是 ${caps.fps}fps。`)
}
return warn
}