koishi-plugin-p-draw 1.6.5 → 1.6.7
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/index.js +119 -16
- package/lib/comfy.js +6 -1
- package/lib/image.js +81 -0
- package/lib/parse.js +12 -1
- package/lib/workflows.js +82 -2
- package/package.json +1 -1
- package/readme.md +25 -7
package/index.js
CHANGED
|
@@ -128,7 +128,7 @@ exports.Config = Schema.object({
|
|
|
128
128
|
width: Schema.number().description('默认宽度'),
|
|
129
129
|
height: Schema.number().description('默认高度'),
|
|
130
130
|
}).description('该模型的参数覆盖')).default({}).description('按模型覆盖参数:key=模型文件名,value 只填要覆盖的字段。显式写了的字段会覆盖工作流内取值'),
|
|
131
|
-
}).description('② 模型与采样参数'),
|
|
131
|
+
}).description('② 模型与采样参数').collapse(),
|
|
132
132
|
|
|
133
133
|
prompt: Schema.object({
|
|
134
134
|
qualityPrefix: Schema.string().default('').description('质量词前缀(Aesthetic 1.1 建议留空;Base 模型可填 masterpiece, best quality, score_7)'),
|
|
@@ -138,13 +138,13 @@ exports.Config = Schema.object({
|
|
|
138
138
|
activeArtistPreset: Schema.string().default('').description('启用的画师组名称'),
|
|
139
139
|
artistPresets: Schema.array(Schema.string()).default([]).description('画师组(格式:名称=tags)'),
|
|
140
140
|
fixedCharacters: Schema.array(Schema.string()).default([]).description('固定角色(格式:角色名=tags;仅兼容旧配置,运行时以数据库为准)'),
|
|
141
|
-
}).description('③ 提示词与画师'),
|
|
141
|
+
}).description('③ 提示词与画师').collapse(),
|
|
142
142
|
|
|
143
143
|
queue: Schema.object({
|
|
144
144
|
queueEnabled: Schema.boolean().default(true).description('启用生成队列(逐张顺序执行)'),
|
|
145
145
|
queueMaxRequests: Schema.number().default(5).description('队列最大任务数(0 表示不限制)'),
|
|
146
146
|
batchMax: Schema.number().default(4).description('单次指令最多生成的张数'),
|
|
147
|
-
}).description('④ 队列与批量'),
|
|
147
|
+
}).description('④ 队列与批量').collapse(),
|
|
148
148
|
|
|
149
149
|
pricing: Schema.object({
|
|
150
150
|
price: Schema.number().default(500).description('一张图消耗的 P 点'),
|
|
@@ -152,7 +152,7 @@ exports.Config = Schema.object({
|
|
|
152
152
|
couponPrice: Schema.number().default(3000).description('提示词优化券单价(可被 data/p-shop.json 覆盖)'),
|
|
153
153
|
couponAskTimeout: Schema.number().default(60).description('优化券确认等待时间(秒)'),
|
|
154
154
|
adminUsers: Schema.array(Schema.string()).default([]).description('免 P 点管理员用户 ID'),
|
|
155
|
-
}).description('⑤ P 点与优化券'),
|
|
155
|
+
}).description('⑤ P 点与优化券').collapse(),
|
|
156
156
|
|
|
157
157
|
access: Schema.object({
|
|
158
158
|
adminOnly: Schema.boolean().default(false).description('仅管理员可用'),
|
|
@@ -161,7 +161,7 @@ exports.Config = Schema.object({
|
|
|
161
161
|
allowedGroupIds: Schema.array(Schema.string()).default([]).description('群白名单(留空不限制)'),
|
|
162
162
|
blockedGroupIds: Schema.array(Schema.string()).default([]).description('群黑名单(优先于白名单)'),
|
|
163
163
|
outputLogs: Schema.boolean().default(true).description('输出详细日志'),
|
|
164
|
-
}).description('⑥ 权限与日志'),
|
|
164
|
+
}).description('⑥ 权限与日志').collapse(),
|
|
165
165
|
|
|
166
166
|
workflow: Schema.object({
|
|
167
167
|
customWorkflowEnabled: Schema.boolean().default(false).description('使用自定义 ComfyUI 工作流 JSON'),
|
|
@@ -189,6 +189,9 @@ exports.Config = Schema.object({
|
|
|
189
189
|
samplerName: Schema.string().description('该预设固定采样器'),
|
|
190
190
|
scheduler: Schema.string().description('该预设固定调度器'),
|
|
191
191
|
overrideParameters: Schema.boolean().description('用上面的参数覆盖工作流内取值'),
|
|
192
|
+
denoise: Schema.number().description('图生图的重绘幅度 0–1(1=整张重绘)。只对需要图片输入的工作流有意义'),
|
|
193
|
+
imageNodeId: Schema.string().description('图片输入节点 ID(LoadImage)。留空则自动使用工作流里的图片节点'),
|
|
194
|
+
price: Schema.number().description('该预设每张消耗的 P 点(留空沿用全局 price / multiPrice)'),
|
|
192
195
|
overrideModel: Schema.boolean().description('是否把 unetName 写进这个工作流的模型节点(留空沿用全局)'),
|
|
193
196
|
modelLoaderNodeId: Schema.string().description('该预设的模型加载节点 ID(留空沿用全局)'),
|
|
194
197
|
}).description('预设')).default({}).description('工作流预设:key=预设名。指令里用 `--工作流 <名称>` 或名称/别名开头选择(如 `画图 极速:1girl`)'),
|
|
@@ -272,9 +275,11 @@ const {
|
|
|
272
275
|
MULTI_PERSON_NEGATIVE_TAGS, buildMultiPersonPlanPrompt, parseMultiPersonPlan,
|
|
273
276
|
renderMultiPersonCharacter, multiPersonAutoSize,
|
|
274
277
|
} = require('./lib/multi')
|
|
278
|
+
const { fileURLToPath } = require('url')
|
|
275
279
|
const { buildComfyClient } = require('./lib/http')
|
|
276
280
|
const { createOutboundFetch, normalizeProxyUrl, proxySupportAvailable } = require('./lib/net')
|
|
277
281
|
const { buildLlmChain, hasLlm, buildChatBody, runLlmChain } = require('./lib/llm')
|
|
282
|
+
const { uploadImageToComfy, decodeDataUrl, guessContentType } = require('./lib/image')
|
|
278
283
|
exports.apply = async function apply(ctx, rawConfig) {
|
|
279
284
|
// 配置统一摊平成扁平 cfg:同时接受新的分组写法和老版本的扁平写法
|
|
280
285
|
const { config: cfg, legacy } = normalizeConfig(rawConfig)
|
|
@@ -414,9 +419,15 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
414
419
|
return out
|
|
415
420
|
}
|
|
416
421
|
|
|
422
|
+
// 预设可以单独定价;没配就回落到全局 price / multiPrice
|
|
423
|
+
function presetPrice(preset) {
|
|
424
|
+
if (!preset || preset.price === undefined || preset.price === null || preset.price === '') return null
|
|
425
|
+
const value = Number(preset.price)
|
|
426
|
+
return Number.isFinite(value) && value >= 0 ? value : null
|
|
427
|
+
}
|
|
428
|
+
|
|
417
429
|
// 体检:这个预设现在能不能真的跑(能否从纯文本启动)
|
|
418
|
-
function inspectPreset(preset) {
|
|
419
|
-
return inspectWorkflowFile(preset.path, {
|
|
430
|
+
function inspectPreset(preset) { return inspectWorkflowFile(preset.path, {
|
|
420
431
|
positivePromptNodeId: preset.positivePromptNodeId || '',
|
|
421
432
|
negativePromptNodeId: preset.negativePromptNodeId || '',
|
|
422
433
|
resolutionNodeId: preset.resolutionNodeId || '',
|
|
@@ -436,6 +447,81 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
436
447
|
return { ok: true, preset }
|
|
437
448
|
}
|
|
438
449
|
|
|
450
|
+
// ---------------- 图生图:从消息取图 → 下载 → 上传到 ComfyUI ----------------
|
|
451
|
+
|
|
452
|
+
// 消息里带的图片地址(http / file / base64 / data: 都可能有)
|
|
453
|
+
function messageImageSources(session) {
|
|
454
|
+
const sources = []
|
|
455
|
+
try {
|
|
456
|
+
const message = session?.event?.message
|
|
457
|
+
if (!message) return sources
|
|
458
|
+
for (const element of h.select(message, 'img')) {
|
|
459
|
+
const src = element?.attrs?.src || element?.attrs?.url
|
|
460
|
+
if (src) sources.push(String(src))
|
|
461
|
+
}
|
|
462
|
+
} catch (e) { /* ignore */ }
|
|
463
|
+
return sources
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function fetchImageBuffer(src) {
|
|
467
|
+
const text = String(src || '')
|
|
468
|
+
const dataUrl = decodeDataUrl(text)
|
|
469
|
+
if (dataUrl) return dataUrl
|
|
470
|
+
if (/^base64:\/\//i.test(text)) {
|
|
471
|
+
const decoded = decodeDataUrl('data:image/png;base64,' + text.slice('base64://'.length))
|
|
472
|
+
if (decoded) return decoded
|
|
473
|
+
throw new Error('base64 图片解码失败')
|
|
474
|
+
}
|
|
475
|
+
if (/^file:\/\//i.test(text)) {
|
|
476
|
+
const filePath = fileURLToPath(text)
|
|
477
|
+
return { buffer: await fsp.readFile(filePath), contentType: guessContentType(filePath) }
|
|
478
|
+
}
|
|
479
|
+
if (/^https?:\/\//i.test(text)) {
|
|
480
|
+
const res = await outboundFetch(text, {})
|
|
481
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
482
|
+
const buffer = Buffer.from(await res.arrayBuffer())
|
|
483
|
+
const headerType = res.headers && typeof res.headers.get === 'function' ? res.headers.get('content-type') : ''
|
|
484
|
+
return { buffer, contentType: headerType || guessContentType(text) }
|
|
485
|
+
}
|
|
486
|
+
throw new Error('不支持的图片来源')
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// 判断当前要用的工作流是否吃图片,并把消息里的图准备好
|
|
490
|
+
async function prepareImageInputs(session, preset) {
|
|
491
|
+
let needsImage = false
|
|
492
|
+
try {
|
|
493
|
+
if (preset) {
|
|
494
|
+
needsImage = Boolean(inspectPreset(preset)?.analysis?.imageInputClasses?.length)
|
|
495
|
+
} else if (cfg.customWorkflowEnabled && cfg.customWorkflowPath) {
|
|
496
|
+
const report = inspectWorkflowFile(cfg.customWorkflowPath, cfg, workflowOpts())
|
|
497
|
+
needsImage = Boolean(report?.analysis?.imageInputClasses?.length)
|
|
498
|
+
}
|
|
499
|
+
} catch (e) { /* 读不到就当不需要 */ }
|
|
500
|
+
|
|
501
|
+
if (!needsImage) return { ok: true, files: [], needsImage: false }
|
|
502
|
+
|
|
503
|
+
const sources = messageImageSources(session)
|
|
504
|
+
if (!sources.length) {
|
|
505
|
+
return {
|
|
506
|
+
ok: false,
|
|
507
|
+
needsImage: true,
|
|
508
|
+
message: '这个工作流需要图片输入:请把参考图和指令一起发送(例如:发一张图 + 「画图 重绘:保持角色,换成水彩风格」)。',
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const files = []
|
|
513
|
+
for (const src of sources) {
|
|
514
|
+
try {
|
|
515
|
+
const { buffer, contentType } = await fetchImageBuffer(src)
|
|
516
|
+
files.push(await uploadImageToComfy(outboundFetch, baseUrl(), { buffer, contentType }))
|
|
517
|
+
} catch (e) {
|
|
518
|
+
return { ok: false, needsImage: true, message: `图片处理失败:${e.message}` }
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (cfg.outputLogs) logger.info(`[p-draw] 已上传 ${files.length} 张参考图:${files.join(', ')}`)
|
|
522
|
+
return { ok: true, files, needsImage: true }
|
|
523
|
+
}
|
|
524
|
+
|
|
439
525
|
// A4:自定义工作流(Aesthetic 1.1)默认跳过质量前缀注入
|
|
440
526
|
function shouldSkipQualityPrefix() {
|
|
441
527
|
return Boolean(cfg.customWorkflowEnabled && cfg.skipQualityPrefixForCustomWorkflow)
|
|
@@ -643,7 +729,10 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
643
729
|
for (const preset of presets) {
|
|
644
730
|
const report = inspectPreset(preset)
|
|
645
731
|
const aliases = (preset.aliases || []).length ? `(别名:${preset.aliases.join('、')})` : ''
|
|
646
|
-
|
|
732
|
+
const unit = presetPrice(preset)
|
|
733
|
+
const priceTag = unit != null ? ` ${unit} P/张` : ' 默认价'
|
|
734
|
+
const imageTag = report.needsImage ? ' 🖼 需带参考图' : ''
|
|
735
|
+
lines.push(`${report.ok ? '✅' : '❌'} ${preset.name}${aliases}${imageTag}${priceTag}`)
|
|
647
736
|
if (report.ok) {
|
|
648
737
|
const analysis = report.analysis
|
|
649
738
|
const pos = report.targets.positive.map(id => `#${id}`).join('、')
|
|
@@ -995,6 +1084,10 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
995
1084
|
modelParams: overrideKeys,
|
|
996
1085
|
overrideModel: baseCfg.workflowOverrideModel !== false,
|
|
997
1086
|
modelLoaderNodeId: baseCfg.modelLoaderNodeId || '',
|
|
1087
|
+
images: overrides.images || [],
|
|
1088
|
+
denoise: overrides.denoise != null ? overrides.denoise
|
|
1089
|
+
: (preset && preset.denoise != null && preset.denoise !== '' ? Number(preset.denoise) : undefined),
|
|
1090
|
+
imageNodeId: (preset && preset.imageNodeId) || '',
|
|
998
1091
|
}))
|
|
999
1092
|
|
|
1000
1093
|
const clientId = crypto.randomUUID()
|
|
@@ -1725,7 +1818,7 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
1725
1818
|
const USERID = session.userId
|
|
1726
1819
|
const isAdmin = isAdminUser(session)
|
|
1727
1820
|
const unet = await resolveUnet(USERID)
|
|
1728
|
-
|
|
1821
|
+
let price = Math.max(0, parseInt(cfg.multiPrice) || cfg.price)
|
|
1729
1822
|
if (cfg.outputLogs) {
|
|
1730
1823
|
logger.info(`[p-draw] 多人请求 userId=${USERID} isAdmin=${isAdmin}`)
|
|
1731
1824
|
}
|
|
@@ -1751,6 +1844,8 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
1751
1844
|
if (usable.ok) activePreset = usable.preset
|
|
1752
1845
|
else if (cfg.outputLogs) logger.warn(`[p-draw] 默认预设不可用,已回落:${usable.message}`)
|
|
1753
1846
|
}
|
|
1847
|
+
const presetUnitPrice = presetPrice(activePreset)
|
|
1848
|
+
if (presetUnitPrice != null) price = presetUnitPrice
|
|
1754
1849
|
const text = parsedPreset.prompt
|
|
1755
1850
|
if (!text) return session.text('.multi-usage')
|
|
1756
1851
|
const count = parsedBatch.count
|
|
@@ -2231,11 +2326,19 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2231
2326
|
const text = parsedPreset.prompt
|
|
2232
2327
|
const seed = parsedSeed.seed
|
|
2233
2328
|
const count = parsedBatch.count
|
|
2329
|
+
// 预设可单独定价,未配置则用全局 price
|
|
2330
|
+
const unitPrice = presetPrice(activePreset) ?? Math.max(0, Number(cfg.price) || 0)
|
|
2234
2331
|
// 命令级参数优先于预设 / modelParams / 全局配置(见 runComfyGenerate)
|
|
2332
|
+
// 图生图:工作流吃图时先把消息里的图下好、传到 ComfyUI;没带图就直接拦下(不扣点)
|
|
2333
|
+
const imagePlan = await prepareImageInputs(session, activePreset)
|
|
2334
|
+
if (!imagePlan.ok) return imagePlan.message
|
|
2335
|
+
|
|
2235
2336
|
const tuningOverrides = Object.assign(
|
|
2236
2337
|
activePreset ? { preset: activePreset } : {},
|
|
2237
2338
|
parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
|
|
2238
2339
|
parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
|
|
2340
|
+
parsedTuning.denoise != null ? { denoise: parsedTuning.denoise } : {},
|
|
2341
|
+
imagePlan.files.length ? { images: imagePlan.files } : {},
|
|
2239
2342
|
)
|
|
2240
2343
|
if (cfg.outputLogs && (parsedTuning.steps != null || parsedTuning.cfg != null)) {
|
|
2241
2344
|
logger.info(`[p-draw] 命令级参数覆盖:steps=${parsedTuning.steps ?? '-'} cfg=${parsedTuning.cfg ?? '-'}`)
|
|
@@ -2243,7 +2346,7 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2243
2346
|
|
|
2244
2347
|
// P 点校验(按总价 = 张数 × 单价)
|
|
2245
2348
|
// P 点校验(按总价 = 张数 × 单价)
|
|
2246
|
-
const pcheck = await precheckPoints(session, USERID, isAdmin, count *
|
|
2349
|
+
const pcheck = await precheckPoints(session, USERID, isAdmin, count * unitPrice)
|
|
2247
2350
|
if (!pcheck.ok) return pcheck.message
|
|
2248
2351
|
|
|
2249
2352
|
// 原样模式
|
|
@@ -2333,8 +2436,8 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2333
2436
|
|
|
2334
2437
|
// 扣 P 点(一次性扣除总价)
|
|
2335
2438
|
if (!isAdmin) {
|
|
2336
|
-
const saving = await deductP(USERID, count *
|
|
2337
|
-
if (cfg.outputLogs) logger.info(`[p-draw] ${USERID} 已扣除 ${count *
|
|
2439
|
+
const saving = await deductP(USERID, count * unitPrice)
|
|
2440
|
+
if (cfg.outputLogs) logger.info(`[p-draw] ${USERID} 已扣除 ${count * unitPrice} P 点(${count} 张 × ${unitPrice}),余额 ${saving - count * unitPrice}`)
|
|
2338
2441
|
}
|
|
2339
2442
|
|
|
2340
2443
|
// 用户手写了 negative: 区块时,默认负面词仍保留;用户 tag 只补充未出现的部分。
|
|
@@ -2356,7 +2459,7 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2356
2459
|
}
|
|
2357
2460
|
const generated = await runComfyGenerate(p, parsedSize.size, generationOverrides)
|
|
2358
2461
|
return { ...generated, prompt: p }
|
|
2359
|
-
}, { USERID, isAdmin, totalPrice: count *
|
|
2462
|
+
}, { USERID, isAdmin, totalPrice: count * unitPrice })
|
|
2360
2463
|
if (!queued.ok) return queued.message
|
|
2361
2464
|
const queuedTasks = queued.tasks
|
|
2362
2465
|
const firstPosition = queued.firstPosition
|
|
@@ -2399,7 +2502,7 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2399
2502
|
return result
|
|
2400
2503
|
}
|
|
2401
2504
|
|
|
2402
|
-
const { results, successCount } = await executeBatch(USERID, isAdmin, count,
|
|
2505
|
+
const { results, successCount } = await executeBatch(USERID, isAdmin, count, unitPrice, runOne)
|
|
2403
2506
|
|
|
2404
2507
|
// 汇总
|
|
2405
2508
|
const allOutputs = []
|
|
@@ -2418,7 +2521,7 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2418
2521
|
|
|
2419
2522
|
const chargeNotice = buildChargeNotice({
|
|
2420
2523
|
isAdmin,
|
|
2421
|
-
totalPrice: successCount *
|
|
2524
|
+
totalPrice: successCount * unitPrice,
|
|
2422
2525
|
unetName: unet,
|
|
2423
2526
|
seeds,
|
|
2424
2527
|
})
|
|
@@ -2580,5 +2683,5 @@ exports.apply = async function apply(ctx, rawConfig) {
|
|
|
2580
2683
|
})
|
|
2581
2684
|
|
|
2582
2685
|
// 暴露内部接口供自动化测试调用(Koishi 忽略 apply 返回值,不影响生产行为)
|
|
2583
|
-
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir, normalizeConfig, presetList, presetOverviewText }
|
|
2686
|
+
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir, normalizeConfig, presetList, presetOverviewText, presetPrice }
|
|
2584
2687
|
}
|
package/lib/comfy.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// ComfyUI 结果等待与输出提取。
|
|
2
2
|
// waitComfyResult 依赖一个注入的 comfyGet(由 http 客户端提供),可独立单测。
|
|
3
3
|
|
|
4
|
+
// 从 /history 结果里取出图片。
|
|
5
|
+
// PreviewImage 之类的节点会产出 type='temp' 的临时预览图(修脸修手工作流一次能有十几张),
|
|
6
|
+
// 这些不该发给用户;优先只取 SaveImage 的 type='output'。
|
|
7
|
+
// 若整条工作流只有预览节点、没有 SaveImage,则退回取全部,避免什么都取不到。
|
|
4
8
|
function outputImages(history) {
|
|
5
9
|
const images = []
|
|
6
10
|
const outputs = history.outputs || {}
|
|
@@ -12,7 +16,8 @@ function outputImages(history) {
|
|
|
12
16
|
}
|
|
13
17
|
}
|
|
14
18
|
}
|
|
15
|
-
|
|
19
|
+
const finals = images.filter(image => image.type !== 'temp')
|
|
20
|
+
return finals.length ? finals : images
|
|
16
21
|
}
|
|
17
22
|
|
|
18
23
|
// ------------------------------------------------------------------
|
package/lib/image.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// 图生图用的图片搬运:把聊天里的图片下载下来,再上传到 ComfyUI 的 input 目录。
|
|
2
|
+
// 只做纯逻辑 + 一个注入的 fetch,方便单测。
|
|
3
|
+
|
|
4
|
+
function guessContentType(name) {
|
|
5
|
+
const ext = String(name || '').toLowerCase().split('.').pop()
|
|
6
|
+
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
|
|
7
|
+
if (ext === 'webp') return 'image/webp'
|
|
8
|
+
if (ext === 'gif') return 'image/gif'
|
|
9
|
+
if (ext === 'bmp') return 'image/bmp'
|
|
10
|
+
return 'image/png'
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// data:image/png;base64,xxxx → { buffer, contentType }
|
|
14
|
+
function decodeDataUrl(source) {
|
|
15
|
+
const text = String(source || '')
|
|
16
|
+
const match = text.match(/^data:([^;,]+)?(;base64)?,([\s\S]*)$/i)
|
|
17
|
+
if (!match) return null
|
|
18
|
+
const contentType = match[1] || 'image/png'
|
|
19
|
+
const isBase64 = Boolean(match[2])
|
|
20
|
+
try {
|
|
21
|
+
const buffer = isBase64
|
|
22
|
+
? Buffer.from(match[3], 'base64')
|
|
23
|
+
: Buffer.from(decodeURIComponent(match[3]), 'binary')
|
|
24
|
+
return { buffer, contentType }
|
|
25
|
+
} catch (e) {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 组装 multipart/form-data(不引第三方依赖)
|
|
31
|
+
function buildMultipart(fields, file) {
|
|
32
|
+
const boundary = `----pdraw${Date.now().toString(16)}${Math.random().toString(16).slice(2, 8)}`
|
|
33
|
+
const chunks = []
|
|
34
|
+
for (const [name, value] of Object.entries(fields || {})) {
|
|
35
|
+
chunks.push(Buffer.from(
|
|
36
|
+
`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`,
|
|
37
|
+
'utf8',
|
|
38
|
+
))
|
|
39
|
+
}
|
|
40
|
+
const contentType = file.contentType || guessContentType(file.filename)
|
|
41
|
+
chunks.push(Buffer.from(
|
|
42
|
+
`--${boundary}\r\nContent-Disposition: form-data; name="image"; filename="${file.filename}"\r\nContent-Type: ${contentType}\r\n\r\n`,
|
|
43
|
+
'utf8',
|
|
44
|
+
))
|
|
45
|
+
chunks.push(file.buffer)
|
|
46
|
+
chunks.push(Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8'))
|
|
47
|
+
return { body: Buffer.concat(chunks), contentType: `multipart/form-data; boundary=${boundary}` }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 上传到 ComfyUI,返回 LoadImage 节点可直接用的文件名(可能带子目录)
|
|
51
|
+
async function uploadImageToComfy(fetchImpl, baseUrl, { buffer, filename, contentType, subfolder = 'pdraw', overwrite = 'true' }) {
|
|
52
|
+
if (!Buffer.isBuffer(buffer) || !buffer.length) throw new Error('图片内容为空')
|
|
53
|
+
// 没给文件名时生成唯一名,避免并发时互相覆盖
|
|
54
|
+
const fallback = `pdraw_${Date.now()}_${Math.random().toString(16).slice(2, 8)}.png`
|
|
55
|
+
const safeName = String(filename || fallback).replace(/[\\/:*?"<>|]/g, '_')
|
|
56
|
+
const { body, contentType: headerValue } = buildMultipart(
|
|
57
|
+
{ type: 'input', subfolder, overwrite },
|
|
58
|
+
{ buffer, filename: safeName, contentType },
|
|
59
|
+
)
|
|
60
|
+
const res = await fetchImpl(`${String(baseUrl).replace(/\/+$/, '')}/upload/image`, {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: { 'Content-Type': headerValue },
|
|
63
|
+
body,
|
|
64
|
+
})
|
|
65
|
+
if (!res.ok) {
|
|
66
|
+
const detail = await res.text().catch(() => '')
|
|
67
|
+
throw new Error(`上传图片失败:HTTP ${res.status}${detail ? ' ' + detail.slice(0, 120) : ''}`)
|
|
68
|
+
}
|
|
69
|
+
const data = await res.json()
|
|
70
|
+
const name = data && data.name
|
|
71
|
+
if (!name) throw new Error('上传图片失败:ComfyUI 没有返回文件名')
|
|
72
|
+
const sub = data.subfolder ? String(data.subfolder).replace(/^\/+|\/+$/g, '') : ''
|
|
73
|
+
return sub ? `${sub}/${name}` : name
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = {
|
|
77
|
+
guessContentType,
|
|
78
|
+
decodeDataUrl,
|
|
79
|
+
buildMultipart,
|
|
80
|
+
uploadImageToComfy,
|
|
81
|
+
}
|
package/lib/parse.js
CHANGED
|
@@ -159,6 +159,8 @@ const CFG_LIMIT = { min: 0, max: 30 }
|
|
|
159
159
|
|
|
160
160
|
const STEPS_PATTERN = /(?<!\S)--(?:steps|步数)\s*(?:=|=|:|:)?\s*(\d+)/i
|
|
161
161
|
const CFG_PATTERN = /(?<!\S)--(?:cfg|强度)\s*(?:=|=|:|:)?\s*(\d+(?:\.\d+)?)/i
|
|
162
|
+
// 重绘幅度(图生图用):--denoise 0.6 / --重绘 0.6 / --重绘幅度 0.6
|
|
163
|
+
const DENOISE_PATTERN = /(?<!\S)--(?:denoise|重绘幅度|重绘率|重绘)\s*(?:=|=|:|:)?\s*(\d+(?:\.\d+)?)/i
|
|
162
164
|
|
|
163
165
|
// 与 parseSeed 一致的剥离清理:去掉 token 后收拢多余分隔符与空白
|
|
164
166
|
function stripMatchedToken(prompt, match) {
|
|
@@ -188,7 +190,15 @@ function parseStepsCfg(text) {
|
|
|
188
190
|
if (Number.isFinite(value) && value >= CFG_LIMIT.min) cfg = Math.min(value, CFG_LIMIT.max)
|
|
189
191
|
}
|
|
190
192
|
|
|
191
|
-
|
|
193
|
+
let denoise = null
|
|
194
|
+
const denoiseMatch = prompt.match(DENOISE_PATTERN)
|
|
195
|
+
if (denoiseMatch) {
|
|
196
|
+
const value = Number(denoiseMatch[1])
|
|
197
|
+
prompt = stripMatchedToken(prompt, denoiseMatch)
|
|
198
|
+
if (Number.isFinite(value) && value >= 0) denoise = Math.min(value, 1)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return { steps, cfg, denoise, prompt }
|
|
192
202
|
}
|
|
193
203
|
|
|
194
204
|
// 工作流预设选择:--工作流 名称 / --workflow 名称,或开头裸写名称/别名(如「极速:描述」)
|
|
@@ -348,6 +358,7 @@ module.exports = {
|
|
|
348
358
|
CFG_LIMIT,
|
|
349
359
|
STEPS_PATTERN,
|
|
350
360
|
CFG_PATTERN,
|
|
361
|
+
DENOISE_PATTERN,
|
|
351
362
|
stripMatchedToken,
|
|
352
363
|
parseStepsCfg,
|
|
353
364
|
matchPreset,
|
package/lib/workflows.js
CHANGED
|
@@ -343,6 +343,18 @@ function customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVa
|
|
|
343
343
|
// 模型名注入:让 unetName / p-draw 模型 对自定义工作流也生效
|
|
344
344
|
const modelResult = applyModelOverride(workflow, cfg, opts)
|
|
345
345
|
|
|
346
|
+
// 图片输入(图生图):工作流需要图却没给 → 明确报错,不要静默跑出个错的图
|
|
347
|
+
const imageResult = applyImageInputs(workflow, opts.images, opts)
|
|
348
|
+
if (imageResult.reason === 'missing-image') {
|
|
349
|
+
const names = imageResult.loaders.map(loader => `#${loader.id} ${loader.classType}`).join('、')
|
|
350
|
+
throw new Error(`这个工作流需要图片输入(${names}),请随指令带一张参考图再发送`)
|
|
351
|
+
}
|
|
352
|
+
if (String(imageResult.reason).startsWith('node-not-found')) {
|
|
353
|
+
throw new Error(`配置的图片节点 ID「${opts.imageNodeId}」不存在于工作流中`)
|
|
354
|
+
}
|
|
355
|
+
// 重绘幅度:只在显式给出时覆盖,保留多段工作流各段自己的 denoise
|
|
356
|
+
applyDenoise(workflow, opts.denoise)
|
|
357
|
+
|
|
346
358
|
for (const nodeId of targets.positive) {
|
|
347
359
|
if (workflow[nodeId] && workflow[nodeId].inputs) workflow[nodeId].inputs.text = prompt
|
|
348
360
|
}
|
|
@@ -463,6 +475,69 @@ function applyModelOverride(workflow, cfg, opts = {}) {
|
|
|
463
475
|
return { applied: true, loaders, targets, model, reason: '' }
|
|
464
476
|
}
|
|
465
477
|
|
|
478
|
+
// 体检:这个工作流能不能在「纯文本」模式下跑,需要什么额外输入
|
|
479
|
+
// 找出工作流里的图片输入节点(LoadImage 等)
|
|
480
|
+
function findImageLoaderNodes(workflow) {
|
|
481
|
+
const found = []
|
|
482
|
+
for (const [nodeId, node] of Object.entries(workflow)) {
|
|
483
|
+
if (!node || typeof node !== 'object') continue
|
|
484
|
+
const classType = String(node.class_type || '')
|
|
485
|
+
if (!IMAGE_INPUT_RE.test(classType)) continue
|
|
486
|
+
const inputs = node.inputs
|
|
487
|
+
if (!inputs || typeof inputs !== 'object') continue
|
|
488
|
+
const inputName = 'image' in inputs
|
|
489
|
+
? 'image'
|
|
490
|
+
: (Object.keys(inputs).find(key => typeof inputs[key] === 'string') || 'image')
|
|
491
|
+
found.push({ id: String(nodeId), classType, inputName })
|
|
492
|
+
}
|
|
493
|
+
return found
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// 把已上传到 ComfyUI 的图片文件名写进 LoadImage 节点。
|
|
497
|
+
// 多个 LoadImage 时按顺序分配;imageNodeId 可指定只改一个。
|
|
498
|
+
function applyImageInputs(workflow, images, opts = {}) {
|
|
499
|
+
const loaders = findImageLoaderNodes(workflow)
|
|
500
|
+
const provided = (Array.isArray(images) ? images : []).filter(Boolean)
|
|
501
|
+
|
|
502
|
+
if (!loaders.length) {
|
|
503
|
+
return { applied: false, loaders, targets: [], reason: provided.length ? 'no-loader' : 'not-needed' }
|
|
504
|
+
}
|
|
505
|
+
if (!provided.length) {
|
|
506
|
+
return { applied: false, loaders, targets: [], reason: 'missing-image' }
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const pinned = cleanNodeId(opts.imageNodeId)
|
|
510
|
+
let targets = loaders
|
|
511
|
+
if (pinned) {
|
|
512
|
+
targets = loaders.filter(loader => loader.id === pinned)
|
|
513
|
+
if (!targets.length) return { applied: false, loaders, targets: [], reason: `node-not-found:${pinned}` }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
targets.forEach((loader, index) => {
|
|
517
|
+
const value = provided[index] || provided[provided.length - 1]
|
|
518
|
+
if (value) workflow[loader.id].inputs[loader.inputName] = value
|
|
519
|
+
})
|
|
520
|
+
return { applied: true, loaders, targets, reason: '' }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 重绘幅度:只写给采样器节点(有 denoise 输入的),用于图生图。
|
|
524
|
+
// 不传就不动 —— 多段工作流各段自己的 denoise 才不会被压平。
|
|
525
|
+
function applyDenoise(workflow, denoise) {
|
|
526
|
+
if (denoise === undefined || denoise === null || denoise === '') return { applied: false, count: 0 }
|
|
527
|
+
const value = Number(denoise)
|
|
528
|
+
if (!Number.isFinite(value)) return { applied: false, count: 0 }
|
|
529
|
+
let count = 0
|
|
530
|
+
for (const node of Object.values(workflow)) {
|
|
531
|
+
if (!node || typeof node !== 'object') continue
|
|
532
|
+
if (!/sampler/i.test(String(node.class_type || ''))) continue
|
|
533
|
+
const inputs = node.inputs
|
|
534
|
+
if (!inputs || typeof inputs !== 'object' || !('denoise' in inputs)) continue
|
|
535
|
+
inputs.denoise = value
|
|
536
|
+
count += 1
|
|
537
|
+
}
|
|
538
|
+
return { applied: count > 0, count }
|
|
539
|
+
}
|
|
540
|
+
|
|
466
541
|
// 体检:这个工作流能不能在「纯文本」模式下跑,需要什么额外输入
|
|
467
542
|
function analyzeWorkflow(workflow) {
|
|
468
543
|
const classes = Object.values(workflow).map(node => String((node && node.class_type) || ''))
|
|
@@ -505,13 +580,15 @@ function inspectWorkflowFile(workflowPath, cfg = {}, opts = {}) {
|
|
|
505
580
|
report.analysis = analyzeWorkflow(workflow)
|
|
506
581
|
const targets = resolveCustomNodeTargets(workflow, cfg)
|
|
507
582
|
report.targets = targets
|
|
583
|
+
// 需要图片输入不算「不可用」——现在支持图生图,只要指令里带图就能跑
|
|
584
|
+
report.needsImage = report.analysis.imageInputClasses.length > 0
|
|
508
585
|
if (targets.errors.length) {
|
|
509
586
|
report.error = targets.errors.join(';')
|
|
510
587
|
return report
|
|
511
588
|
}
|
|
512
|
-
if (!report.analysis.
|
|
589
|
+
if (!report.analysis.hasLatentStart) {
|
|
513
590
|
report.error = report.analysis.requires.length
|
|
514
|
-
? `需要${report.analysis.requires.join('、')}
|
|
591
|
+
? `需要${report.analysis.requires.join('、')},且工作流里找不到可写入尺寸的 latent 节点`
|
|
515
592
|
: '工作流里找不到可写入尺寸的 latent 节点(缺少文生图起点)'
|
|
516
593
|
return report
|
|
517
594
|
}
|
|
@@ -558,6 +635,9 @@ module.exports = {
|
|
|
558
635
|
MODEL_LOADER_INPUTS,
|
|
559
636
|
findModelLoaders,
|
|
560
637
|
applyModelOverride,
|
|
638
|
+
findImageLoaderNodes,
|
|
639
|
+
applyImageInputs,
|
|
640
|
+
applyDenoise,
|
|
561
641
|
analyzeWorkflow,
|
|
562
642
|
inspectWorkflowFile,
|
|
563
643
|
}
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -384,6 +384,24 @@ p-draw:
|
|
|
384
384
|
- [ ] 替换工作流 JSON 后,在 `customWorkflowReloadOnChange: true` 下无需重启插件即生效。
|
|
385
385
|
- [ ] `p-draw 诊断` 能显示实际工作流路径、更新时间与实际解析到的节点 ID。
|
|
386
386
|
|
|
387
|
+
### 图生图(带参考图)
|
|
388
|
+
|
|
389
|
+
需要图片输入的工作流(图生图、分块放大、ControlNet)现在可以直接用:**把参考图和指令一起发**即可。
|
|
390
|
+
|
|
391
|
+
```
|
|
392
|
+
[发一张图] + 画图 重绘:保持角色,换成水彩风格
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
插件会自动完成:从消息里取图 → 下载 → 上传到 ComfyUI 的 `input/pdraw/` → 把返回的文件名写进工作流的 `LoadImage` 节点。
|
|
396
|
+
|
|
397
|
+
- **没带图时会直接拒绝并提示**,既不扣点也不会跑出一张错的图
|
|
398
|
+
- `--重绘 0.6` / `--重绘幅度 0.6` 可临时指定重绘幅度(0–1,越大改动越大)
|
|
399
|
+
- 预设里可固定 `denoise`(重绘幅度)与 `imageNodeId`(多个 `LoadImage` 时指定改哪个)
|
|
400
|
+
- 传多张图时按顺序分配给多个 `LoadImage` 节点(ControlNet 多分支用)
|
|
401
|
+
- 上传文件名带时间戳,并发不会互相覆盖
|
|
402
|
+
|
|
403
|
+
`画图 工作流` 里会用「🖼 需带参考图」标出这类预设。
|
|
404
|
+
|
|
387
405
|
## 工作流预设
|
|
388
406
|
|
|
389
407
|
> 下面片段按字段名展示,实际写在 `workflow:` 分组下(见「配置说明」的分组示例)。
|
|
@@ -431,15 +449,15 @@ defaultWorkflowPreset: 基础文生图
|
|
|
431
449
|
|
|
432
450
|
| # | 工作流 | 节点 | 起点 | 当前版本 |
|
|
433
451
|
|---|---|---|---|---|
|
|
434
|
-
| 09 | Text-to-Image Baseline | 17 | 文本 | ✅
|
|
435
|
-
| 03 | DMDX 4-Step Speed Run | 19 | 文本 |
|
|
436
|
-
| 04 | Three-Stage High-Quality | 26 | 文本 | ✅
|
|
452
|
+
| 09 | Text-to-Image Baseline | 17 | 文本 | ✅ 可用(已转好并实测) |
|
|
453
|
+
| 03 | DMDX 4-Step Speed Run | 19 | 文本 | ⏳ 需 DMDX LoRA(`dmdx_student_final_comfy.safetensors`) |
|
|
454
|
+
| 04 | Three-Stage High-Quality | 26 | 文本 | ✅ 可用(已转好并实测) |
|
|
437
455
|
| 01 | 1.5x Upscale | 20 | 文本 | ✅ 可用(见下方依赖) |
|
|
438
|
-
| 05 | Tiled Upscale | 45 |
|
|
439
|
-
| 08 | T2I + ControlNet + Face/Hand Repair | 60 | 文本 + 控制图 |
|
|
456
|
+
| 05 | Tiled Upscale | 45 | 图片 | ⏳ 已转好,需 `4x_NMKD-Siax_200k.pth`(放 `models/upscale_models`) |
|
|
457
|
+
| 08 | T2I + ControlNet + Face/Hand Repair | 60 | 文本 + 控制图 | ✅ 可用(已裁成单输出;ControlNet 分支默认旁路,需检测器 + SAM 模型) |
|
|
440
458
|
| 02 | ControlNet Precision Control | 32 | 图片 | ❌ 需图生图 |
|
|
441
|
-
| 06 | i2i + ControlNet + Face/Hand Repair | 52 | 图片 |
|
|
442
|
-
| 07 | Image-to-Image | 19 | 图片 |
|
|
459
|
+
| 06 | i2i + ControlNet + Face/Hand Repair | 52 | 图片 | ✅ 可用(已裁成单输出;WD14 打标器已剔除,重绘幅度建议 0.4–0.6) |
|
|
460
|
+
| 07 | Image-to-Image | 19 | 图片 | ✅ 可用(已裁成单输出;`Qwen3VLProcessor` 已剔除,需配 `denoise`) |
|
|
443
461
|
| 10 | Anima-Edit LoRA / IC | 52 | 图片 | ❌ 需图生图 |
|
|
444
462
|
|
|
445
463
|
判断依据是自动体检的结果:**只要 JSON 里出现 `LoadImage` 一类节点,就判定为需要图片输入**。所以 05/08 到底能不能用,取决于你导出时是「从空 latent 开始」还是「从图开始」——`画图 工作流` 会直接告诉你。
|