dsh-sendcomfy 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRACT.md +586 -0
- package/FEATURES.zh.md +244 -0
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/bin/sendcomfy.mjs +74 -0
- package/client.js +2851 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +22 -0
- package/index.js +449 -0
- package/lib/actions.mjs +1193 -0
- package/lib/capabilities.mjs +476 -0
- package/lib/comfy.mjs +968 -0
- package/lib/http.mjs +302 -0
- package/lib/state.mjs +384 -0
- package/lib/workflow.mjs +1572 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +66 -4
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-sendcomfy — 工作流能力画像与 AI 自主选型
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* 契约:CONTRACT.md §11.1 / §11.2。
|
|
5
|
+
*
|
|
6
|
+
* 会话里的文本模型不该让用户「先挑工作流、再报名字」,它只需要知道用户想要什么:
|
|
7
|
+
* - describeWorkflow(apiGraph) 从 API 图推导「这个工作流是干什么的」
|
|
8
|
+
* (文生图 / 图生图 / 局部重绘 / 放大 / ControlNet / LoRA / 视频 / 音频、需要准备的输入、输出类型)
|
|
9
|
+
* - chooseCandidates(task, ...) 按确定性规则给「任务描述 × 候选工作流」打分排序,交给模型自己决定
|
|
10
|
+
*
|
|
11
|
+
* 纯函数、零第三方依赖、无 I/O、不修改入参;坏输入一律降级成 'other',不抛错。
|
|
12
|
+
*/
|
|
13
|
+
import { summarizeGraph } from './workflow.mjs'
|
|
14
|
+
|
|
15
|
+
/** 能力标签顺序:既是 kinds 的输出顺序,也是 kindLabels 的顺序。 */
|
|
16
|
+
export const KINDS = ['txt2img', 'img2img', 'inpaint', 'upscale', 'controlnet', 'lora', 'video', 'audio', 'other']
|
|
17
|
+
|
|
18
|
+
/** 能力标签的中文名。 */
|
|
19
|
+
export const KIND_LABELS = {
|
|
20
|
+
txt2img: '文生图',
|
|
21
|
+
img2img: '图生图',
|
|
22
|
+
inpaint: '局部重绘',
|
|
23
|
+
upscale: '放大',
|
|
24
|
+
controlnet: 'ControlNet',
|
|
25
|
+
lora: 'LoRA',
|
|
26
|
+
video: '视频',
|
|
27
|
+
audio: '音频',
|
|
28
|
+
other: '其他',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 意图词典:命中任意词条即把对应能力加入 intentKinds。 */
|
|
32
|
+
const INTENT_WORDS = {
|
|
33
|
+
txt2img: [
|
|
34
|
+
'文生图', '文转图', '文字生图', '生成图', '生成图片', '生成一张', '画一', '画个', '绘制', '出图',
|
|
35
|
+
'插画', '海报', '头像', '壁纸', '想象', '创作', 'txt2img', 'text to image', 'text2img',
|
|
36
|
+
'generate image', 'generate a', 'draw', 'paint', 'illustration', 'poster', 'avatar', 'wallpaper',
|
|
37
|
+
],
|
|
38
|
+
img2img: [
|
|
39
|
+
'图生图', '重绘', '改图', '换风格', '风格化', '垫图', '参考图', '以图生图', '把这张图', '这张图', '原图',
|
|
40
|
+
'img2img', 'image to image', 'image2image', 'restyle', 'style transfer', 'reference image',
|
|
41
|
+
'based on this image', 'this image', '输入图', '输入图片',
|
|
42
|
+
],
|
|
43
|
+
inpaint: [
|
|
44
|
+
'局部重绘', '遮罩', '蒙版', '修复', '抹除', '去掉', '擦除', '消除', '去除',
|
|
45
|
+
'inpaint', 'inpainting', 'mask', 'remove', 'erase',
|
|
46
|
+
],
|
|
47
|
+
upscale: [
|
|
48
|
+
'放大', '超分', '高清', '清晰', '清晰化', '修复老照片', '提升分辨率',
|
|
49
|
+
'upscale', 'upscaler', 'upscaling', 'super resolution', 'superres', 'hires', '4k', '8k',
|
|
50
|
+
'sharpen', 'enhance resolution', 'higher resolution',
|
|
51
|
+
],
|
|
52
|
+
video: ['视频', '动画', '动图', '图生视频', '文生视频', '补帧', '延长', 'video', 'animate', 'animation', 'gif', 'i2v', 't2v', 'motion'],
|
|
53
|
+
audio: ['音频', '语音', '声音', '音乐', '配音', '朗读', 'audio', 'voice', 'speech', 'tts', 'music', 'sound'],
|
|
54
|
+
controlnet: ['线稿', '姿势', '骨架', '深度', '边缘', '结构控制', 'controlnet', 'canny', 'pose', 'depth', 'openpose', 'lineart', 'scribble'],
|
|
55
|
+
lora: ['lora', '风格模型', '微调模型', '角色模型', '画风', '风格'],
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 英文分词停用词。 */
|
|
59
|
+
const STOP_WORDS = new Set([
|
|
60
|
+
'the', 'a', 'an', 'and', 'or', 'of', 'to', 'for', 'with', 'is', 'are', 'my', 'this', 'that',
|
|
61
|
+
'please', 'can', 'you', 'i', 'me', 'we', 'it', 'in', 'on', 'at', 'by', 'as', 'be', 'do', 'one',
|
|
62
|
+
'image', 'picture', 'pic', 'photo', 'img', 'use', 'using', 'want', 'make', 'need', 'should',
|
|
63
|
+
])
|
|
64
|
+
|
|
65
|
+
/** 中文虚词/语气词:不参与「名称包含任务串」这类关键字面匹配。 */
|
|
66
|
+
const CJK_FILLERS = new Set([
|
|
67
|
+
'的', '了', '吧', '呀', '啊', '呢', '一张', '一个', '帮我', '请', '用', '把', '张', '只', '下',
|
|
68
|
+
'这张', '这个', '给我', '做成', '里', '一下', '图', '图片',
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
/** 文件输入类(运行前必须先上传/准备)。 */
|
|
72
|
+
const FILE_INPUT_RULES = [
|
|
73
|
+
{ re: /^LoadImage(Mask|MaskOnly)?$/, label: '输入图片' },
|
|
74
|
+
{ re: /^LoadImageOutput$/, label: '输入图片(来自输出)' },
|
|
75
|
+
{ re: /^VHS_LoadImage$/, label: '输入图片' },
|
|
76
|
+
{ re: /^LoadVideo$|^VHS_LoadVideo|^LoadVideoUpload$/, label: '输入视频' },
|
|
77
|
+
{ re: /^VHS_LoadAudio|^LoadAudio$|^LoadAudioUpload$/, label: '输入音频' },
|
|
78
|
+
{ re: /^LoadMask$|^LoadImageMask$|^ImageToMask$|^LoadImageMaskUpload$/, label: '遮罩图片' },
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
const LOAD_FILE_CLASS_RE = /^(LoadImage|LoadImageMask|LoadImageMaskUpload|LoadImageOutput|LoadVideo|LoadVideoUpload|LoadAudio|LoadAudioUpload|VHS_LoadVideo|VHS_LoadAudio|VHS_LoadImage|LoadMask|ImageToMask)$/
|
|
82
|
+
|
|
83
|
+
const UPSCALE_CLASS_RE = /(UpscaleModelLoader|ImageUpscaleWithModel|UltimateSDUpscale|LatentUpscale|ImageScaleBy|ImageScale|NomosUpscaler)/
|
|
84
|
+
const CONTROLNET_CLASS_RE = /(ControlNetLoader|ControlNetApply|^ACN_|T2IAdapterLoader)/
|
|
85
|
+
const LORA_CLASS_RE = /^(LoraLoader|LoraLoaderModelOnly|LoraLoaderList)$/
|
|
86
|
+
const VIDEO_CLASS_RE = /(EmptyHunyuanLatentVideo|WanImageToVideo|WanFirstLastFrameToVideo|EmptyMochiLatentVideo|AnimateDiff|^VHS_|SaveAnimatedWEBP|SaveAnimatedPNG|^CreateVideo$|^SaveVideo$|^SaveWEBM$|SVD_|SamplerCustomVideo|CosmosVideo)/
|
|
87
|
+
const AUDIO_CLASS_RE = /(SaveAudio|PreviewAudio|LoadAudio|Audio|Voice|Speech|TTS)/
|
|
88
|
+
const INPAINT_CLASS_RE = /(VAEEncodeForInpaint|InpaintModelConditioning|SetLatentNoiseMask)/
|
|
89
|
+
const SAMPLER_CLASS_RE = /^(KSampler|KSamplerAdvanced|SamplerCustom|SamplerCustomAdvanced)$/
|
|
90
|
+
const EMPTY_LATENT_CLASS_RE = /^(EmptyLatentImage|EmptySD3LatentImage|EmptyFluxLatentImage|EmptyHunyuanLatentVideo|EmptyMochiLatentVideo)$/
|
|
91
|
+
const TEXT_ENCODE_CLASS_RE = /(CLIPTextEncode|TextEncode)/
|
|
92
|
+
const VAE_ENCODE_CLASS_RE = /^(VAEEncode|VAEEncodeForInpaint|VAEEncodeTiled)$/
|
|
93
|
+
const VAE_DECODE_CLASS_RE = /^(VAEDecode|VAEDecodeTiled|VAEDecodeAudio)$/
|
|
94
|
+
|
|
95
|
+
const OUT_IMAGE = new Set(['SaveImage', 'PreviewImage', 'SaveImagePlus'])
|
|
96
|
+
const OUT_VIDEO_RE = /(VHS_VideoCombine|SaveAnimatedWEBP|SaveAnimatedPNG|^CreateVideo$|^SaveVideo$|^SaveWEBM$|SaveGif)/
|
|
97
|
+
const OUT_AUDIO_RE = /(SaveAudio|PreviewAudio)/
|
|
98
|
+
const OUT_LATENT = new Set(['SaveLatent', 'PreviewLatent'])
|
|
99
|
+
|
|
100
|
+
const MODEL_FILE_RE = /\.(safetensors|ckpt|pt|pth|bin|gguf|onnx|sft)$/i
|
|
101
|
+
const MAX_CLASSES = 60
|
|
102
|
+
const MAX_MODELS = 20
|
|
103
|
+
const MAX_LIST = 10 // chooseCandidates(limit) 允许的候选上限
|
|
104
|
+
|
|
105
|
+
/* ───────────────────────────── 小工具 ───────────────────────────── */
|
|
106
|
+
|
|
107
|
+
function isPlainObject(value) {
|
|
108
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isLinkValue(value) {
|
|
112
|
+
return Array.isArray(value)
|
|
113
|
+
&& value.length === 2
|
|
114
|
+
&& typeof value[0] === 'string'
|
|
115
|
+
&& (typeof value[1] === 'number' || typeof value[1] === 'string')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function inputEntries(apiGraph) {
|
|
119
|
+
if (!isPlainObject(apiGraph)) return []
|
|
120
|
+
const list = []
|
|
121
|
+
for (const [id, node] of Object.entries(apiGraph)) {
|
|
122
|
+
if (!isPlainObject(node)) continue
|
|
123
|
+
const classType = typeof node.class_type === 'string' ? node.class_type : ''
|
|
124
|
+
if (!classType) continue
|
|
125
|
+
list.push({ id: String(id), node, classType })
|
|
126
|
+
}
|
|
127
|
+
return list
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function nodeInputs(node) {
|
|
131
|
+
return isPlainObject(node) && isPlainObject(node.inputs) ? Object.entries(node.inputs) : []
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function titleOf(node) {
|
|
135
|
+
if (!isPlainObject(node) || !isPlainObject(node._meta)) return ''
|
|
136
|
+
return typeof node._meta.title === 'string' ? node._meta.title.trim() : ''
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 顶点出发可达的所有节点 id 集合(带上限,防环)。 */
|
|
140
|
+
function reachableFrom(apiGraph, startId, limit = 500) {
|
|
141
|
+
const seen = new Set()
|
|
142
|
+
const stack = [String(startId)]
|
|
143
|
+
while (stack.length > 0 && seen.size < limit) {
|
|
144
|
+
const id = stack.pop()
|
|
145
|
+
if (seen.has(id)) continue
|
|
146
|
+
seen.add(id)
|
|
147
|
+
const node = apiGraph[id]
|
|
148
|
+
if (!isPlainObject(node)) continue
|
|
149
|
+
for (const [, value] of nodeInputs(node)) {
|
|
150
|
+
if (isLinkValue(value) && !seen.has(String(value[0]))) stack.push(String(value[0]))
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return seen
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 中文一句话总结:能力 + 提示词 + 需要准备的输入 + 输出。 */
|
|
157
|
+
function summarizeCapabilities(kinds, hasPrompt, hasNegative, neededInputs, outputKinds) {
|
|
158
|
+
const parts = []
|
|
159
|
+
const kindLabels = kinds
|
|
160
|
+
.filter((kind) => kind !== 'other')
|
|
161
|
+
.map((kind) => KIND_LABELS[kind])
|
|
162
|
+
parts.push(kindLabels.length > 0 ? `${kindLabels.join(' + ')} 工作流` : '未识别的执行工作流')
|
|
163
|
+
if (hasPrompt) parts.push(hasNegative ? '支持正负提示词' : '支持正向提示词')
|
|
164
|
+
else parts.push('没有可注入的提示词文本节点')
|
|
165
|
+
if (neededInputs.length > 0) parts.push(`运行前需准备 ${neededInputs.length} 个输入文件(${neededInputs.map((item) => item.label).join('、')})`)
|
|
166
|
+
else parts.push('无需上传输入文件')
|
|
167
|
+
if (outputKinds.length > 0) parts.push(`输出${outputKinds.map((kind) => ({ image: '图片', video: '视频', audio: '音频', latent: '潜空间' }[kind] || kind)).join('/')}`)
|
|
168
|
+
let text = parts.join(',')
|
|
169
|
+
if (text.length > 120) text = `${text.slice(0, 117)}…`
|
|
170
|
+
return text
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const IMAGE_OUTPUTS = new Set(['SaveImage', 'PreviewImage', 'SaveImagePlus'])
|
|
174
|
+
const LATENT_OUTPUTS = new Set(['SaveLatent', 'PreviewLatent'])
|
|
175
|
+
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
// describeWorkflow
|
|
178
|
+
// ---------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 从 API 格式的图推导能力画像(CONTRACT §11.2)。
|
|
182
|
+
* 防御式:非对象 / 空图 / 坏节点一律返回 kinds:['other'] 的结果,不抛错。
|
|
183
|
+
*
|
|
184
|
+
* @param {Record<string, unknown>} apiGraph
|
|
185
|
+
* @returns {{ kinds: string[], kindLabels: string[], hasPrompt: boolean, hasNegative: boolean,
|
|
186
|
+
* classes: string[], models: string[], neededInputs: {param:string,nodeClass:string,inputName:string,label:string,hint:string}[],
|
|
187
|
+
* outputKinds: string[], summary: string }}
|
|
188
|
+
*/
|
|
189
|
+
export function describeWorkflow(apiGraph) {
|
|
190
|
+
const empty = {
|
|
191
|
+
kinds: ['other'],
|
|
192
|
+
kindLabels: [KIND_LABELS.other],
|
|
193
|
+
hasPrompt: false,
|
|
194
|
+
hasNegative: false,
|
|
195
|
+
classes: [],
|
|
196
|
+
models: [],
|
|
197
|
+
neededInputs: [],
|
|
198
|
+
outputKinds: [],
|
|
199
|
+
summary: '无法识别的工作流(不是 ComfyUI API 格式,或图里没有可执行节点)',
|
|
200
|
+
}
|
|
201
|
+
if (!isPlainObject(apiGraph)) return empty
|
|
202
|
+
const entries = inputEntries(apiGraph)
|
|
203
|
+
if (entries.length === 0) return empty
|
|
204
|
+
|
|
205
|
+
const classList = [...new Set(entries.map((entry) => entry.classType))].slice(0, MAX_CLASSES)
|
|
206
|
+
const hasClass = (re) => classList.some((name) => re.test(name))
|
|
207
|
+
|
|
208
|
+
/* ── 输出类型 ── */
|
|
209
|
+
const outputKinds = []
|
|
210
|
+
for (const classType of classList) {
|
|
211
|
+
if (IMAGE_OUTPUTS.has(classType) && !outputKinds.includes('image')) outputKinds.push('image')
|
|
212
|
+
else if (OUT_VIDEO_RE.test(classType) && !outputKinds.includes('video')) outputKinds.push('video')
|
|
213
|
+
else if (OUT_AUDIO_RE.test(classType) && !outputKinds.includes('audio')) outputKinds.push('audio')
|
|
214
|
+
else if (LATENT_OUTPUTS.has(classType) && !outputKinds.includes('latent')) outputKinds.push('latent')
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/* ── 提示词节点 ── */
|
|
218
|
+
const textNodes = entries.filter((entry) => TEXT_ENCODE_CLASS_RE.test(entry.classType))
|
|
219
|
+
let hasPrompt = false
|
|
220
|
+
let hasNegative = false
|
|
221
|
+
for (const { node } of textNodes) {
|
|
222
|
+
const title = titleOf(node)
|
|
223
|
+
if (/negative|负/i.test(title)) hasNegative = true
|
|
224
|
+
for (const [inputName] of nodeInputs(node)) {
|
|
225
|
+
const name = inputName.toLowerCase()
|
|
226
|
+
if (name === 'negative') hasNegative = true
|
|
227
|
+
if (['text', 'text_g', 'text_l', 'prompt', 'positive'].includes(name) && !/negative|负/.test(title)) hasPrompt = true
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/* ── 原图是否经 VAEEncode 进采样(图生图) ── */
|
|
232
|
+
let imageEncoded = false
|
|
233
|
+
for (const { node } of entries) {
|
|
234
|
+
const classType = String(node.class_type || '')
|
|
235
|
+
if (!VAE_ENCODE_CLASS_RE.test(classType)) continue
|
|
236
|
+
for (const [, value] of nodeInputs(node)) {
|
|
237
|
+
if (!isLinkValue(value)) continue
|
|
238
|
+
for (const upstreamId of reachableFrom(apiGraph, value[0])) {
|
|
239
|
+
const upstream = apiGraph[upstreamId]
|
|
240
|
+
if (!isPlainObject(upstream)) continue
|
|
241
|
+
if (/^LoadImage$|^LoadImageOutput$|^VHS_LoadImage$|^LoadImageMask$/.test(String(upstream.class_type || ''))) {
|
|
242
|
+
imageEncoded = true
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const hasSampler = hasClass(SAMPLER_CLASS_RE)
|
|
249
|
+
const hasEmptyLatent = hasClass(EMPTY_LATENT_CLASS_RE)
|
|
250
|
+
const inpaintish = hasClass(INPAINT_CLASS_RE) || classList.includes('LoadImageMask')
|
|
251
|
+
|
|
252
|
+
/* ── kinds(按 KINDS 顺序组装) ── */
|
|
253
|
+
const kinds = []
|
|
254
|
+
if (outputKinds.includes('video') || hasClass(VIDEO_CLASS_RE)) kinds.push('video')
|
|
255
|
+
if (outputKinds.includes('audio') || hasClass(AUDIO_CLASS_RE)) kinds.push('audio')
|
|
256
|
+
if (hasClass(UPSCALE_CLASS_RE)) kinds.push('upscale')
|
|
257
|
+
if (hasClass(CONTROLNET_CLASS_RE)) kinds.push('controlnet')
|
|
258
|
+
if (hasClass(LORA_CLASS_RE)) kinds.push('lora')
|
|
259
|
+
if (imageEncoded && inpaintish) kinds.push('inpaint')
|
|
260
|
+
if (imageEncoded) kinds.push('img2img')
|
|
261
|
+
if (hasSampler && (hasEmptyLatent || !imageEncoded)) kinds.push('txt2img')
|
|
262
|
+
if (kinds.length === 0) kinds.push('other')
|
|
263
|
+
const orderedKinds = KINDS.filter((kind) => kinds.includes(kind))
|
|
264
|
+
|
|
265
|
+
/* ── 需要准备的输入文件 ── */
|
|
266
|
+
const neededInputs = []
|
|
267
|
+
for (const { id, node, classType } of entries) {
|
|
268
|
+
const rule = FILE_INPUT_RULES.find((item) => item.re.test(classType))
|
|
269
|
+
if (!rule) continue
|
|
270
|
+
for (const [inputName, value] of nodeInputs(node)) {
|
|
271
|
+
if (value === null || value === undefined) continue
|
|
272
|
+
if (typeof value === 'object') continue
|
|
273
|
+
neededInputs.push({
|
|
274
|
+
param: `${id}.${inputName}`,
|
|
275
|
+
nodeClass: classType,
|
|
276
|
+
inputName,
|
|
277
|
+
label: rule.label,
|
|
278
|
+
hint: `先用 comfy_upload_image 上传文件(path 填工作区路径),再把返回的 name 填进参数 "${id}.${inputName}"`,
|
|
279
|
+
})
|
|
280
|
+
break
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/* ── 模型文件:字面量里像 *.safetensors 之类的值 ── */
|
|
285
|
+
const models = []
|
|
286
|
+
for (const { node } of entries) {
|
|
287
|
+
for (const [inputName, value] of nodeInputs(node)) {
|
|
288
|
+
if (typeof value !== 'string' || !MODEL_FILE_RE.test(value.trim())) continue
|
|
289
|
+
const normalized = value.trim()
|
|
290
|
+
if (models.includes(normalized) || models.length >= MAX_MODELS) continue
|
|
291
|
+
models.push(normalized)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
kinds: orderedKinds,
|
|
297
|
+
kindLabels: orderedKinds.map((kind) => KIND_LABELS[kind]),
|
|
298
|
+
hasPrompt,
|
|
299
|
+
hasNegative,
|
|
300
|
+
classes: classList,
|
|
301
|
+
models,
|
|
302
|
+
neededInputs,
|
|
303
|
+
outputKinds,
|
|
304
|
+
summary: summarizeCapabilities(orderedKinds, hasPrompt, hasNegative, neededInputs, outputKinds),
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* ───────────────────────────── 任务选型 ───────────────────────────── */
|
|
309
|
+
|
|
310
|
+
/** 词条归一:小写、去空白。 */
|
|
311
|
+
function normalizeWord(word) {
|
|
312
|
+
return String(word || '').toLowerCase().replace(/\s+/g, ' ').trim()
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** 中文段 → bigram(长度 ≤2 的段保留原串)。 */
|
|
316
|
+
function cjkBigrams(segment) {
|
|
317
|
+
const chars = [...segment]
|
|
318
|
+
if (chars.length <= 2) return [segment]
|
|
319
|
+
const grams = []
|
|
320
|
+
for (let i = 0; i < chars.length - 1; i += 1) grams.push(`${chars[i]}${chars[i + 1]}`)
|
|
321
|
+
return grams
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* 任务分词(确定性,不做魔法)。
|
|
326
|
+
* - 英文/数字:按非字母数字切词,小写、去停用词、长度 ≥3
|
|
327
|
+
* - 中文:连续 CJK 段拆 bigram
|
|
328
|
+
* @param {string} text
|
|
329
|
+
* @returns {string[]} 去重后的词条
|
|
330
|
+
*/
|
|
331
|
+
export function tokenizeTask(text) {
|
|
332
|
+
const raw = String(text || '')
|
|
333
|
+
const out = new Set()
|
|
334
|
+
const segments = raw.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
|
|
335
|
+
for (const segment of segments) {
|
|
336
|
+
const lower = segment.toLowerCase()
|
|
337
|
+
if (/^[a-z0-9]+$/.test(lower)) {
|
|
338
|
+
if (STOP_WORDS.has(lower)) continue
|
|
339
|
+
if (lower.length >= 3) out.add(lower)
|
|
340
|
+
continue
|
|
341
|
+
}
|
|
342
|
+
if (/^\p{Script=Han}+$/u.test(segment)) {
|
|
343
|
+
for (const gram of cjkBigrams(lower)) {
|
|
344
|
+
if (!CJK_FILLERS.has(gram)) out.add(gram)
|
|
345
|
+
}
|
|
346
|
+
continue
|
|
347
|
+
}
|
|
348
|
+
// 中英混合段:中文部分拆 bigram,英文/数字部分保留
|
|
349
|
+
for (const match of lower.matchAll(/\p{Script=Han}+|[a-z0-9]{3,}/gu)) {
|
|
350
|
+
const token = match[0]
|
|
351
|
+
if (/^\p{Script=Han}+$/u.test(token)) {
|
|
352
|
+
for (const gram of cjkBigrams(token)) {
|
|
353
|
+
if (!CJK_FILLERS.has(gram)) out.add(gram)
|
|
354
|
+
}
|
|
355
|
+
} else if (!STOP_WORDS.has(token)) {
|
|
356
|
+
out.add(token)
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return [...out]
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* 从任务描述推断能力意图(CONTRACT §11.2 意图词典)。
|
|
365
|
+
* @param {string} task
|
|
366
|
+
* @returns {string[]} intentKinds,按 KINDS 顺序
|
|
367
|
+
*/
|
|
368
|
+
export function detectIntentKinds(task) {
|
|
369
|
+
const haystack = ` ${String(task || '').toLowerCase()} `
|
|
370
|
+
if (!haystack.trim()) return []
|
|
371
|
+
const found = []
|
|
372
|
+
for (const [kind, words] of Object.entries(INTENT_WORDS)) {
|
|
373
|
+
if (words.some((word) => haystack.includes(String(word).toLowerCase()))) found.push(kind)
|
|
374
|
+
}
|
|
375
|
+
return KINDS.filter((kind) => found.includes(kind))
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* 按任务给候选工作流打分排序(CONTRACT §11.2 的 chooseCandidates)。
|
|
380
|
+
*
|
|
381
|
+
* candidates: { name, description?, tags?, kinds?, kindLabels?, classes?, paramNames?, models? }[]
|
|
382
|
+
* 返回 { matches:[{index,score,matched,reasons}], tokens, intentKinds }
|
|
383
|
+
* - 确定性、可复现;同分按原始 index 升序
|
|
384
|
+
* - 无任何命中时仍按原顺序返回前 limit 个,matched:false,附「没有明显匹配」理由
|
|
385
|
+
*/
|
|
386
|
+
export function chooseCandidates(task, candidates, { limit = 5 } = {}) {
|
|
387
|
+
const taskText = String(task || '')
|
|
388
|
+
const tokens = tokenizeTask(taskText)
|
|
389
|
+
const intentKinds = detectIntentKinds(taskText)
|
|
390
|
+
const list = Array.isArray(candidates) ? candidates : []
|
|
391
|
+
const safeLimit = Math.max(1, Math.min(MAX_LIST, Math.round(Number(limit) || 5)))
|
|
392
|
+
const taskCore = normalizeWord(taskText.replace(/[\s\p{P}]/gu, ''))
|
|
393
|
+
|
|
394
|
+
const scored = list.map((candidate, index) => {
|
|
395
|
+
if (!isPlainObject(candidate)) return { index, score: 0, matched: false, reasons: [] }
|
|
396
|
+
let score = 0
|
|
397
|
+
const reasons = []
|
|
398
|
+
const nameText = normalizeWord(candidate.name)
|
|
399
|
+
const nameTokens = tokenizeTask(candidate.name)
|
|
400
|
+
const descriptionText = normalizeWord(candidate.description)
|
|
401
|
+
const tags = Array.isArray(candidate.tags)
|
|
402
|
+
? candidate.tags.map((tag) => normalizeWord(tag)).filter(Boolean)
|
|
403
|
+
: []
|
|
404
|
+
const kinds = Array.isArray(candidate.kinds) ? candidate.kinds : []
|
|
405
|
+
const extraWords = [
|
|
406
|
+
...(Array.isArray(candidate.classes) ? candidate.classes : []),
|
|
407
|
+
...(Array.isArray(candidate.paramNames) ? candidate.paramNames : []),
|
|
408
|
+
...(Array.isArray(candidate.models) ? candidate.models : []),
|
|
409
|
+
].map((word) => normalizeWord(word)).filter(Boolean)
|
|
410
|
+
|
|
411
|
+
// 1) 名称包含任务串(6–12 字,足够长才算「精确」)
|
|
412
|
+
if (taskCore.length >= 6 && taskCore.length <= 12 && nameText.includes(taskCore)) {
|
|
413
|
+
score += 10
|
|
414
|
+
reasons.push(`名称包含「${String(taskText).trim().slice(0, 12)}」`)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// 2) 名称 token 命中(每个 +6,封顶 +18)
|
|
418
|
+
const nameHits = tokens.filter((token) => nameTokens.includes(token) || nameText.includes(token))
|
|
419
|
+
if (nameHits.length > 0) {
|
|
420
|
+
score += 6 * Math.min(nameHits.length, 3)
|
|
421
|
+
reasons.push(`名称命中:${nameHits.slice(0, 3).join(' / ')}`)
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// 3) 说明 token 命中(每个 +2,封顶 +6)
|
|
425
|
+
const descriptionHits = tokens.filter((token) => descriptionText.includes(token))
|
|
426
|
+
if (descriptionHits.length > 0) {
|
|
427
|
+
score += Math.min(6, 2 * descriptionHits.length)
|
|
428
|
+
reasons.push(`说明提到:${descriptionHits.slice(0, 3).join(' / ')}`)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// 4) 标签命中(每个 +3,封顶 +9)
|
|
432
|
+
const tagHits = tokens.filter((token) => tags.includes(token))
|
|
433
|
+
if (tagHits.length > 0) {
|
|
434
|
+
score += Math.min(9, 3 * tagHits.length)
|
|
435
|
+
reasons.push(`标签命中:${tagHits.slice(0, 3).join(' / ')}`)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// 5) 能力命中意图(每个 +5,封顶 +15)
|
|
439
|
+
const kindHits = intentKinds.filter((kind) => kinds.includes(kind))
|
|
440
|
+
if (kindHits.length > 0) {
|
|
441
|
+
score += 5 * Math.min(kindHits.length, 3)
|
|
442
|
+
reasons.push(`能力匹配:${kindHits.map((kind) => KIND_LABELS[kind] || kind).join(' / ')}`)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// 6) 节点类 / 参数名 / 模型名命中(每个 +2,封顶 +6)
|
|
446
|
+
const extraHits = tokens.filter((token) => extraWords.some((word) => word.includes(token)))
|
|
447
|
+
if (extraHits.length > 0) {
|
|
448
|
+
score += Math.min(6, 2 * extraHits.length)
|
|
449
|
+
reasons.push(`节点/参数/模型提到:${extraHits.slice(0, 3).join(' / ')}`)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// 7) 误配高危媒体类型(视频/音频)且任务没要求 → 重罚(避免「视频流」抢「单图放大」这类任务)
|
|
453
|
+
const risky = kinds.filter((kind) => (kind === 'video' || kind === 'audio') && !intentKinds.includes(kind))
|
|
454
|
+
if (risky.length > 0) {
|
|
455
|
+
score -= 8 * risky.length
|
|
456
|
+
reasons.push(`候选包含未要求的${risky.map((kind) => KIND_LABELS[kind] || kind).join('/')},降权`)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// 8) 与意图无关的额外能力轻度降权(能力越杂越不专)
|
|
460
|
+
const unrelated = kinds.filter((kind) => ['controlnet', 'inpaint', 'upscale', 'lora'].includes(kind) && !intentKinds.includes(kind))
|
|
461
|
+
if (unrelated.length > 0) score -= 2 * Math.min(unrelated.length, 2)
|
|
462
|
+
|
|
463
|
+
// 9) 示例/测试类工作流降权(「示例」流通常不是最佳生产选择)
|
|
464
|
+
if (/示例|example|test|测试|demo|副本|copy/i.test(nameText)) {
|
|
465
|
+
score -= 3
|
|
466
|
+
reasons.push('名称像示例/测试工作流,降权')
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const matched = score > 0
|
|
470
|
+
if (!matched) reasons.push('没有明显匹配,按可用工作流列出')
|
|
471
|
+
return { index, score, matched, reasons: reasons.slice(0, 4) }
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
scored.sort((a, b) => (b.score - a.score) || (a.index - b.index))
|
|
475
|
+
return { matches: scored.slice(0, safeLimit), tokens, intentKinds }
|
|
476
|
+
}
|