koishi-plugin-p-draw 1.6.3 → 1.6.4
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 +273 -58
- package/lib/i18n.js +2 -0
- package/lib/parse.js +50 -0
- package/lib/workflows.js +87 -2
- package/package.json +1 -1
- package/readme.md +104 -10
package/index.js
CHANGED
|
@@ -26,6 +26,7 @@ exports.usage = `
|
|
|
26
26
|
输出更详细的配置与连通性诊断。
|
|
27
27
|
- **尺寸:** 支持 \`竖图\` \`横图\` \`方图\` \`长竖图\` \`宽屏\` 或在描述中写 \`1024x1536:描述\` / \`--尺寸 1216x832\`。
|
|
28
28
|
- **采样参数:** 描述里可写 \`--steps 40\` / \`--cfg 3.5\`(也可写 \`--步数\` / \`--强度\`)临时覆盖步数与 CFG,优先于 \`modelParams\` 与全局配置。
|
|
29
|
+
- **工作流预设:** 配置里可登记多套工作流 JSON,用 \`--工作流 名称:描述\` 或直接以名称/别名开头(如 \`极速:描述\`)切换;\`画图 工作流\` 可列出所有预设及是否可用。
|
|
29
30
|
- **原样模式:** 描述前加 \`无优化\` 直接提交写好的 tags。
|
|
30
31
|
- **联网搜索:** 描述中带 \`联网\` / \`搜索\` / \`查一下\` 等词时,会先联网搜索补充角色设定(需配置 Tavily Key)。
|
|
31
32
|
- **画师组:** \`创建画师组 名称=tags\` \`切换画师组 名称\` \`查看画师组\` \`删除画师组 名称\`
|
|
@@ -33,17 +34,76 @@ exports.usage = `
|
|
|
33
34
|
`;
|
|
34
35
|
|
|
35
36
|
const { zhCN } = require('./lib/i18n')
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
// 配置分组定义:组名 → 组内扁平键。
|
|
38
|
+
//
|
|
39
|
+
// 控制台里只有「嵌套 object 字段」才会渲染出折叠箭头(intersect 分支是平铺的),
|
|
40
|
+
// 所以这里用嵌套结构换折叠能力;运行时统一摊平成扁平 cfg,
|
|
41
|
+
// 并兼容老版本写在 koishi.yml 里的扁平键。
|
|
42
|
+
const CONFIG_GROUPS = {
|
|
43
|
+
connection: ['comfyuiBaseUrl', 'timeout', 'pollInterval'],
|
|
44
|
+
model: [
|
|
45
|
+
'unetName', 'useGgufUnet', 'clipName', 'vaeName', 'width', 'height',
|
|
46
|
+
'allowedSizes', 'steps', 'cfg', 'samplerName', 'scheduler', 'modelParams',
|
|
47
|
+
],
|
|
48
|
+
prompt: [
|
|
49
|
+
'qualityPrefix', 'negativePrompt', 'styleTags', 'defaultArtistTags',
|
|
50
|
+
'activeArtistPreset', 'artistPresets', 'fixedCharacters',
|
|
51
|
+
],
|
|
52
|
+
queue: ['queueEnabled', 'queueMaxRequests', 'batchMax'],
|
|
53
|
+
pricing: ['price', 'multiPrice', 'couponPrice', 'couponAskTimeout', 'adminUsers'],
|
|
54
|
+
access: ['adminOnly', 'allowedUserIds', 'blockedUserIds', 'allowedGroupIds', 'blockedGroupIds', 'outputLogs'],
|
|
55
|
+
workflow: [
|
|
56
|
+
'customWorkflowEnabled', 'customWorkflowPath', 'skipQualityPrefixForCustomWorkflow',
|
|
57
|
+
'customWorkflowOverrideParameters', 'customWorkflowReloadOnChange',
|
|
58
|
+
'positivePromptNodeId', 'negativePromptNodeId', 'resolutionNodeId', 'seedNodeId', 'stepsNodeId',
|
|
59
|
+
'workflowPresets', 'defaultWorkflowPreset',
|
|
60
|
+
],
|
|
61
|
+
llm: [
|
|
62
|
+
'promptOptimizeEnabled', 'llmBaseUrl', 'llmApiKey', 'llmProxy', 'llmModel', 'llmModels',
|
|
63
|
+
'llmChannels', 'llmChannelOrder', 'llmThinking', 'llmExtraBody', 'llmMaxTokens',
|
|
64
|
+
'promptOptimizeTemplate',
|
|
65
|
+
],
|
|
66
|
+
search: [
|
|
67
|
+
'webSearchEnabled', 'tavilyApiKey', 'tavilyProxy',
|
|
68
|
+
'webSearchMaxResults', 'webSearchDepth', 'webSearchQueryTemplate',
|
|
69
|
+
],
|
|
70
|
+
vision: [
|
|
71
|
+
'multiVerifyEnabled', 'multiVerifyPassScore', 'multiCandidateCount', 'multiSendDegradedCandidate',
|
|
72
|
+
'verifyLlmBaseUrl', 'verifyLlmApiKey', 'verifyLlmProxy', 'verifyLlmModel', 'verifyLlmModels',
|
|
73
|
+
'verifyLlmChannels', 'verifyLlmChannelOrder',
|
|
74
|
+
],
|
|
75
|
+
legacy: ['workflow'],
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 把嵌套配置摊平成扁平 cfg(就地写入,保持对象引用不变)。
|
|
79
|
+
// 优先级:顶层的旧扁平键 > 分组内的值。这样老 koishi.yml 直接可用,
|
|
80
|
+
// 而迁移到新结构后(顶层不再有同名键)就以分组值为准。
|
|
81
|
+
function normalizeConfig(raw) {
|
|
82
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
83
|
+
const known = Object.values(CONFIG_GROUPS).flat()
|
|
84
|
+
const legacy = known.filter(key => Object.prototype.hasOwnProperty.call(src, key))
|
|
85
|
+
|
|
86
|
+
for (const [group, keys] of Object.entries(CONFIG_GROUPS)) {
|
|
87
|
+
const node = src[group]
|
|
88
|
+
if (!node || typeof node !== 'object') continue
|
|
89
|
+
for (const key of keys) {
|
|
90
|
+
// 顶层扁平旧键优先,不被分组值覆盖
|
|
91
|
+
if (legacy.includes(key)) continue
|
|
92
|
+
if (key in node) src[key] = node[key]
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { config: src, legacy }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 控制台里每个分组是一个「可折叠小节」:嵌套 object 字段天生带折叠箭头,默认展开。
|
|
99
|
+
exports.Config = Schema.object({
|
|
100
|
+
connection: Schema.object({
|
|
41
101
|
comfyuiBaseUrl: Schema.string().default('http://127.0.0.1:8188').description('ComfyUI 地址'),
|
|
42
102
|
timeout: Schema.number().default(300).description('单次生成超时(秒)'),
|
|
43
103
|
pollInterval: Schema.number().default(2).description('生成状态查询间隔(秒)'),
|
|
44
104
|
}).description('① ComfyUI 连接'),
|
|
45
105
|
|
|
46
|
-
Schema.object({
|
|
106
|
+
model: Schema.object({
|
|
47
107
|
unetName: Schema.string().default('anima-aesthetic-v1.1.safetensors').description('主模型文件名,需与 ComfyUI models/diffusion_models 下的文件名完全一致;8G 显存可填 .gguf 版(插件自动改用 UnetLoaderGGUF)'),
|
|
48
108
|
useGgufUnet: Schema.union([
|
|
49
109
|
Schema.const('auto').description('按文件名自动判断(.gguf → UnetLoaderGGUF)'),
|
|
@@ -59,11 +119,19 @@ exports.Config = Schema.intersect([
|
|
|
59
119
|
cfg: Schema.number().default(4.0).description('CFG 强度(Aesthetic 1.1 推荐 4,用 3 也常更好)'),
|
|
60
120
|
samplerName: Schema.string().default('er_sde').description('采样器'),
|
|
61
121
|
scheduler: Schema.string().default('simple').description('调度器'),
|
|
122
|
+
modelParams: Schema.dict(Schema.object({
|
|
123
|
+
samplerName: Schema.string().description('采样器'),
|
|
124
|
+
scheduler: Schema.string().description('调度器'),
|
|
125
|
+
steps: Schema.number().description('采样步数'),
|
|
126
|
+
cfg: Schema.number().description('CFG 强度'),
|
|
127
|
+
width: Schema.number().description('默认宽度'),
|
|
128
|
+
height: Schema.number().description('默认高度'),
|
|
129
|
+
}).description('该模型的参数覆盖')).default({}).description('按模型覆盖参数:key=模型文件名,value 只填要覆盖的字段。显式写了的字段会覆盖工作流内取值'),
|
|
62
130
|
}).description('② 模型与采样参数'),
|
|
63
131
|
|
|
64
|
-
Schema.object({
|
|
132
|
+
prompt: Schema.object({
|
|
65
133
|
qualityPrefix: Schema.string().default('').description('质量词前缀(Aesthetic 1.1 建议留空;Base 模型可填 masterpiece, best quality, score_7)'),
|
|
66
|
-
negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词。推荐值就是当前默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts(Aesthetic 1.1 适用)。若用 Base 模型,可再加 score_4, score_5, score_6
|
|
134
|
+
negativePrompt: Schema.string().default('worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts').description('负面提示词。推荐值就是当前默认值:worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts(Aesthetic 1.1 适用)。若用 Base 模型,可再加 score_4, score_5, score_6'),
|
|
67
135
|
styleTags: Schema.string().default('').description('画风 tags'),
|
|
68
136
|
defaultArtistTags: Schema.string().default('').description('备用画师 tags'),
|
|
69
137
|
activeArtistPreset: Schema.string().default('').description('启用的画师组名称'),
|
|
@@ -71,13 +139,13 @@ exports.Config = Schema.intersect([
|
|
|
71
139
|
fixedCharacters: Schema.array(Schema.string()).default([]).description('固定角色(格式:角色名=tags;仅兼容旧配置,运行时以数据库为准)'),
|
|
72
140
|
}).description('③ 提示词与画师'),
|
|
73
141
|
|
|
74
|
-
Schema.object({
|
|
142
|
+
queue: Schema.object({
|
|
75
143
|
queueEnabled: Schema.boolean().default(true).description('启用生成队列(逐张顺序执行)'),
|
|
76
144
|
queueMaxRequests: Schema.number().default(5).description('队列最大任务数(0 表示不限制)'),
|
|
77
145
|
batchMax: Schema.number().default(4).description('单次指令最多生成的张数'),
|
|
78
146
|
}).description('④ 队列与批量'),
|
|
79
147
|
|
|
80
|
-
Schema.object({
|
|
148
|
+
pricing: Schema.object({
|
|
81
149
|
price: Schema.number().default(500).description('一张图消耗的 P 点'),
|
|
82
150
|
multiPrice: Schema.number().default(900).description('多人指令单张消耗的 P 点'),
|
|
83
151
|
couponPrice: Schema.number().default(3000).description('提示词优化券单价(可被 data/p-shop.json 覆盖)'),
|
|
@@ -85,7 +153,7 @@ exports.Config = Schema.intersect([
|
|
|
85
153
|
adminUsers: Schema.array(Schema.string()).default([]).description('免 P 点管理员用户 ID'),
|
|
86
154
|
}).description('⑤ P 点与优化券'),
|
|
87
155
|
|
|
88
|
-
Schema.object({
|
|
156
|
+
access: Schema.object({
|
|
89
157
|
adminOnly: Schema.boolean().default(false).description('仅管理员可用'),
|
|
90
158
|
allowedUserIds: Schema.array(Schema.string()).default([]).description('用户白名单(留空不限制)'),
|
|
91
159
|
blockedUserIds: Schema.array(Schema.string()).default([]).description('用户黑名单(优先于白名单)'),
|
|
@@ -94,8 +162,7 @@ exports.Config = Schema.intersect([
|
|
|
94
162
|
outputLogs: Schema.boolean().default(true).description('输出详细日志'),
|
|
95
163
|
}).description('⑥ 权限与日志'),
|
|
96
164
|
|
|
97
|
-
|
|
98
|
-
Schema.object({
|
|
165
|
+
workflow: Schema.object({
|
|
99
166
|
customWorkflowEnabled: Schema.boolean().default(false).description('使用自定义 ComfyUI 工作流 JSON'),
|
|
100
167
|
customWorkflowPath: Schema.string().default('').description('工作流 JSON 路径(相对 Koishi 运行目录,如 data/p-draw/workflows/anima-aesthetic-v1.1.json)'),
|
|
101
168
|
skipQualityPrefixForCustomWorkflow: Schema.boolean().default(true).description('启用自定义工作流时跳过质量前缀注入'),
|
|
@@ -103,27 +170,31 @@ exports.Config = Schema.intersect([
|
|
|
103
170
|
customWorkflowReloadOnChange: Schema.boolean().default(true).description('工作流文件变化时自动重载(无需重启)'),
|
|
104
171
|
positivePromptNodeId: Schema.string().default('').description('正面提示词节点 ID(留空自动识别;示例 6,以实际 JSON 为准)'),
|
|
105
172
|
negativePromptNodeId: Schema.string().default('').description('负面提示词节点 ID(留空自动识别;示例 7)'),
|
|
106
|
-
resolutionNodeId: Schema.string().default('').description('尺寸节点 ID
|
|
173
|
+
resolutionNodeId: Schema.string().default('').description('尺寸节点 ID(留空自动识别)'),
|
|
107
174
|
seedNodeId: Schema.string().default('').description('种子节点 ID(KSampler,可留空;示例 3)'),
|
|
108
175
|
stepsNodeId: Schema.string().default('').description('步数节点 ID(KSampler,可留空;示例 3)'),
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
176
|
+
workflowPresets: Schema.dict(Schema.object({
|
|
177
|
+
path: Schema.string().description('工作流 JSON 路径(相对 Koishi 运行目录)'),
|
|
178
|
+
aliases: Schema.array(Schema.string()).description('指令别名,例如 ["极速","fast"]'),
|
|
179
|
+
positivePromptNodeId: Schema.string().description('正面提示词节点 ID(留空自动识别)'),
|
|
180
|
+
negativePromptNodeId: Schema.string().description('负面提示词节点 ID(留空自动识别)'),
|
|
181
|
+
resolutionNodeId: Schema.string().description('尺寸节点 ID(留空自动识别)'),
|
|
182
|
+
seedNodeId: Schema.string().description('种子节点 ID(留空自动识别)'),
|
|
183
|
+
stepsNodeId: Schema.string().description('步数节点 ID(留空自动识别)'),
|
|
184
|
+
steps: Schema.number().description('该预设固定步数(如极速流 4)'),
|
|
185
|
+
cfg: Schema.number().description('该预设固定 CFG'),
|
|
186
|
+
samplerName: Schema.string().description('该预设固定采样器'),
|
|
187
|
+
scheduler: Schema.string().description('该预设固定调度器'),
|
|
188
|
+
overrideParameters: Schema.boolean().description('用上面的参数覆盖工作流内取值'),
|
|
189
|
+
}).description('预设')).default({}).description('工作流预设:key=预设名。指令里用 `--工作流 <名称>` 或名称/别名开头选择(如 `画图 极速:1girl`)'),
|
|
190
|
+
defaultWorkflowPreset: Schema.string().default('').description('默认预设名(留空则用上面的 customWorkflow* 那套)'),
|
|
191
|
+
}).description('⑦ 自定义工作流'),
|
|
192
|
+
|
|
193
|
+
llm: Schema.object({
|
|
123
194
|
promptOptimizeEnabled: Schema.boolean().default(false).description('启用自然语言优化(需配置下面的 LLM 接口)'),
|
|
124
195
|
llmBaseUrl: Schema.string().default('').description('LLM 接口地址(OpenAI 兼容,如 https://api.deepseek.com/v1)'),
|
|
125
196
|
llmApiKey: Schema.string().role('secret').default('').description('LLM API Key'),
|
|
126
|
-
llmProxy: Schema.string().default('').description('仅 LLM 使用代理(留空直连)。格式 http://127.0.0.1:7890 / socks5://127.0.0.1:7891,可省略 http
|
|
197
|
+
llmProxy: Schema.string().default('').description('仅 LLM 使用代理(留空直连)。格式 http://127.0.0.1:7890 / socks5://127.0.0.1:7891,可省略 http://;通道内单独填了 proxy 则优先用通道的'),
|
|
127
198
|
llmModel: Schema.string().default('').description('LLM 模型名(旧版单模型;请在 llmModels 里配置,这里留空即可)'),
|
|
128
199
|
llmModels: Schema.array(Schema.string()).default([]).description('主通道的模型名列表,按顺序逐个尝试(如 ["deepseek-chat","gpt-4o-mini"])'),
|
|
129
200
|
llmChannels: Schema.dict(Schema.object({
|
|
@@ -141,18 +212,18 @@ exports.Config = Schema.intersect([
|
|
|
141
212
|
llmExtraBody: Schema.string().role('textarea').default('{}').description('附加请求体 JSON(最后覆盖),用于中转站私有参数,如 {"enable_thinking":false}'),
|
|
142
213
|
llmMaxTokens: Schema.number().default(1000).description('LLM 输出上限'),
|
|
143
214
|
promptOptimizeTemplate: Schema.string().description('优化模板(支持 {theme} {search_block} {character_rule} 占位符)').default('你是为 Anima 图像生成模型编写正面提示词的 AI 画师。\n\n请根据用户的原始要求设计一幅完整、协调、具有视觉吸引力的画面,并将结果输出为英文 Danbooru-style tags。\n\n输出要求:\n- 只输出一行英文 tags,使用英文逗号分隔。\n- 不要输出解释、分析、标题、编号、Markdown、代码块或中文。\n- 不要输出 masterpiece、best quality、score 等质量前缀。\n- 不要输出画师 tags;质量词和画师组会由程序另行拼接。\n- 尽量使用模型容易理解的可见画面描述。\n- 保持用户明确指定的角色、主体、人数、关键服装、动作、表情和道具。\n- 除上述明确要求外,可以自由决定服装细节、姿态、构图、镜头、背景、环境、光影、色彩、氛围、前景和特效。\n- 以最终图像协调、精致、有表现力和好看为优先,不需要机械追求固定 Tag 数量。\n- 不要为了数量重复同义词;画面已经完整时即可停止。\n- 请自行解决明显冲突,直接输出你认为最适合生成最终画面的版本。\n\n角色和动态上下文:\n{character_rule}\n{search_block}\n\n用户原始要求:\n{theme}'),
|
|
144
|
-
}).description('
|
|
215
|
+
}).description('⑧ 提示词优化 / LLM'),
|
|
145
216
|
|
|
146
|
-
Schema.object({
|
|
217
|
+
search: Schema.object({
|
|
147
218
|
webSearchEnabled: Schema.boolean().default(false).description('启用联网搜索(指令里写「联网/搜索/查一下」触发)'),
|
|
148
219
|
tavilyApiKey: Schema.string().role('secret').default('').description('Tavily API Key(https://tavily.com)'),
|
|
149
|
-
tavilyProxy: Schema.string().default('').description('仅联网搜索(Tavily
|
|
220
|
+
tavilyProxy: Schema.string().default('').description('仅联网搜索(Tavily)使用代理(留空直连)。与 LLM / 视觉校验的代理互相独立'),
|
|
150
221
|
webSearchMaxResults: Schema.number().default(5).description('搜索结果数量'),
|
|
151
222
|
webSearchDepth: Schema.string().default('basic').description('搜索深度(basic / advanced)'),
|
|
152
223
|
webSearchQueryTemplate: Schema.string().default('{prompt} 角色 外观 立绘 服装 配色 武器 官方图 official art character design outfit appearance wiki fandom').description('搜索词模板({prompt} 代表用户需求)'),
|
|
153
|
-
}).description('
|
|
224
|
+
}).description('⑨ 联网搜索'),
|
|
154
225
|
|
|
155
|
-
Schema.object({
|
|
226
|
+
vision: Schema.object({
|
|
156
227
|
multiVerifyEnabled: Schema.boolean().default(true).description('多人图生成后启用视觉校验'),
|
|
157
228
|
multiVerifyPassScore: Schema.number().default(6).description('校验合格分数(0-10)'),
|
|
158
229
|
multiCandidateCount: Schema.number().default(2).description('候选采样数量(最多重试 候选数-1 次)'),
|
|
@@ -169,20 +240,18 @@ exports.Config = Schema.intersect([
|
|
|
169
240
|
proxy: Schema.string().description('该通道专用代理(留空则用上面的 verifyLlmProxy)'),
|
|
170
241
|
}).description('通道')).default({}).description('视觉校验的附加通道:主通道全部失败后按顺序继续尝试'),
|
|
171
242
|
verifyLlmChannelOrder: Schema.array(Schema.string()).default([]).description('视觉附加通道的尝试顺序(填通道名;留空则按配置先后顺序)'),
|
|
172
|
-
}).description('
|
|
243
|
+
}).description('⑩ 多人视觉校验'),
|
|
173
244
|
|
|
174
|
-
Schema.object({
|
|
245
|
+
legacy: Schema.object({
|
|
175
246
|
workflow: Schema.string().default('anima_t2i').description('旧版工作流标识,仅用于状态/诊断显示,内置工作流固定 anima_t2i'),
|
|
176
|
-
}).description('
|
|
177
|
-
]).i18n({
|
|
178
|
-
'zh-CN': zhCN,
|
|
247
|
+
}).description('⑪ 兼容项(旧版,可忽略)'),
|
|
179
248
|
})
|
|
180
249
|
|
|
181
250
|
// ------------------------------------------------------------------
|
|
182
251
|
// 纯函数库已拆分到 lib/(解析 / tag 清洗 / 工作流 / Comfy 等待 / 多人规划 / HTTP 客户端)
|
|
183
252
|
// ------------------------------------------------------------------
|
|
184
253
|
const {
|
|
185
|
-
normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed, parseStepsCfg,
|
|
254
|
+
normalizeBaseUrl, escapeRe, parseGenerationSize, parseBatchCount, parseSeed, parseStepsCfg, parseWorkflowPreset,
|
|
186
255
|
stripRawPrefix, splitPositiveNegativePrompt, parseNameTags, parsePresetList, mergeTagText,
|
|
187
256
|
} = require('./lib/parse')
|
|
188
257
|
const {
|
|
@@ -190,7 +259,7 @@ const {
|
|
|
190
259
|
NO_ARTIST_RE, NO_STYLE_RE,
|
|
191
260
|
} = require('./lib/tags')
|
|
192
261
|
const {
|
|
193
|
-
buildWorkflow, inspectCustomWorkflow, isGgufUnet,
|
|
262
|
+
buildWorkflow, inspectCustomWorkflow, isGgufUnet, inspectWorkflowFile,
|
|
194
263
|
} = require('./lib/workflows')
|
|
195
264
|
const { outputImages, waitComfyResult } = require('./lib/comfy')
|
|
196
265
|
const { materializeImageSource } = require('./lib/media')
|
|
@@ -201,20 +270,25 @@ const {
|
|
|
201
270
|
const { buildComfyClient } = require('./lib/http')
|
|
202
271
|
const { createOutboundFetch, normalizeProxyUrl, proxySupportAvailable } = require('./lib/net')
|
|
203
272
|
const { buildLlmChain, hasLlm, buildChatBody, runLlmChain } = require('./lib/llm')
|
|
204
|
-
exports.apply = async function apply(ctx,
|
|
205
|
-
//
|
|
206
|
-
|
|
273
|
+
exports.apply = async function apply(ctx, rawConfig) {
|
|
274
|
+
// 配置统一摊平成扁平 cfg:同时接受新的分组写法和老版本的扁平写法
|
|
275
|
+
const { config: cfg, legacy } = normalizeConfig(rawConfig)
|
|
207
276
|
|
|
208
277
|
const logger = ctx.logger('p-draw')
|
|
209
278
|
ctx.i18n.define('zh-CN', zhCN)
|
|
279
|
+
if (legacy.length) {
|
|
280
|
+
logger.warn(`[p-draw] koishi.yml 里仍有扁平旧配置键(${legacy.slice(0, 6).join('、')}${legacy.length > 6 ? ' 等' : ''}),本次已按它们生效;建议迁移到分组结构后删掉旧键,否则控制台里改同名项不会生效。`)
|
|
281
|
+
}
|
|
210
282
|
|
|
211
283
|
// 出站请求:代理按用途各自传入(联网搜索 / 文本 LLM / 视觉校验互不影响)
|
|
212
284
|
const outboundFetch = createOutboundFetch({
|
|
213
285
|
onWarn: (message) => logger.warn(message),
|
|
214
286
|
})
|
|
215
287
|
|
|
216
|
-
//
|
|
217
|
-
//
|
|
288
|
+
// 注意:不在此处 extend p_system 表 —— 该表由 p-qiandao 等 p 系插件创建。
|
|
289
|
+
// 重复声明同一张表可能导致 Koishi 的 schema 迁移冲突,拖垮签到插件。
|
|
290
|
+
|
|
291
|
+
// 运行时数据持久化到数据库,而不是调用 scope.update // 写 koishi.yml:scope.update 会触发插件重载,导致正在生成的图被 dispose(Context has
|
|
218
292
|
// been disposed),且重复写入时配置文件会被冲掉(曾出现配置整体恢复成默认)。
|
|
219
293
|
try {
|
|
220
294
|
ctx.model.extend('p_draw_config', {
|
|
@@ -283,6 +357,72 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
283
357
|
// 自定义工作流路径一律相对 Koishi 运行目录解析(见 lib/workflows.js)
|
|
284
358
|
const workflowOpts = () => ({ baseDir: ctx.baseDir || process.cwd() })
|
|
285
359
|
|
|
360
|
+
// ---------------- 工作流预设 ----------------
|
|
361
|
+
// 预设 = 一个 JSON 路径 + 可选的节点 ID / 采样参数覆盖,指令里按名字选用。
|
|
362
|
+
function presetList() {
|
|
363
|
+
const dict = cfg.workflowPresets
|
|
364
|
+
if (!dict || typeof dict !== 'object') return []
|
|
365
|
+
return Object.entries(dict)
|
|
366
|
+
.filter(([, value]) => value && typeof value === 'object')
|
|
367
|
+
.map(([name, value]) => ({ name, aliases: value.aliases || [], ...value }))
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function findPreset(name) {
|
|
371
|
+
if (!name) return null
|
|
372
|
+
return presetList().find(preset => preset.name === name) || null
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// 预设 → 生成用的配置补丁(工作流路径 + 节点 ID + 参数)
|
|
376
|
+
function presetCfgPatch(preset) {
|
|
377
|
+
if (!preset) return {}
|
|
378
|
+
const patch = {
|
|
379
|
+
customWorkflowEnabled: true,
|
|
380
|
+
customWorkflowPath: preset.path || '',
|
|
381
|
+
positivePromptNodeId: preset.positivePromptNodeId || '',
|
|
382
|
+
negativePromptNodeId: preset.negativePromptNodeId || '',
|
|
383
|
+
resolutionNodeId: preset.resolutionNodeId || '',
|
|
384
|
+
seedNodeId: preset.seedNodeId || '',
|
|
385
|
+
stepsNodeId: preset.stepsNodeId || '',
|
|
386
|
+
customWorkflowOverrideParameters: preset.overrideParameters != null
|
|
387
|
+
? Boolean(preset.overrideParameters)
|
|
388
|
+
: Boolean(cfg.customWorkflowOverrideParameters),
|
|
389
|
+
}
|
|
390
|
+
return patch
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// 预设里显式写死的参数,优先级高于 modelParams
|
|
394
|
+
function presetParams(preset) {
|
|
395
|
+
if (!preset) return {}
|
|
396
|
+
const out = {}
|
|
397
|
+
for (const key of ['steps', 'cfg', 'samplerName', 'scheduler', 'width', 'height']) {
|
|
398
|
+
if (preset[key] === undefined || preset[key] === null || preset[key] === '') continue
|
|
399
|
+
out[key] = key === 'samplerName' || key === 'scheduler' ? String(preset[key]).trim() : Number(preset[key])
|
|
400
|
+
}
|
|
401
|
+
return out
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// 体检:这个预设现在能不能真的跑(能否从纯文本启动)
|
|
405
|
+
function inspectPreset(preset) {
|
|
406
|
+
return inspectWorkflowFile(preset.path, {
|
|
407
|
+
positivePromptNodeId: preset.positivePromptNodeId || '',
|
|
408
|
+
negativePromptNodeId: preset.negativePromptNodeId || '',
|
|
409
|
+
resolutionNodeId: preset.resolutionNodeId || '',
|
|
410
|
+
seedNodeId: preset.seedNodeId || '',
|
|
411
|
+
stepsNodeId: preset.stepsNodeId || '',
|
|
412
|
+
customWorkflowReloadOnChange: cfg.customWorkflowReloadOnChange,
|
|
413
|
+
}, workflowOpts())
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// 指令里选了预设时先体检,不可用就给出人话原因
|
|
417
|
+
function checkPresetUsable(name) {
|
|
418
|
+
const preset = findPreset(name)
|
|
419
|
+
if (!preset) return { ok: false, message: `没有名为「${name}」的工作流预设。可用:${presetList().map(p => p.name).join('、') || '(未配置)'}` }
|
|
420
|
+
if (!String(preset.path || '').trim()) return { ok: false, message: `预设「${name}」没有填写 path。` }
|
|
421
|
+
const report = inspectPreset(preset)
|
|
422
|
+
if (!report.ok) return { ok: false, message: `预设「${name}」当前不可用:${report.error}` }
|
|
423
|
+
return { ok: true, preset }
|
|
424
|
+
}
|
|
425
|
+
|
|
286
426
|
// A4:自定义工作流(Aesthetic 1.1)默认跳过质量前缀注入
|
|
287
427
|
function shouldSkipQualityPrefix() {
|
|
288
428
|
return Boolean(cfg.customWorkflowEnabled && cfg.skipQualityPrefixForCustomWorkflow)
|
|
@@ -468,6 +608,44 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
468
608
|
return lines
|
|
469
609
|
}
|
|
470
610
|
|
|
611
|
+
// 预设总览:每个预设能不能跑、需要什么(不实际生图)
|
|
612
|
+
function presetOverviewText() {
|
|
613
|
+
const presets = presetList()
|
|
614
|
+
if (!presets.length) {
|
|
615
|
+
return '还没有配置工作流预设。\n在「⑦ 自定义工作流 → workflowPresets」里添加,key 用预设名,例如:\n workflowPresets:\n 极速4步:\n path: data/p-draw/workflows/03-dmdx.json\n aliases: [极速]'
|
|
616
|
+
}
|
|
617
|
+
const lines = ['工作流预设:']
|
|
618
|
+
for (const preset of presets) {
|
|
619
|
+
const report = inspectPreset(preset)
|
|
620
|
+
const aliases = (preset.aliases || []).length ? `(别名:${preset.aliases.join('、')})` : ''
|
|
621
|
+
lines.push(`${report.ok ? '✅' : '❌'} ${preset.name}${aliases}`)
|
|
622
|
+
if (report.ok) {
|
|
623
|
+
const analysis = report.analysis
|
|
624
|
+
const pos = report.targets.positive.map(id => `#${id}`).join('、')
|
|
625
|
+
const neg = report.targets.negative.map(id => `#${id}`).join('、')
|
|
626
|
+
lines.push(` 节点 ${analysis.nodeCount} 个 · 正面 ${pos} · 负面 ${neg} · 尺寸 ${report.targets.resolutionIds.map(id => `#${id}`).join('、') || '(无)'}`)
|
|
627
|
+
} else {
|
|
628
|
+
lines.push(` 不可用:${report.error}`)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const def = String(cfg.defaultWorkflowPreset || '').trim()
|
|
632
|
+
lines.push(`默认预设:${def ? `${def}${findPreset(def) ? '' : '(未找到此预设,已回落)'}` : '(未设置,使用内置/自定义工作流)'}`)
|
|
633
|
+
lines.push('用法:画图 --工作流 <名称>:描述 或 画图 <别名>:描述')
|
|
634
|
+
return lines.join('\n')
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// 诊断里附一段预设摘要
|
|
638
|
+
function presetDiagLines() {
|
|
639
|
+
const presets = presetList()
|
|
640
|
+
if (!presets.length) return []
|
|
641
|
+
const lines = [`工作流预设(${presets.length} 个):`]
|
|
642
|
+
for (const preset of presets) {
|
|
643
|
+
const report = inspectPreset(preset)
|
|
644
|
+
lines.push(` ${report.ok ? '✅' : '❌'} ${preset.name}${report.ok ? '' : ` — ${report.error}`}`)
|
|
645
|
+
}
|
|
646
|
+
return lines
|
|
647
|
+
}
|
|
648
|
+
|
|
471
649
|
async function diagnoseText(session) {
|
|
472
650
|
const payload = await statusPayload()
|
|
473
651
|
const lines = ['【p-draw 诊断】']
|
|
@@ -508,6 +686,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
508
686
|
// A7:自定义工作流 + 非空 qualityPrefix 的迁移提示
|
|
509
687
|
const warning = qualityPrefixWarning()
|
|
510
688
|
if (warning) lines.push(`⚠ ${warning}`)
|
|
689
|
+
lines.push(...presetDiagLines())
|
|
511
690
|
return lines.join('\n')
|
|
512
691
|
}
|
|
513
692
|
|
|
@@ -767,9 +946,15 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
767
946
|
async function runComfyGenerate(prompt, size, overrides) {
|
|
768
947
|
const sizes = parseAllowedSizes()
|
|
769
948
|
const unetName = overrides.unet || cfg.unetName
|
|
770
|
-
//
|
|
949
|
+
// 工作流预设:把路径 / 节点 ID 替换进配置,并取出预设写死的采样参数
|
|
950
|
+
const preset = overrides.preset || null
|
|
951
|
+
const presetExtra = presetParams(preset)
|
|
952
|
+
const baseCfg = preset ? Object.assign({}, cfg, presetCfgPatch(preset)) : cfg
|
|
953
|
+
// 应用该模型的独立参数覆盖(modelParams),再叠加预设参数与命令级 overrides
|
|
771
954
|
const modelSpecific = resolveModelParams(unetName)
|
|
772
|
-
const workCfg = Object.assign({},
|
|
955
|
+
const workCfg = Object.assign({}, baseCfg, modelSpecific, presetExtra, { unetName })
|
|
956
|
+
// 预设/modelParams 里显式配置的字段要覆盖自定义工作流内的取值
|
|
957
|
+
const overrideKeys = Object.assign({}, modelSpecific, presetExtra)
|
|
773
958
|
const requestedWidth = (size && size[0]) || overrides.width || workCfg.width
|
|
774
959
|
const requestedHeight = (size && size[1]) || overrides.height || workCfg.height
|
|
775
960
|
// 防御:sampler/scheduler 配置若带尾随空格会导致 ComfyUI 报 "Value not in list",统一 trim
|
|
@@ -781,7 +966,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
781
966
|
const cfgVal = Number(overrides.cfg) || workCfg.cfg
|
|
782
967
|
const seed = Number(overrides.seed) || crypto.randomInt(1, 2 ** 32 - 1)
|
|
783
968
|
const negativePrompt = joinPromptParts([overrides.negativePrompt || cfg.negativePrompt || ''])
|
|
784
|
-
const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), Object.assign({}, workflowOpts(), { modelParams:
|
|
969
|
+
const promptBody = buildWorkflow(workCfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, Boolean(size), Object.assign({}, workflowOpts(), { modelParams: overrideKeys }))
|
|
785
970
|
|
|
786
971
|
const clientId = crypto.randomUUID()
|
|
787
972
|
const submit = await comfyPost('/prompt', { prompt: promptBody, client_id: clientId }, 20000)
|
|
@@ -1331,7 +1516,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1331
1516
|
|
|
1332
1517
|
// 视觉校验(anima_verify + generation_verifier 移植):对生成的图片跑视觉 LLM,
|
|
1333
1518
|
// 不合格则用相同提示词重试(最多 multiCandidateCount 张),按多候选规则挑选并返回结果。
|
|
1334
|
-
async function verifyGeneratedImages(session, images, userRequest, prompt, size, planCount, unet, negativePrompt) {
|
|
1519
|
+
async function verifyGeneratedImages(session, images, userRequest, prompt, size, planCount, unet, negativePrompt, preset = null) {
|
|
1335
1520
|
if (!hasLlm(cfg, 'vision')) {
|
|
1336
1521
|
return { ok: true, degraded: true, message: '', verdict: null, outputs: images, prompt, negativePrompt }
|
|
1337
1522
|
}
|
|
@@ -1443,7 +1628,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1443
1628
|
if (hint) {
|
|
1444
1629
|
currentPrompt = `${userRequest}\n【上次问题,请修正】${hint}`
|
|
1445
1630
|
}
|
|
1446
|
-
const regen = await runComfyGenerate(currentPrompt, size, { unet, negativePrompt: currentNegativePrompt })
|
|
1631
|
+
const regen = await runComfyGenerate(currentPrompt, size, Object.assign({ unet, negativePrompt: currentNegativePrompt }, preset ? { preset } : {}))
|
|
1447
1632
|
if (!regen.ok) {
|
|
1448
1633
|
logger.warn(`多人校验重试生成失败:${regen.message}`)
|
|
1449
1634
|
break
|
|
@@ -1524,11 +1709,24 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1524
1709
|
const parsedBatch = parseBatchCount(parsedSize.prompt, cfg.batchMax)
|
|
1525
1710
|
// 采样参数覆盖(--steps 40 / --cfg 3.5),并从描述中剥离,避免进入 LLM 规划
|
|
1526
1711
|
const parsedTuning = parseStepsCfg(parsedBatch.prompt)
|
|
1527
|
-
|
|
1712
|
+
// 工作流预设(多人生图同样支持)
|
|
1713
|
+
const parsedPreset = parseWorkflowPreset(parsedTuning.prompt, presetList())
|
|
1714
|
+
if (parsedPreset.error) return parsedPreset.error
|
|
1715
|
+
let activePreset = null
|
|
1716
|
+
if (parsedPreset.preset) {
|
|
1717
|
+
const usable = checkPresetUsable(parsedPreset.preset)
|
|
1718
|
+
if (!usable.ok) return usable.message
|
|
1719
|
+
activePreset = usable.preset
|
|
1720
|
+
} else if (String(cfg.defaultWorkflowPreset || '').trim()) {
|
|
1721
|
+
const usable = checkPresetUsable(String(cfg.defaultWorkflowPreset).trim())
|
|
1722
|
+
if (usable.ok) activePreset = usable.preset
|
|
1723
|
+
else if (cfg.outputLogs) logger.warn(`[p-draw] 默认预设不可用,已回落:${usable.message}`)
|
|
1724
|
+
}
|
|
1725
|
+
const text = parsedPreset.prompt
|
|
1528
1726
|
if (!text) return session.text('.multi-usage')
|
|
1529
1727
|
const count = parsedBatch.count
|
|
1530
1728
|
const tuningOverrides = Object.assign(
|
|
1531
|
-
{},
|
|
1729
|
+
activePreset ? { preset: activePreset } : {},
|
|
1532
1730
|
parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
|
|
1533
1731
|
parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
|
|
1534
1732
|
)
|
|
@@ -1600,7 +1798,7 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1600
1798
|
if (!cfg.multiVerifyEnabled) {
|
|
1601
1799
|
return { ok: true, outputs: result.outputs, seed: result.seed, prompt: finalPrompt, negativePrompt: result.negativePrompt, note: session.text('.multi-degraded', ['(未启用校验或未配置视觉模型)']) }
|
|
1602
1800
|
}
|
|
1603
|
-
const verified = await verifyGeneratedImages(session, result.outputs, text, finalPrompt, size, plan.characters.length, unet, result.negativePrompt || multiNegative)
|
|
1801
|
+
const verified = await verifyGeneratedImages(session, result.outputs, text, finalPrompt, size, plan.characters.length, unet, result.negativePrompt || multiNegative, activePreset)
|
|
1604
1802
|
if (!verified.ok) return { ok: false, message: verified.message }
|
|
1605
1803
|
return { ok: true, outputs: verified.outputs, seed: result.seed, prompt: verified.prompt || finalPrompt, negativePrompt: verified.negativePrompt || result.negativePrompt || multiNegative, note: verified.message || '' }
|
|
1606
1804
|
}
|
|
@@ -1824,6 +2022,9 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1824
2022
|
if (lower === '诊断' || lower === 'diagnose' || lower === '部署诊断' || lower === 'debug' || lower === '调试' || lower === '调试状态') {
|
|
1825
2023
|
return await diagnoseText(session)
|
|
1826
2024
|
}
|
|
2025
|
+
if (lower === '工作流' || lower === '预设' || lower === 'workflow' || lower === 'workflows') {
|
|
2026
|
+
return presetOverviewText()
|
|
2027
|
+
}
|
|
1827
2028
|
|
|
1828
2029
|
// 多人指令:p-draw 多人 <描述>
|
|
1829
2030
|
const multiMatch = text.match(/^(?:多人|多人生图|双人|三人|群像)\s*(.*)$/)
|
|
@@ -1984,12 +2185,26 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
1984
2185
|
const parsedSeed = parseSeed(parsedBatch.prompt)
|
|
1985
2186
|
// 采样参数覆盖(--steps 40 / --cfg 3.5),并从提示词中剥离
|
|
1986
2187
|
const parsedTuning = parseStepsCfg(parsedSeed.prompt)
|
|
1987
|
-
|
|
2188
|
+
// 工作流预设:--工作流 xxx 或开头裸写名称/别名
|
|
2189
|
+
const parsedPreset = parseWorkflowPreset(parsedTuning.prompt, presetList())
|
|
2190
|
+
if (parsedPreset.error) return parsedPreset.error
|
|
2191
|
+
let activePreset = null
|
|
2192
|
+
if (parsedPreset.preset) {
|
|
2193
|
+
const usable = checkPresetUsable(parsedPreset.preset)
|
|
2194
|
+
if (!usable.ok) return usable.message
|
|
2195
|
+
activePreset = usable.preset
|
|
2196
|
+
} else if (String(cfg.defaultWorkflowPreset || '').trim()) {
|
|
2197
|
+
// 默认预设不可用时不阻断生成,回落到 customWorkflow* / 内置工作流
|
|
2198
|
+
const usable = checkPresetUsable(String(cfg.defaultWorkflowPreset).trim())
|
|
2199
|
+
if (usable.ok) activePreset = usable.preset
|
|
2200
|
+
else if (cfg.outputLogs) logger.warn(`[p-draw] 默认预设不可用,已回落:${usable.message}`)
|
|
2201
|
+
}
|
|
2202
|
+
const text = parsedPreset.prompt
|
|
1988
2203
|
const seed = parsedSeed.seed
|
|
1989
2204
|
const count = parsedBatch.count
|
|
1990
|
-
//
|
|
2205
|
+
// 命令级参数优先于预设 / modelParams / 全局配置(见 runComfyGenerate)
|
|
1991
2206
|
const tuningOverrides = Object.assign(
|
|
1992
|
-
{},
|
|
2207
|
+
activePreset ? { preset: activePreset } : {},
|
|
1993
2208
|
parsedTuning.steps != null ? { steps: parsedTuning.steps } : {},
|
|
1994
2209
|
parsedTuning.cfg != null ? { cfg: parsedTuning.cfg } : {},
|
|
1995
2210
|
)
|
|
@@ -2336,5 +2551,5 @@ exports.apply = async function apply(ctx, cfg) {
|
|
|
2336
2551
|
})
|
|
2337
2552
|
|
|
2338
2553
|
// 暴露内部接口供自动化测试调用(Koishi 忽略 apply 返回值,不影响生产行为)
|
|
2339
|
-
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir }
|
|
2554
|
+
return { couponConfirmFlow, buyCouponsAndConsume, normalizeConfirm, resolveCouponPrice, buildChargeNotice, buildGenerationReply, shouldOptimizePerImage, sendNotices, sendImagesAsForward, executeBatch, composePrompt, shouldSkipQualityPrefix, qualityPrefixWarning, customWorkflowDiagLines, diagnoseText, workflowDir, normalizeConfig, presetList, presetOverviewText }
|
|
2340
2555
|
}
|
package/lib/i18n.js
CHANGED
|
@@ -15,6 +15,8 @@ const zhCN = {
|
|
|
15
15
|
resolutionNodeId: { $description: '自定义工作流中尺寸节点 ID(EmptyLatentImage,可留空;示例 5)' },
|
|
16
16
|
seedNodeId: { $description: '自定义工作流中种子节点 ID(KSampler,可留空;示例 3)' },
|
|
17
17
|
stepsNodeId: { $description: '自定义工作流中步数节点 ID(KSampler,可留空;示例 3)' },
|
|
18
|
+
workflowPresets: { $description: '工作流预设:key=预设名。指令里用 --工作流 <名称> 或名称/别名开头选择' },
|
|
19
|
+
defaultWorkflowPreset: { $description: '默认预设名(留空则用 customWorkflow* 那套)' },
|
|
18
20
|
timeout: { $description: '单次生成超时(秒)' },
|
|
19
21
|
pollInterval: { $description: '生成状态查询间隔(秒)' },
|
|
20
22
|
unetName: { $description: '主模型文件名(8G 显存推荐 GGUF Q8_0 版,插件会自动改用 UnetLoaderGGUF 加载)' },
|
package/lib/parse.js
CHANGED
|
@@ -191,6 +191,54 @@ function parseStepsCfg(text) {
|
|
|
191
191
|
return { steps, cfg, prompt }
|
|
192
192
|
}
|
|
193
193
|
|
|
194
|
+
// 工作流预设选择:--工作流 名称 / --workflow 名称,或开头裸写名称/别名(如「极速:描述」)
|
|
195
|
+
// presets: [{ name, aliases: [] }]
|
|
196
|
+
function matchPreset(wanted, presets) {
|
|
197
|
+
const key = String(wanted || '').trim().toLowerCase()
|
|
198
|
+
if (!key) return null
|
|
199
|
+
for (const preset of presets) {
|
|
200
|
+
if (String(preset.name || '').toLowerCase() === key) return preset.name
|
|
201
|
+
if ((preset.aliases || []).some(alias => String(alias || '').toLowerCase() === key)) return preset.name
|
|
202
|
+
}
|
|
203
|
+
return null
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function parseWorkflowPreset(text, presets = []) {
|
|
207
|
+
const original = String(text || '').trim()
|
|
208
|
+
const list = Array.isArray(presets) ? presets : []
|
|
209
|
+
if (!list.length) return { preset: null, prompt: original, error: null }
|
|
210
|
+
|
|
211
|
+
// 1) 显式开关:--工作流 xxx
|
|
212
|
+
const flag = original.match(/(?<!\S)--(?:工作流|预设|workflow|preset)\s*(?:=|=|:|:)?\s*([^\s,,::]+)/i)
|
|
213
|
+
if (flag) {
|
|
214
|
+
const hit = matchPreset(flag[1], list)
|
|
215
|
+
if (!hit) {
|
|
216
|
+
return {
|
|
217
|
+
preset: null,
|
|
218
|
+
prompt: original,
|
|
219
|
+
error: `没有名为「${flag[1]}」的工作流预设。可用:${list.map(p => p.name).join('、')}`,
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return { preset: hit, prompt: stripMatchedToken(original, flag), error: null }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// 2) 开头裸写名称或别名(长的优先,避免「高清」抢了「高清重绘」)
|
|
226
|
+
const candidates = []
|
|
227
|
+
for (const preset of list) {
|
|
228
|
+
if (preset.name) candidates.push([String(preset.name), preset.name])
|
|
229
|
+
for (const alias of preset.aliases || []) if (alias) candidates.push([String(alias), preset.name])
|
|
230
|
+
}
|
|
231
|
+
candidates.sort((a, b) => b[0].length - a[0].length)
|
|
232
|
+
for (const [token, name] of candidates) {
|
|
233
|
+
const pattern = new RegExp(`^\\s*${escapeRe(token)}\\s*(?:[::,,]|\\s|$)`, 'i')
|
|
234
|
+
const matched = original.match(pattern)
|
|
235
|
+
if (matched) {
|
|
236
|
+
return { preset: name, prompt: original.slice(matched[0].length).trim(), error: null }
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return { preset: null, prompt: original, error: null }
|
|
240
|
+
}
|
|
241
|
+
|
|
194
242
|
// ------------------------------------------------------------------
|
|
195
243
|
// 提示词辅助(移植自 anima prompt_presets)
|
|
196
244
|
// ------------------------------------------------------------------
|
|
@@ -302,6 +350,8 @@ module.exports = {
|
|
|
302
350
|
CFG_PATTERN,
|
|
303
351
|
stripMatchedToken,
|
|
304
352
|
parseStepsCfg,
|
|
353
|
+
matchPreset,
|
|
354
|
+
parseWorkflowPreset,
|
|
305
355
|
RAW_PREFIXES,
|
|
306
356
|
stripRawPrefix,
|
|
307
357
|
splitPositiveNegativePrompt,
|
package/lib/workflows.js
CHANGED
|
@@ -182,6 +182,22 @@ function findNodesByClass(workflow, classTypes) {
|
|
|
182
182
|
return ids
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
// 尺寸节点:凡是「类名带 Latent 且同时有 width/height 输入」的都算。
|
|
186
|
+
// 这样 EmptyLatentImage、EmptySD3LatentImage、EmptyHunyuanLatentVideo 等新老节点都能认。
|
|
187
|
+
function findResolutionNodeIds(workflow) {
|
|
188
|
+
const ids = []
|
|
189
|
+
for (const [nodeId, node] of Object.entries(workflow)) {
|
|
190
|
+
if (!node || typeof node !== 'object') continue
|
|
191
|
+
const classType = String(node.class_type || '')
|
|
192
|
+
const inputs = node.inputs
|
|
193
|
+
if (!inputs || typeof inputs !== 'object') continue
|
|
194
|
+
if (!/latent/i.test(classType)) continue
|
|
195
|
+
if (!('width' in inputs) || !('height' in inputs)) continue
|
|
196
|
+
ids.push(String(nodeId))
|
|
197
|
+
}
|
|
198
|
+
return ids
|
|
199
|
+
}
|
|
200
|
+
|
|
185
201
|
// 从 KSampler 的 positive/negative 入口沿连线反查,找到真正的文本编码节点
|
|
186
202
|
function conditioningTextNodeIds(workflow, inputName, textNodes) {
|
|
187
203
|
const pending = []
|
|
@@ -254,12 +270,12 @@ function resolveCustomNodeTargets(workflow, cfg = {}) {
|
|
|
254
270
|
let resolutionIds = []
|
|
255
271
|
if (explicitResolution) {
|
|
256
272
|
if (!workflow[explicitResolution]) {
|
|
257
|
-
errors.push(`配置的尺寸节点 ID「${explicitResolution}」不存在于工作流中。可能是:\n ${
|
|
273
|
+
errors.push(`配置的尺寸节点 ID「${explicitResolution}」不存在于工作流中。可能是:\n ${findResolutionNodeIds(workflow).map(id => nodeLabel(workflow, id)).join('\n ') || '(无)'}`)
|
|
258
274
|
} else {
|
|
259
275
|
resolutionIds = [explicitResolution]
|
|
260
276
|
}
|
|
261
277
|
} else {
|
|
262
|
-
resolutionIds =
|
|
278
|
+
resolutionIds = findResolutionNodeIds(workflow)
|
|
263
279
|
}
|
|
264
280
|
|
|
265
281
|
// 采样节点:显式指定则只改该节点,否则改所有 KSampler
|
|
@@ -379,6 +395,70 @@ function inspectCustomWorkflow(cfg, opts = {}) {
|
|
|
379
395
|
}
|
|
380
396
|
}
|
|
381
397
|
|
|
398
|
+
// 只有图像输入类节点才需要用户「喂图」;这些工作流在纯文生图模式下无法使用
|
|
399
|
+
const IMAGE_INPUT_RE = /^(LoadImage|LoadImageMask|LoadImageOutput|ImageInput|LoadImageFromUrl)$/i
|
|
400
|
+
const CONTROLNET_RE = /controlnet/i
|
|
401
|
+
|
|
402
|
+
// 体检:这个工作流能不能在「纯文本」模式下跑,需要什么额外输入
|
|
403
|
+
function analyzeWorkflow(workflow) {
|
|
404
|
+
const classes = Object.values(workflow).map(node => String((node && node.class_type) || ''))
|
|
405
|
+
const unique = (list) => [...new Set(list)]
|
|
406
|
+
const imageInputClasses = unique(classes.filter(type => IMAGE_INPUT_RE.test(type)))
|
|
407
|
+
const controlNetClasses = unique(classes.filter(type => CONTROLNET_RE.test(type)))
|
|
408
|
+
const resolutionIds = findResolutionNodeIds(workflow)
|
|
409
|
+
const textNodes = collectTextNodeIds(workflow)
|
|
410
|
+
|
|
411
|
+
const requires = []
|
|
412
|
+
if (imageInputClasses.length) requires.push(`图片输入(${imageInputClasses.join(' / ')})`)
|
|
413
|
+
if (controlNetClasses.length && !imageInputClasses.length) {
|
|
414
|
+
requires.push(`ControlNet 控制图(${controlNetClasses.join(' / ')})`)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return {
|
|
418
|
+
nodeCount: classes.length,
|
|
419
|
+
textNodes,
|
|
420
|
+
resolutionIds,
|
|
421
|
+
imageInputClasses,
|
|
422
|
+
controlNetClasses,
|
|
423
|
+
hasLatentStart: resolutionIds.length > 0,
|
|
424
|
+
requires,
|
|
425
|
+
// 纯文本可跑:有文生图起点,且没有任何需要外部图片的节点
|
|
426
|
+
canRunTextOnly: resolutionIds.length > 0 && imageInputClasses.length === 0,
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// 体检任意一个工作流文件(预设用)。返回结构不抛错,便于诊断里逐条展示。
|
|
431
|
+
function inspectWorkflowFile(workflowPath, cfg = {}, opts = {}) {
|
|
432
|
+
const report = {
|
|
433
|
+
ok: false, path: '', mtimeMs: null, analysis: null, targets: null, error: '',
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const absPath = resolveCustomWorkflowPath({ customWorkflowPath: workflowPath }, opts)
|
|
437
|
+
report.path = absPath
|
|
438
|
+
try { report.mtimeMs = fs.statSync(absPath).mtimeMs } catch (e) { /* ignore */ }
|
|
439
|
+
const body = readCustomWorkflowBody(absPath, cfg.customWorkflowReloadOnChange !== false)
|
|
440
|
+
const workflow = JSON.parse(JSON.stringify(body))
|
|
441
|
+
report.analysis = analyzeWorkflow(workflow)
|
|
442
|
+
const targets = resolveCustomNodeTargets(workflow, cfg)
|
|
443
|
+
report.targets = targets
|
|
444
|
+
if (targets.errors.length) {
|
|
445
|
+
report.error = targets.errors.join(';')
|
|
446
|
+
return report
|
|
447
|
+
}
|
|
448
|
+
if (!report.analysis.canRunTextOnly) {
|
|
449
|
+
report.error = report.analysis.requires.length
|
|
450
|
+
? `需要${report.analysis.requires.join('、')},当前版本不支持图生图`
|
|
451
|
+
: '工作流里找不到可写入尺寸的 latent 节点(缺少文生图起点)'
|
|
452
|
+
return report
|
|
453
|
+
}
|
|
454
|
+
report.ok = true
|
|
455
|
+
return report
|
|
456
|
+
} catch (e) {
|
|
457
|
+
report.error = String((e && e.message) || e)
|
|
458
|
+
return report
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
382
462
|
function buildWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, explicitSize, opts = {}) {
|
|
383
463
|
if (cfg.customWorkflowEnabled && cfg.customWorkflowPath) {
|
|
384
464
|
return customWorkflow(cfg, prompt, negativePrompt, width, height, steps, cfgVal, seed, explicitSize, opts)
|
|
@@ -402,9 +482,14 @@ module.exports = {
|
|
|
402
482
|
nodeLabel,
|
|
403
483
|
collectTextNodeIds,
|
|
404
484
|
findNodesByClass,
|
|
485
|
+
findResolutionNodeIds,
|
|
405
486
|
buildWorkflow,
|
|
406
487
|
customWorkflow,
|
|
407
488
|
conditioningTextNodeIds,
|
|
408
489
|
resolveCustomNodeTargets,
|
|
409
490
|
inspectCustomWorkflow,
|
|
491
|
+
IMAGE_INPUT_RE,
|
|
492
|
+
CONTROLNET_RE,
|
|
493
|
+
analyzeWorkflow,
|
|
494
|
+
inspectWorkflowFile,
|
|
410
495
|
}
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -66,7 +66,7 @@ plugins:
|
|
|
66
66
|
|
|
67
67
|
## 配置说明
|
|
68
68
|
|
|
69
|
-
控制台里配置分成 **
|
|
69
|
+
控制台里配置分成 **11 个可折叠分组**,点标题即可折叠/展开,默认展开。分组是嵌套结构,`koishi.yml` 里写成 `组名: { 字段名: 值 }`,详见文末的分组对照与示例。
|
|
70
70
|
|
|
71
71
|
### ① ComfyUI 连接
|
|
72
72
|
|
|
@@ -127,6 +127,8 @@ plugins:
|
|
|
127
127
|
| `customWorkflowReloadOnChange` | 工作流文件变化时自动重载,无需重启(默认 `true`) |
|
|
128
128
|
| `positivePromptNodeId` / `negativePromptNodeId` | 正/负面提示词节点 ID;留空自动识别 |
|
|
129
129
|
| `resolutionNodeId` / `seedNodeId` / `stepsNodeId` | 尺寸 / 种子 / 步数节点 ID;可留空(留空则按节点类型覆盖) |
|
|
130
|
+
| `workflowPresets` | 工作流预设字典:`预设名 → { path, aliases, 节点 ID, steps, cfg, ... }`,供指令按名切换(见下方「工作流预设」) |
|
|
131
|
+
| `defaultWorkflowPreset` | 默认预设名;留空则使用 `customWorkflow*` 那套或内置工作流 |
|
|
130
132
|
|
|
131
133
|
### ⑧ 模型独立参数覆盖(折叠)
|
|
132
134
|
|
|
@@ -173,22 +175,52 @@ plugins:
|
|
|
173
175
|
|----|------|
|
|
174
176
|
| `workflow` | 旧版工作流标识,仅用于状态/诊断显示,内置工作流固定 `anima_t2i` |
|
|
175
177
|
|
|
176
|
-
|
|
178
|
+
控制台里配置分成 **11 个可折叠分组**(每个分组都能折叠/展开,默认展开)。分组是**嵌套结构**:`koishi.yml` 里对应写成 `组名: { 字段名: 值 }`。
|
|
179
|
+
|
|
180
|
+
已有的**扁平旧配置仍然生效**(插件会就地摊平并打一条日志提醒),但建议迁移成下面的分组写法——否则你在控制台里改同名项不会生效,因为旧扁平键优先级更高。
|
|
181
|
+
|
|
182
|
+
| 分组 | 内容 |
|
|
183
|
+
|---|---|
|
|
184
|
+
| `connection` | ComfyUI 地址、超时、轮询间隔 |
|
|
185
|
+
| `model` | 模型文件、采样参数、尺寸、`modelParams` |
|
|
186
|
+
| `prompt` | 质量前缀、负面词、画师组、固定角色 |
|
|
187
|
+
| `queue` | 队列与批量张数 |
|
|
188
|
+
| `pricing` | P 点价格、优化券、管理员 |
|
|
189
|
+
| `access` | 白名单/黑名单、日志 |
|
|
190
|
+
| `workflow` | 自定义工作流、节点 ID、工作流预设 |
|
|
191
|
+
| `llm` | 提示词优化、多通道/多模型、LLM 代理 |
|
|
192
|
+
| `search` | 联网搜索(Tavily)与其代理 |
|
|
193
|
+
| `vision` | 多人视觉校验及其通道/代理 |
|
|
194
|
+
| `legacy` | 旧版 `workflow` 标识,可忽略 |
|
|
177
195
|
|
|
178
196
|
```yaml
|
|
179
197
|
p-draw:0z81el:
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
198
|
+
connection:
|
|
199
|
+
comfyuiBaseUrl: http://127.0.0.1:8188
|
|
200
|
+
model:
|
|
201
|
+
unetName: anima-aesthetic-v1.1.safetensors
|
|
202
|
+
cfg: 4.0
|
|
203
|
+
steps: 30
|
|
204
|
+
prompt:
|
|
205
|
+
qualityPrefix: ''
|
|
206
|
+
workflow:
|
|
207
|
+
customWorkflowEnabled: true
|
|
208
|
+
customWorkflowPath: data/p-draw/workflows/anima-aesthetic-v1.1.json
|
|
209
|
+
workflowPresets:
|
|
210
|
+
极速4步:
|
|
211
|
+
path: data/p-draw/workflows/03-dmdx.json
|
|
212
|
+
aliases: [极速]
|
|
213
|
+
steps: 4
|
|
214
|
+
cfg: 1.0
|
|
215
|
+
llm:
|
|
216
|
+
llmBaseUrl: https://api.deepseek.com
|
|
217
|
+
llmModels: [deepseek-chat]
|
|
188
218
|
```
|
|
189
219
|
|
|
190
220
|
## 中转站、多模型与代理
|
|
191
221
|
|
|
222
|
+
> 下面片段为便于阅读只按**字段名**展示,实际请写在对应分组下:`llm*` → `llm:`,`tavilyProxy` / `webSearch*` → `search:`,`verifyLlm*` → `vision:`。
|
|
223
|
+
|
|
192
224
|
### 多模型逐个回退
|
|
193
225
|
|
|
194
226
|
同一个 `baseUrl` + `apiKey` 下可以填**多个模型名**,按顺序逐个尝试;前一个失败(网络错误 / 非 2xx / 返回空文本)自动换下一个:
|
|
@@ -350,6 +382,68 @@ p-draw:
|
|
|
350
382
|
- [ ] 替换工作流 JSON 后,在 `customWorkflowReloadOnChange: true` 下无需重启插件即生效。
|
|
351
383
|
- [ ] `p-draw 诊断` 能显示实际工作流路径、更新时间与实际解析到的节点 ID。
|
|
352
384
|
|
|
385
|
+
## 工作流预设
|
|
386
|
+
|
|
387
|
+
> 下面片段按字段名展示,实际写在 `workflow:` 分组下(见「配置说明」的分组示例)。
|
|
388
|
+
|
|
389
|
+
Anima Aesthetic 1.1 官方/社区共 10 个工作流。插件**不内置任何 JSON**,你导出后登记成预设,指令里按名字切换。
|
|
390
|
+
|
|
391
|
+
### 登记预设
|
|
392
|
+
|
|
393
|
+
```yaml
|
|
394
|
+
workflowPresets:
|
|
395
|
+
基础文生图: # 预设名 = 指令里用的名字
|
|
396
|
+
path: data/p-draw/workflows/09-baseline.json
|
|
397
|
+
aliases: [基础, base] # 指令别名(可选)
|
|
398
|
+
positivePromptNodeId: '6' # 节点 ID 可留空,插件会自动识别
|
|
399
|
+
negativePromptNodeId: '7'
|
|
400
|
+
极速4步:
|
|
401
|
+
path: data/p-draw/workflows/03-dmdx.json
|
|
402
|
+
aliases: [极速, fast]
|
|
403
|
+
steps: 4 # 该预设固定步数,覆盖全局与 modelParams
|
|
404
|
+
cfg: 1.0
|
|
405
|
+
overrideParameters: true
|
|
406
|
+
defaultWorkflowPreset: 基础文生图
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
### 指令用法
|
|
410
|
+
|
|
411
|
+
```
|
|
412
|
+
画图 --工作流 极速4步:1girl, solo
|
|
413
|
+
画图 极速:1girl, solo # 用别名开头,等效
|
|
414
|
+
画图 工作流 # 列出所有预设及其可用性
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
`画图 工作流` 会逐个体检并给出结论,例如:
|
|
418
|
+
|
|
419
|
+
```
|
|
420
|
+
✅ 基础文生图(别名:基础、base)
|
|
421
|
+
节点 9 个 · 正面 #6 · 负面 #7 · 尺寸 #5
|
|
422
|
+
❌ 图生图(别名:i2i)
|
|
423
|
+
不可用:需要图片输入(LoadImage),当前版本不支持图生图
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
选了不可用的预设会**直接拒绝并说明原因**,不会静默失败或跑错工作流。
|
|
427
|
+
|
|
428
|
+
### 10 个工作流的可用性对照
|
|
429
|
+
|
|
430
|
+
| # | 工作流 | 节点 | 起点 | 当前版本 |
|
|
431
|
+
|---|---|---|---|---|
|
|
432
|
+
| 09 | Text-to-Image Baseline | 17 | 文本 | ✅ 可用 |
|
|
433
|
+
| 03 | DMDX 4-Step Speed Run | 19 | 文本 | ✅ 可用(设 `steps: 4`、低 CFG) |
|
|
434
|
+
| 04 | Three-Stage High-Quality | 26 | 文本 | ✅ 可用(多段采样+放大) |
|
|
435
|
+
| 01 | 1.5x Upscale | 20 | 视导出而定 | ⚠️ 若含 `LoadImage` 则不可用 |
|
|
436
|
+
| 05 | Tiled Upscale | 45 | 视导出而定 | ⚠️ 同上 |
|
|
437
|
+
| 08 | T2I + ControlNet + Face/Hand Repair | 60 | 文本 + 控制图 | ⚠️ ControlNet 分支需参考图,禁用后方可用 |
|
|
438
|
+
| 02 | ControlNet Precision Control | 32 | 图片 | ❌ 需图生图 |
|
|
439
|
+
| 06 | i2i + ControlNet + Face/Hand Repair | 52 | 图片 | ❌ 需图生图 |
|
|
440
|
+
| 07 | Image-to-Image | 19 | 图片 | ❌ 需图生图 |
|
|
441
|
+
| 10 | Anima-Edit LoRA / IC | 52 | 图片 | ❌ 需图生图 |
|
|
442
|
+
|
|
443
|
+
判断依据是自动体检的结果:**只要 JSON 里出现 `LoadImage` 一类节点,就判定为需要图片输入**。所以 01/05/08 到底能不能用,取决于你导出时是「从空 latent 开始」还是「从图开始」——`画图 工作流` 会直接告诉你。
|
|
444
|
+
|
|
445
|
+
图生图能力(图片上传 + `LoadImage` 注入 + 重绘幅度)尚未实现,所以 ❌ 的四个目前只能等后续版本。
|
|
446
|
+
|
|
353
447
|
## 注意
|
|
354
448
|
|
|
355
449
|
- `p-draw` 指令消耗 `price` P 点,`p-draw 多人` 消耗 `multiPrice` P 点,需要先通过 `p-qiandao` 签到。
|