/*
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 B-4)的纯函数:分组、搜索、能力标签、单价、不兼容原因、最近使用。
// 无 React / i18n 依赖(文案以 i18n key + 插值返回),可直接 node --test。
import { getParamDefault, optionValue } from '../params/constraints.js';
export const RECENT_GROUP = '__recent__';
export const OTHER_GROUP = '__other__';
export const RECENT_LIMIT = 4;
const TEXT_MODES = { video: 'text2video', image: 'text2image' };
const MODE_LABEL_KEYS = {
text2video: '文生视频',
image2video: '图生视频',
first_last_frame: '首尾帧',
reference2video: '参考图生视频',
text2image: '文生图',
edit: '图生图',
};
export const modelKeyOf = (m) => (m && m.model) || '';
/** 展示名:运营覆盖层 display_name,缺省为模型名。 */
export const displayNameOf = (m) => (m && (m.display_name || m.model)) || '';
/** 分组 key:schema series → vendor → 其他。 */
export const seriesOf = (m) => {
const s = (m && (m.series || m.vendor)) || '';
return String(s).trim() || OTHER_GROUP;
};
/** 搜索:模型名 / 展示名 / 系列 / 介绍,大小写不敏感,空格分隔的词全部命中。 */
export const matchesQuery = (m, query) => {
const words = String(query || '')
.toLowerCase()
.split(/\s+/)
.filter(Boolean);
if (!words.length) return true;
const hay = [m?.model, m?.display_name, m?.series, m?.vendor, m?.description]
.filter(Boolean)
.join(' ')
.toLowerCase();
return words.every((w) => hay.includes(w));
};
/**
* 分组:无搜索词时"最近使用"置顶(模型同时保留在所属系列中),其后按系列首次出现的顺序,
* "其他"放最后。有搜索词时不显示"最近使用"。
*
* @returns {Array<{ key: string, label: string, models: object[] }>}
* label 为系列原名;RECENT_GROUP / OTHER_GROUP 由界面翻译。
*/
export const groupModels = (models, { recent = [], query = '' } = {}) => {
const list = (Array.isArray(models) ? models : []).filter(
(m) => m && m.model && matchesQuery(m, query),
);
const groups = [];
if (!String(query || '').trim() && recent.length) {
const byName = new Map(list.map((m) => [m.model, m]));
const recentModels = recent.map((n) => byName.get(n)).filter(Boolean);
if (recentModels.length) {
groups.push({ key: RECENT_GROUP, label: '', models: recentModels });
}
}
const order = [];
const bySeries = new Map();
list.forEach((m) => {
const key = seriesOf(m);
if (!bySeries.has(key)) {
bySeries.set(key, []);
order.push(key);
}
bySeries.get(key).push(m);
});
order
.filter((k) => k !== OTHER_GROUP)
.forEach((k) => groups.push({ key: k, label: k, models: bySeries.get(k) }));
if (bySeries.has(OTHER_GROUP)) {
groups.push({
key: OTHER_GROUP,
label: '',
models: bySeries.get(OTHER_GROUP),
});
}
return groups;
};
/** 键盘导航用的扁平选项列表:[{ id, model, group }],id 在同一模型出现于多个分组时仍唯一。 */
export const flattenOptions = (groups, idPrefix = 'mp') =>
(groups || []).flatMap((g) =>
g.models.map((m) => ({
id: `${idPrefix}-${g.key === RECENT_GROUP ? 'r' : 's'}-${String(m.model).replace(/[^\w-]/g, '_')}`,
model: m,
group: g.key,
})),
);
/** 上下移动后的下标(循环);列表为空返回 -1。 */
export const moveActive = (length, current, delta) => {
if (!length) return -1;
if (current < 0 || current >= length) return delta < 0 ? length - 1 : 0;
return (current + delta + length) % length;
};
const numericOptions = (param) =>
((param && param.options) || [])
.map((o) => Number(optionValue(o)))
.filter((n) => Number.isFinite(n) && n > 0);
const findParam = (m, key) =>
((m && m.params) || []).find((p) => p && p.key === key) || null;
const enabledModes = (m) => new Set((m && m.modes) || []);
/**
* 能力标签(i18n key + 插值):图生 / 首尾帧 / 参考图 / 编辑 / 音频 / 最长时长。
* 只看可用模式与参数;因系统配置禁用的模式不计入。
*
* @returns {Array<{ key: string, label: string, values?: object }>}
*/
export const capabilityTags = (kind, m) => {
if (!m) return [];
const modes = enabledModes(m);
const tags = [];
if (kind === 'image') {
if (modes.has('edit')) {
tags.push({ key: 'edit', label: '编辑' });
const max = Number(m.inputs?.reference_images?.max);
if (Number.isFinite(max) && max > 1) {
tags.push({
key: 'reference',
label: '参考图 ×{{n}}',
values: { n: max },
});
}
}
return tags;
}
if (modes.has('image2video')) tags.push({ key: 'i2v', label: '图生' });
if (modes.has('first_last_frame')) {
tags.push({ key: 'flf', label: '首尾帧' });
}
if (modes.has('reference2video')) {
tags.push({ key: 'reference', label: '参考图' });
}
if (findParam(m, 'generate_audio') || (m.badges || []).includes('audio')) {
tags.push({ key: 'audio', label: '音频' });
}
const durations = numericOptions(findParam(m, 'duration'));
if (durations.length) {
tags.push({
key: 'max_duration',
label: '最长 {{n}} 秒',
values: { n: Math.max(...durations) },
});
}
return tags;
};
const BADGE_LABELS = { recommended: '推荐', new: '新' };
/** 展示徽标(推荐 / 新);其余 badge(如 audio)已体现在能力标签中。 */
export const badgesOf = (m) =>
((m && m.badges) || [])
.filter((b) => BADGE_LABELS[b])
.map((b) => ({ key: b, label: BADGE_LABELS[b] }));
const UNIT_LABELS = { second: '秒', task: '次', image: '张' };
/**
* 与当前参数对应的单价(取自 schema pricing,不调用估价接口)。
* 分档(by=resolution 等)时按当前取值(缺省为该参数默认值)取档位价,档位缺失退回默认价。
*
* @returns {{ amount: number, currency: string, unit: string, unitLabel: string, tier: string } | null}
*/
export const unitPriceOf = (m, params = {}) => {
const p = m && m.pricing;
if (!p) return null;
let amount = Number(p.price);
let tier = '';
if (p.by && p.prices && typeof p.prices === 'object') {
let current = params ? params[p.by] : undefined;
if (current === undefined || current === null || current === '') {
current = getParamDefault(findParam(m, p.by));
}
if (current !== undefined && current !== null && current !== '') {
const want = String(current).toLowerCase();
const hit = Object.keys(p.prices).find((k) => k.toLowerCase() === want);
if (hit && Number.isFinite(Number(p.prices[hit]))) {
amount = Number(p.prices[hit]);
tier = hit;
}
}
}
if (!Number.isFinite(amount) || amount <= 0) return null;
return {
amount,
currency: p.currency || '',
unit: p.unit || '',
unitLabel: UNIT_LABELS[p.unit] || '',
tier,
};
};
/**
* 与当前输入不兼容的原因(i18n key + 插值),兼容返回 null。
* 当前为非文生模式(用户已选图生 / 首尾帧 / 参考图 / 编辑)时,不支持该模式的模型不兼容。
* 等级锁定由调用方单独处理,不在此判断。
*
* @returns {{ key: string, values: { mode: string } } | null} values.mode 为模式名的 i18n key
*/
export const incompatibilityOf = (kind, m, { mode } = {}) => {
if (!m || !mode || mode === TEXT_MODES[kind]) return null;
if (enabledModes(m).has(mode)) return null;
return {
key: '不支持{{mode}}',
values: { mode: MODE_LABEL_KEYS[mode] || mode },
};
};
// ---------------------------------------------------------------------------
// 最近使用(localStorage creation..recent,读写全部 try/catch)
// ---------------------------------------------------------------------------
export const recentKeyOf = (kind) => `creation.${kind}.recent`;
export const loadRecent = (storage, kind) => {
try {
const raw = storage ? storage.getItem(recentKeyOf(kind)) : null;
const list = raw ? JSON.parse(raw) : [];
return Array.isArray(list)
? list.filter((n) => typeof n === 'string' && n).slice(0, RECENT_LIMIT)
: [];
} catch (e) {
return [];
}
};
/** 把模型放到最近使用首位并保存;返回新列表。 */
export const pushRecent = (storage, kind, name, current) => {
const base = Array.isArray(current) ? current : loadRecent(storage, kind);
if (!name) return base;
const next = [name, ...base.filter((n) => n !== name)].slice(0, RECENT_LIMIT);
try {
if (storage) storage.setItem(recentKeyOf(kind), JSON.stringify(next));
} catch (e) {
// 存储不可用时只在内存中生效
}
return next;
};