Files
image-workbench-desktop/src/generation-request-shape.js
T

134 lines
7.1 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.
/* 生图请求体生成策略(按"厂商分类"下发不同字段语义)
*
* 背景(2026-10-04 依据 tuzi(兔子) 网关真实文档/示例确定,见 docs/reference/tuzi-api.md):
* - openai 系(gpt-image 等):尺寸用**像素** size(如 "2160x3840"),质量用我们自己的 6 档 quality
* - gemini/nano-banana(openai 兼容端点):**size = 比例字符串("9x16")**,**quality = 分辨率档("1k"/"2k"/"4k")**
* ⇒ 同一字段名 quality 在不同族里语义不同:该族不发送我们的 6 档质量
* - doubao/seedream(即梦):**默认像素 size**(文档:总像素 [1024x1024,4096x4096]、宽高比 [1/16,16] ⇒ 比例靠像素表达),
* 比例=自动 时可改发 **K 档字符串**("2K");另有每模型上限(5-0 只到 3K、3-0 只到 2K)
* - custom:用户模板(占位符 $model $prompt $n $size $ratio $res $width $height),适配任意网关
*
* 纯函数;不读配置、不发请求。调用方(app.js 的 wGenerate)负责加 image / 6 档 quality 闸门。
*/
;(function (global) {
'use strict'
const KINDS = ['openai', 'gemini', 'doubao', 'custom']
// 默认「模型名 → 分类」规则(可被服务商配置里的 modelRules 覆盖;不区分大小写)
const DEFAULT_RULES = [
{ match: '^gemini.*image|nano-?banana', kind: 'gemini' },
{ match: '^doubao|seedream|即梦', kind: 'doubao' },
]
const K_TIERS = ['1K', '2K', '3K', '4K']
const K_RANK = { '1K': 1, '2K': 2, '3K': 3, '4K': 4 }
const SIZE_MODES = ['auto', 'pixel', 'k']
function ratioToken(v) {
const m = /^\s*(\d{1,4})\s*[:x×/]\s*(\d{1,4})\s*$/.exec(String(v == null ? '' : v))
return m ? (Number(m[1]) + 'x' + Number(m[2])) : ''
}
function kTier(res) {
const v = String(res == null ? '' : res).trim().toUpperCase()
return K_TIERS.indexOf(v) >= 0 ? v : ''
}
function kToken(res) { const t = kTier(res); return t ? t.toLowerCase() : '' }
// 文档实测的每模型档位上限(未列出的按 4K 允许,靠 size-smaller 诊断再收敛)
function maxKTierForModel(model) {
const m = String(model || '')
if (/^doubao-seedream-3-0|^seedream-3-0/i.test(m)) return '2K'
if (/^doubao-seedream-5-0/i.test(m)) return '3K'
return '4K'
}
function clampKTier(res, model) {
const want = kTier(res)
if (!want) return { res: '', capped: false }
const max = maxKTierForModel(model)
if ((K_RANK[want] || 0) <= (K_RANK[max] || 4)) return { res: want, capped: false }
return { res: max, capped: true }
}
function resolveKind(model, providerKind, rules, modelKind) {
if (KINDS.indexOf(modelKind) >= 0) return modelKind
if (KINDS.indexOf(providerKind) >= 0) return providerKind
const list = (Array.isArray(rules) && rules.length) ? rules : DEFAULT_RULES
for (const r of list) {
if (!r || !r.match) continue
try { if (new RegExp(String(r.match), 'i').test(String(model || ''))) return KINDS.indexOf(r.kind) >= 0 ? r.kind : 'openai' } catch (e) { /* 规则写错忽略 */ }
}
return 'openai'
}
// custom:模板里 $xxx 占位符替换(支持嵌套对象/数组;未知占位符保留原样)
function renderTemplate(node, vars) {
if (typeof node === 'string') {
return node.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (all, name) => (Object.prototype.hasOwnProperty.call(vars, name) ? String(vars[name] == null ? '' : vars[name]) : all))
}
if (Array.isArray(node)) return node.map((x) => renderTemplate(x, vars))
if (node && typeof node === 'object') {
const out = {}
for (const k in node) out[k] = renderTemplate(node[k], vars)
return out
}
return node
}
function sizeModeOf(o) {
const m = String((o && o.sizeMode) || '').trim()
return SIZE_MODES.indexOf(m) >= 0 ? m : 'auto'
}
/**
* @param {object} o
* kind, model, prompt, n, size(像素), ratio, res(1K/2K/4K/auto), sizeMode(auto|pixel|k),
* responseFormat, template(custom 用), watermark(布尔;doubao 默认 false)
* @returns {{body:object, kind:string, capped:boolean, sizeMode:string, kTier:string, aspect:string}}
*/
function buildGenerationBody(o) {
const opts = o || {}
const kind = KINDS.indexOf(opts.kind) >= 0 ? opts.kind : 'openai'
const model = String(opts.model || '')
const prompt = String(opts.prompt || '')
const n = Math.max(1, Number(opts.n) || 1)
const rf = String(opts.responseFormat || 'url')
const mode = sizeModeOf(opts)
const aspect = ratioToken(opts.ratio)
const pixel = String(opts.size == null ? '' : opts.size).trim()
if (kind === 'gemini') {
const b = { model, prompt, n, response_format: rf }
if (aspect) b.size = aspect // ← 该族 size 表示比例
if (mode !== 'pixel') { const k = kToken(opts.res); if (k) b.quality = k } // ← 该族 quality 表示分辨率档
return { body: b, kind, capped: false, sizeMode: mode, kTier: kToken(opts.res), aspect }
}
if (kind === 'doubao') {
const capped = clampKTier(opts.res, model)
const b = { model, prompt, n, response_format: rf, watermark: opts.watermark === true }
const usePixel = mode === 'pixel' || (mode === 'auto' && !!aspect && !!pixel)
if (usePixel && pixel) b.size = pixel // 像素模式:比例 + 档位都精确
else if (capped.res) b.size = capped.res // K 档模式:比例交给上游
return { body: b, kind, capped: capped.capped, sizeMode: usePixel ? 'pixel' : 'k', kTier: capped.res, aspect }
}
if (kind === 'custom') {
const cappedRes = clampKTier(opts.res, model)
const vars = {
model, prompt, n, size: pixel,
ratio: String(opts.ratio == null ? '' : opts.ratio),
ratio_x: aspect,
res: cappedRes.res || '', // 用户看到的大写档位(4K)
res_k: cappedRes.res ? cappedRes.res.toLowerCase() : '', // 小写变体(4k)
width: '', height: '',
}
const m = /^(\d+)x(\d+)$/.exec(pixel)
if (m) { vars.width = m[1]; vars.height = m[2] }
const tpl = (opts.template && typeof opts.template === 'object') ? opts.template : {}
const body = renderTemplate(tpl, vars)
if (body && typeof body === 'object' && !Array.isArray(body)) { if (body.model === undefined) body.model = model; if (body.prompt === undefined) body.prompt = prompt }
return { body: (body && typeof body === 'object' && !Array.isArray(body)) ? body : {}, kind, capped: false, sizeMode: mode, kTier: kTier(opts.res), aspect }
}
const b = { model, prompt, n, response_format: rf }
if (pixel) b.size = pixel
return { body: b, kind: 'openai', capped: false, sizeMode: mode, kTier: kTier(opts.res), aspect }
}
function cappedKTierSafe(res, model) { const c = clampKTier(res, model); return c.res ? c.res.toLowerCase() : '' }
global.IWBGenerationRequestShape = Object.freeze({
KINDS, DEFAULT_RULES, K_TIERS, SIZE_MODES,
ratioToken, kTier, kToken, maxKTierForModel, clampKTier, resolveKind, renderTemplate, buildGenerationBody,
})
})(typeof window !== 'undefined' ? window : globalThis)