Files
monkey-ai-web/src/components/creation/ModelPicker/modelPickerUtils.js
T
qiubaishen 6160a23117 sync: 同步总仓库 luoguang/monkey-ai weiyuan@bfdfb339 的 web/ 改动
同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2)
范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json)

- 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models
- 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s
- dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台)
- b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join
- 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文
- e4c301d5 fix: merge enterprise task record date filters
- c9369b95 feat: expose enterprise image and video task records
- a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2)
- 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写
- 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费
- f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口
- 8cdf1994 fix(topup): reset amount when switching from PayPal
- 93a4ac34 feat(baidu): configure Seedance liveness header by channel
- cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21)
- 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分)
- e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分)
- b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足
- e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销
- 584aad52 style(web): 个人中心侧边栏按 prettier 换行
- b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView
- eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤
- 8b254d49 fix: 小程序里隐藏企业充值入口与页面
- a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转
- cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票
- c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费
- 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式
- 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
2026-11-10 11:05:34 +08:00

270 lines
9.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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 <https://www.gnu.org/licenses/>.
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.<kind>.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;
};