From a181cc1768dc2068502fadfe5453f9034d51824c Mon Sep 17 00:00:00 2001 From: Jony <951565127@qq.com> Date: Mon, 9 Nov 2026 09:11:12 +0800 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFAdd=20MJ=20image=20node,=20GIF=20save,?= =?UTF-8?q?=20and=20Kling/image=20generator=20updates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ship o1key MJ图片生成 with content/style refs and prompt flags, save-GIF with preview, Kling 4.0 helpers, plus GPT/unified image node polish and docs. --- README.md | 26 +- __init__.py | 7 +- clients/gpt_image_client.py | 144 +- clients/kling_video_client.py | 144 ++ clients/mj_image_client.py | 361 +++++ docs/architecture.md | 21 +- .../0016-kling-v4-generation-modes.md | 40 + ...0017-remove-retired-unified-nano-models.md | 19 + docs/decisions/README.md | 2 + docs/development.md | 15 +- nodes/K3_video.py | 218 ++- nodes/__init__.py | 4 +- nodes/gpt_image.py | 127 +- nodes/gpt_image_batch.py | 102 +- nodes/mj_image.py | 402 +++++ nodes/o1key_image_generator.py | 131 +- nodes/save_gif.py | 220 +++ requirements.txt | 2 + tests/test_gpt_image_migrate_tail.mjs | 124 ++ tests/test_gpt_image_nodes.py | 252 ++- tests/test_gpt_image_quality_frontend.mjs | 55 + tests/test_kling_video.py | 117 ++ tests/test_mj_prompt.py | 416 +++++ tests/test_o1key_image_generator.py | 169 +- tests/test_o1key_image_generator_frontend.mjs | 827 ++++++++-- tests/test_o1key_image_generator_layout.mjs | 201 +++ tests/test_o1key_image_jobs.py | 109 +- tests/test_o1key_image_save.py | 67 + tests/test_save_gif.py | 188 +++ utils/gpt_image_media.py | 294 ++++ utils/image_utils.py | 17 +- utils/mj_prompt.py | 264 +++ utils/o1key_image_catalog.py | 139 +- utils/o1key_image_jobs.py | 144 +- utils/o1key_image_save.py | 29 +- utils/video_task.py | 11 + web/js/gifPreview.js | 240 +++ web/js/gptImageQuality.js | 107 +- web/js/migrateWorkflow.js | 201 ++- web/js/o1keyImageGenerator.js | 1430 +++++++++++++---- 40 files changed, 6711 insertions(+), 675 deletions(-) create mode 100644 clients/kling_video_client.py create mode 100644 clients/mj_image_client.py create mode 100644 docs/decisions/0016-kling-v4-generation-modes.md create mode 100644 docs/decisions/0017-remove-retired-unified-nano-models.md create mode 100644 nodes/mj_image.py create mode 100644 nodes/save_gif.py create mode 100644 tests/test_gpt_image_migrate_tail.mjs create mode 100644 tests/test_kling_video.py create mode 100644 tests/test_mj_prompt.py create mode 100644 tests/test_o1key_image_generator_layout.mjs create mode 100644 tests/test_save_gif.py create mode 100644 utils/gpt_image_media.py create mode 100644 utils/mj_prompt.py create mode 100644 web/js/gifPreview.js diff --git a/README.md b/README.md index 60754dc..f725cf1 100644 --- a/README.md +++ b/README.md @@ -148,9 +148,11 @@ pip install -r requirements.txt --upgrade 参考图上传完成后,复制、粘贴节点或保存后重新加载工作流,会保留参考图顺序、批量目标图、蒙版和参数。图片清单引用当前 ComfyUI 的本地文件;复制后可独立调整清单。 -模型列表新增 `GPT Image 2.5 Sunburst`(最新,高质量)和 `GPT Image 2.5 Flare`(快速,日常)。两者与 GPT Image 2 使用相同的「智能 / 1K / 2K / 4K」分辨率和「智能、1:1、3:2、2:3、4:3、3:4、16:9、9:16」宽高比;特价、优质、企业线路分别调用模型 ID 的 `-sp`、`-sd` 和无后缀版本。下文的 GPT Image 2 参数说明也适用于这两个 GPT Image 2.5 模型。 +模型列表支持 `GPT Image 2.5 Sunburst / Flare` 和 `GPT Image 2.6 Sunburst / Flare`。2.6 Sunburst 偏精修与细节还原,2.6 Flare 偏快速出图;新模型加入「o1key 图片生成」、独立 GPT Image 和 GPT Image 批量跑图节点,已有默认模型与工作流选项保持不变。四者与 GPT Image 2 使用相同的「智能 / 1K / 2K / 4K」分辨率和「智能、1:1、3:2、2:3、4:3、3:4、16:9、9:16」宽高比;特价、优质、企业线路分别调用模型 ID 的 `-sp`、`-sd` 和无后缀版本。 -面板式图片生成节点统一支持 Nano Banana 系列、GPT Image 2 与 Seedream 5.0 Pro。提示词右下角使用带 `✨` 图标的「AI帮写」按钮;独立 Nano Banana 节点不再提供提示词优化按钮。参数区按“生成参数”和“保存设置”分组,采用单列参数列表,标签在左、控件在右;保留顶部批量开关、参考图区、提示词内 AI 帮写、种子右侧随机按钮和底部开始生成,控件颜色沿用当前 ComfyUI 主题,按钮不使用独立强调色;提示词独立显示为“画面描述”区域,随机种子按钮仍内嵌在种子输入框右侧。ComfyUI Nodes 1.0 因识别到 `seed` 输入而自动添加的「生成后控制」与该按钮功能重复,因此会由面板隐藏,不占用节点顶部空间。模型、线路、分辨率、宽高比、生图数量和种子常显;模型专属参数会随模型动态切换:仅 Nano Banana 2 / 2.1 显示「思考等级」和「在线搜索」,GPT Image 2 / 2.5 显示「质量」「背景」和「蒙版」,GPT Image 2 / 2.5 与 Seedream 5.0 Pro 都显示作为 API 参数的「输出格式」。在线搜索默认为「关闭」,关闭时不发送相关参数;选择「打开」时,请求体顶层发送 `google_search: true`。这些参数不收进高级设置弹层;切换模型只隐藏不适用参数,不会清空已选值。分辨率新增默认值「智能」;选择它时,Nano Banana、GPT Image 和 Seedream 的上游请求都不发送 `size`,由模型决定输出尺寸。选择具体档位时,GPT Image 2 会把分辨率与宽高比映射为具体像素尺寸;宽高比选择「智能」时按正方形映射为 `1024x1024 / 2048x2048 / 2880x2880`。背景支持自动、透明和不透明,输出格式支持 JPEG、PNG 和 WebP;新建 GPT 设置默认 PNG,已有工作流保留保存的格式,其中透明背景只能搭配 PNG 或 WebP。所有模型每次请求最多使用 10 张参考图。GPT Image 新选项支持每条提示词生成 1–8 张,旧工作流中的 9 张仍可执行;其余模型保持 `1 / 2 / 4 / 9`。GPT Image 2.5 的质量另支持「超高 / 最高」,分别发送 `xhigh / max`;GPT Image 2 仅支持原有四档。提示词支持用独占一行的 `---` 分隔多条内容;所有模型和执行入口都会按“提示词数量 × 生图数量”生成任务,任务排列为同一提示词的所选张数在前、下一条提示词随后,单次最多 1000 个任务。任务会按受控并发分批执行,GPT Image 与 Seedream 请求中的 `n` 固定为 `1`。模型线路在面板中显示为「特价(便宜)/ 优质(小贵)/ 企业(贵)」,工作流内部仍保存兼容值「畅速 / 直连 / 专线」;思考等级默认为「低」,显示为「低(耗时低,智力低)/ 高(耗时高,智力高)」;缩放图片显示为「不缩放(无大图)/ 智能缩放(有大图)」。带标签的下拉参数在菜单收起后也会显示当前选项的标签。 同一面板支持 Nodes 1.0 / 2.0 切换,参数、参考图和操作位置保持不变。 +GPT Image 2.6 新增「复杂度」:`low / medium / high`(默认 `high`),控制渲染前的规划强度,越高规划越充分、耗时越长。该控件仅选择 2.6 时显示,切回旧模型会隐藏并保留选择,旧模型请求省略 `complexity`。2.6 同样支持「超高 / 最高」质量。2.6 额外支持 SVG / GIF 输出(仅纯文生图,有参考图或蒙版时前端会隐藏并后端拒绝):GIF 会展开为 IMAGE 批帧,同时保留原始 GIF 文件:独立节点通过 FILE 路径与带 `animated` 标志的节点内预览播放;统一面板在保存格式为「原始」时会把 GIF 原样落到 output,并由保存节点以可播放方式预览;SVG 会落盘 `.svg`,并额外返回栅格化 IMAGE 预览(优先 cairosvg / ImageMagick / Inkscape,否则占位图)。GIF 控件 `帧数`(2–64,默认 9)与 `帧时长ms`(20–2000,默认 200,按 10ms 取整)仅在格式为 gif 时显示。独立 `markup` 标注图参数仍未接入;现有参考图、蒙版和前端图像编辑功能保持原有方式。更新后重启 ComfyUI 并硬刷新页面即可选择新模型与格式。 + +面板式图片生成节点统一支持 Nano Banana 2.1 / 2 / Pro、GPT Image 2 与 Seedream 5.0 Pro。旧工作流中的 Nano Banana 2 Lite 和 Nano Banana 会在加载前迁移为 Nano Banana 2,避免重启后下拉选项变化导致参数错位。提示词右下角使用带 `✨` 图标的「AI帮写」按钮;独立 Nano Banana 节点不再提供提示词优化按钮。参数区采用 LiteGraph 原生参数控件,提示词和参考图保留自定义面板;模型、线路、分辨率、宽高比、生图数量等参数行由原生控件负责渲染并把标题和值放在同一个参数框内,种子保留一行紧凑的随机按钮;保留批量开关、参考图区、提示词内 AI 帮写和底部开始生成,控件颜色沿用当前 ComfyUI 主题,按钮不使用独立强调色;提示词区域不再显示额外标题,默认输入框展示约 3 行内容;随机种子按钮仍内嵌在种子输入框右侧。ComfyUI Nodes 1.0 因识别到 `seed` 输入而自动添加的「生成后控制」与该按钮功能重复,因此会由面板隐藏,不占用节点顶部空间。模型、线路、分辨率、宽高比、生图数量和种子常显;模型专属参数会随模型动态切换:仅 Nano Banana 2 / 2.1 显示「思考等级」,GPT Image 2 / 2.5 / 2.6 显示「质量」「背景」和「蒙版」,GPT Image 2 / 2.5 / 2.6 与 Seedream 5.0 Pro 都显示作为 API 参数的「输出格式」。这些参数不收进高级设置弹层;切换模型只隐藏不适用参数,不会清空已选值。分辨率新增默认值「智能」;选择它时,Nano Banana、GPT Image 和 Seedream 的上游请求都不发送 `size`,由模型决定输出尺寸。选择具体档位时,GPT Image 2 会把分辨率与宽高比映射为具体像素尺寸;宽高比选择「智能」时按正方形映射为 `1024x1024 / 2048x2048 / 2880x2880`。背景支持自动、透明和不透明,输出格式支持 JPEG、PNG 和 WebP;新建 GPT 设置默认 PNG,已有工作流保留保存的格式,其中透明背景只能搭配 PNG 或 WebP。所有模型每次请求最多使用 10 张参考图。GPT Image 新选项支持每条提示词生成 1–8 张,旧工作流中的 9 张仍可执行;其余模型保持 `1 / 2 / 4 / 9`。GPT Image 2.5 的质量另支持「超高 / 最高」,分别发送 `xhigh / max`;GPT Image 2 仅支持原有四档。提示词支持用独占一行的 `---` 分隔多条内容;所有模型和执行入口都会按“提示词数量 × 生图数量”生成任务,任务排列为同一提示词的所选张数在前、下一条提示词随后,单次最多 1000 个任务。任务会按受控并发分批执行,GPT Image 与 Seedream 请求中的 `n` 固定为 `1`。模型线路在面板中显示为「特价(便宜)/ 优质(小贵)/ 企业(贵)」,工作流内部仍保存兼容值「畅速 / 直连 / 专线」;新建节点的思考等级默认为「高」,显示为「低(耗时低,智力低)/ 高(耗时高,智力高)」;缩放图片默认为「智能缩放」,显示为「不缩放(无大图)/ 智能缩放(有大图)」。下拉菜单展开时可查看选项说明,收起后参数框只显示当前值。 同一面板支持 Nodes 1.0 / 2.0 切换,参数、参考图和操作位置保持不变。 Seedream 5.0 Pro 位于 GPT Image 2 下方,支持「智能 / 1K / 2K」分辨率与「智能、1:1、4:3、3:4、16:9、9:16、3:2、2:3、21:9」宽高比;具体档位会转换为接口要求的精确像素尺寸。参考图通过当前全局线路的 `/v1/o1key/uploads` 上传为临时 HTTPS URL,再按原顺序传入 `images`。输出格式实际发送 `output_format=png/jpeg`;水印不提供界面开关,固定发送 `watermark=false`。 @@ -165,21 +167,21 @@ Seedream 还提供「图层拆分」。开启后必须且只能上传 1 张待 - 「素材图」提供需要引用的对象、元素、风格、材质或结构。 - 「目标图」是素材内容最终要应用到的图片。 -批量模式提供三种执行方式: +批量模式提供三种执行方式,命名不绑定行业:服装的成套搭配、家具的板式与场景、包装的刀版与瓶型、建筑的立面与体块、平面设计的版式与画幅,都可以用「素材 / 目标」来表达。 -- 「整组素材 → 多个目标」会把当前所有素材图作为一组,并依次与每张目标图组成一次请求。例如 3 张素材图、10 张目标图、每组生图数为 1 时,共生成 10 张;该模式每组最多 9 张素材图,为当前目标图保留第 10 个参考位。 -- 「全匹配(素材 × 目标)」会把每张素材图分别与每张目标图组合。例如 10 张素材图和 10 张目标图会展开为 100 个请求。每个请求只携带当前素材图和当前目标图,不会把 20 张图片一起发送给模型。 -- 「单图批量(每张素材独立)」不需要目标图。将多张模特图上传到素材区后,每张图都会作为该次请求的唯一参考图,适合批量换动作、换表情或做其他无需额外对照图的修改。选中后目标图区会隐藏,已保存的目标图清单不参与该批次。 +- 「整组素材→多个目标」会把当前所有素材图作为一组,并依次与每张目标图组成一次请求。例如 3 张素材图、10 张目标图、每组生图数为 1 时,共生成 10 张;该模式每组最多 9 张素材图,为当前目标图保留第 10 个参考位。 +- 「每张素材×每张目标」会把每张素材图分别与每张目标图组合。例如 10 张素材图和 10 张目标图会展开为 100 个请求。每个请求只携带当前素材图和当前目标图,不会把 20 张图片一起发送给模型。 +- 「每张素材单独出图」不需要目标图。把多张素材图上传到素材区后,每张图都会作为该次请求的唯一参考图,适合批量换动作、换表情、换配色、换字体或做其他无需额外对照图的修改。选中后目标图区会隐藏,已保存的目标图清单不参与该批次。 -批量素材和目标清单的上限均为 50 张。「整组素材 → 多个目标」由于会把整组素材放入同一次请求,素材区仍限 9 张,但目标图可上传 50 张;「全匹配」和「单图批量」的素材区可上传 50 张。最终展开后仍受单次 1000 个任务上限约束。 +批量素材和目标清单的上限均为 50 张。「整组素材→多个目标」由于会把整组素材放入同一次请求,素材区仍限 9 张,但目标图可上传 50 张;「每张素材×每张目标」和「每张素材单独出图」的素材区可上传 50 张。最终展开后仍受单次 1000 个任务上限约束。旧存档里的旧标签(`一组搭配+多模特`、`全部搭配×全部模特`、`单图素材批量`)载入时会自动改写为新标签,配对行为保持不变。 -素材图和目标图使用两条独立的横向大卡轨道,缩略图为 `102 × 102`,上传和「画布取图」收在各自标题行;普通模式沿用同一套大卡样式,只显示参考图轨道。轨道通过独立的最大 `256 × 256` WebP 预览加载图片,只有打开全屏大图时才读取原始文件;缩略图不会覆盖原图,AI帮写和生成 API 始终使用上传到 `input` 的原始图片。标题行同时显示当前图片数量,素材图区说明会随模式切换:「整组素材 → 多个目标」显示“整组参与”,「全匹配(素材 × 目标)」显示“匹配时每张独立”,「单图批量」显示“每张独立生成”。 +素材图和目标图使用两条独立的横向大卡轨道,缩略图为 `102 × 102`;轨道末尾的「+ 添加素材图 / 添加目标图」卡片是唯一上传入口,标题行只保留轨道名称和「画布取图」按钮。普通模式沿用同一套大卡样式,只显示参考图轨道。轨道通过独立的最大 `256 × 256` WebP 预览加载图片,只有打开全屏大图时才读取原始文件;缩略图不会覆盖原图,AI帮写和生成 API 始终使用上传到 `input` 的原始图片。普通模式下标题行还会显示当前图片数量(如 `1 张 · 最多 10 张`);批量模式为保持标题简洁不再显示这行说明,图片张数与组合数由下方预览行统一给出。 上传后,每张缩略图左下角显示它在实际模型请求中的图号,例如「图2」或「图4」。缩略图不再显示独立的排序手柄;鼠标左键按住图片即可直接拖动排序。拖动时原卡片会明显缩小、变暗并显示“移动中”,当前轨道同步高亮,目标位置通过粗插入线和卡片位移展示。缩略图获得焦点后,也可用 `Alt + ←/→` 前后微调,或用 `Alt + Home/End` 移到首尾。素材图和目标图分别排序,调整后图号、工作流清单、AI帮写和实际生成请求会立即使用新顺序;仍有图片上传时会暂时锁定当前图片组的排序。第1张参考图会标明其主图/色彩基准语义。单击已上传的缩略图会在当前 ComfyUI 画布上打开与左侧「资产」一致的全屏大图预览;拖动操作结束后不会误触大图。可点击遮罩或关闭按钮,也可按 `Esc` 关闭,多图使用左右按钮或方向键切换。缩略图悬停时不显示额外文字标签。批量界面不显示额外的“描述示例”板块。 每张参考图、素材图和目标图的右下角都有「替换」按钮:选择一张本地图片后,新图会留在原位置,其他图片和顺序不变;验证或上传失败时保留旧图。左上角的编辑按钮继续用于裁剪和标记。点击后可按「自由 / 原图 / 1:1 / 4:3 / 3:4 / 3:2 / 2:3 / 16:9 / 9:16」快速裁剪,也可用「遮罩」画笔涂出半透明红色关注区域,或用彩色「画笔」自由圈选和批注物品。「箭头」从按下位置开始、以松开位置作为箭头尖端,用于精确指定需要关注或修改的画面位置,并支持颜色与粗细调整。「贴图」可从本地上传一张上层图片:拖动图片移动,拖动四角等比缩放,拖动顶部圆点旋转,按住 `Shift` 时以 15° 吸附;还可调节透明度、替换、移除或重置贴图。编辑器支持撤销和重做;应用后会把裁剪、贴图与标记合成为一张新的 PNG,通过 ComfyUI 原生上传接口写入 `input` 并替换当前清单项,原文件不会被覆盖。箭头、画笔和视觉遮罩位于贴图之上,确保指示内容不会被遮挡。贴图的控制框不会进入输出;贴图源文件只在当前弹窗中临时读取,不会写入工作流。「遮罩」是直接合成进图片的视觉标记,不会创建或修改 ComfyUI `MASK` 数据,也不会自动填入 GPT Image 的「蒙版」参数。 -配对模式中的「生图数量」显示为「每组生图数」;单图批量中显示为「每图生成数」。界面会按“有效提示词数 × 配对或素材数 × 每组/每图生图数”显示任务总数,并受单次 1000 个任务上限约束。Nano Banana 与 GPT Image 2、面板后台任务与标准 ComfyUI 执行使用相同的展开顺序;单个失败槽位只重试原来的参考图组合。批量出图暂不支持 GPT 蒙版编辑,开启前需先移除蒙版。 +配对模式中的「生图数量」显示为「每组生图数」;「每张素材单独出图」中显示为「每图生成数」。素材图与目标图之间会实时显示一行出图预览,格式为“`整组 3 张素材 × 4 个目标 = 4 组 · 每组 2 张 · 2 条提示词` + `共 16 张`”,随素材、目标、生图数量、提示词条数和模式切换即时刷新,并受单次 1000 个任务上限约束。Nano Banana 与 GPT Image 2、面板后台任务与标准 ComfyUI 执行使用相同的展开顺序;单个失败槽位只重试原来的参考图组合。批量出图暂不支持 GPT 蒙版编辑,开启前需先移除蒙版。 提示词框右下角提供“魔法棒图标 + AI帮写”的文字按钮。填写提示词并按需上传参考图后,点击按钮会使用 `gpt-5.6-sol` 和高思考分析当前文字及全部参考图;处理期间会显示“AI帮写中…”,完成后再将一份可直接用于生图的提示词回填到原输入框。优化以视觉元素与具体对象的绑定为第一优先级;图生图场景会进一步明确必须保持不变的内容和需要改变的目标。API Key 只在服务端读取,不会传给浏览器或写入工作流。 @@ -197,7 +199,7 @@ Nano Banana 与 GPT Image 2 的最终 UTF-8 JSON 请求体(含 Base64)都按 本地「格式」只在 Banana 模型下显示,默认「原始」,也可选 `PNG / JPEG / WebP`;它控制保存时是否转换容器。Nano Banana 不接收 `output_format`,所以模型返回 PNG 就保留 PNG,返回 JPEG 就保留 JPEG,除非这里显式转换。GPT Image 2 不使用这个本地参数,而使用独立的 API「输出格式」;可选 `JPEG / PNG / WebP`,默认 `JPEG`,实际请求值为小写 `jpeg`。Seedream 同样使用 API「输出格式」,只提供 `PNG / JPEG`,并按所选值保存上游原始容器。透明背景仍只支持 GPT Image 的 PNG 或 WebP。保存节点写入可恢复工作流时遵循 ComfyUI 原生图片元数据约定:PNG 保存 `prompt` 和 `workflow` 文本块;由于 ComfyUI 不从 JPEG 读取工作流且 JPEG EXIF 容量有限,带工作流的 JPEG 来源或 JPEG 保存选项会自动落盘为 PNG。将该 PNG 拖回或载入 ComfyUI 即可恢复工作流;关闭 ComfyUI 全局元数据写入时仍按所选 JPEG 保存,但不会附带工作流。 -生成参数沿用 ComfyUI 主题颜色,使用垂直居中的下拉箭头;模型列表会显示用途说明。新建节点默认尺寸为 `560 × 1035`,提示词框约显示 5 行内容;开启批量出图或切换到参数较多的 GPT Image 2 时,节点会增加高度以容纳额外控件。`Nano Banana 2 / 2.1` 提供 `1K / 2K / 4K` 分辨率,不再提供 `512`。批次提交后,「o1key 保存图像」会立即按实际任务展开顺序排列固定图片槽位;每张图片完整下载到 ComfyUI `temp` 后会立即显示在对应槽位,无需等待整批完成,全部成功后再切回 ComfyUI 原生图片预览并按设置永久保存。拖动保存节点改变宽度或高度时,原生单图和多图预览会同步使用全部可用区域重新排布并等比缩放,不裁切图片,也不保留旧节点尺寸产生的固定空白。若部分图片失败,成功图仍保留在原序号位置,失败槽位显示独立重试按钮;不同失败槽位可以连续点击并行重试,每个槽位只重新提交自己的原提示词和原素材组合,先完成的重试不会结束或覆盖仍在运行的其他槽位。槽位状态和安全的结果描述会随工作流保存、刷新恢复,且槽位视图与原生预览不会同时叠加。原生下载按钮会替换为白底黑色的重新生成图标;在全成功的多图结果中先选中目标图片,再点击该图标,即可沿用当前参数和新的随机种子只生成 1 张新图,且不会修改生成面板中原来选择的生图数量。生成过程中仍保留顶部细进度条,不显示百分比文案。 +生成参数沿用 ComfyUI 主题颜色,使用垂直居中的下拉箭头;模型列表会显示用途说明。新建节点默认尺寸为 `560 × 1035`,提示词框默认约显示 3 行内容;开启批量出图或切换到参数较多的 GPT Image 2 时,节点会增加高度以容纳额外控件。`Nano Banana 2 / 2.1` 提供 `1K / 2K / 4K` 分辨率,不再提供 `512`。批次提交后,「o1key 保存图像」会立即按实际任务展开顺序排列固定图片槽位;每张图片完整下载到 ComfyUI `temp` 后会立即显示在对应槽位,无需等待整批完成,全部成功后再切回 ComfyUI 原生图片预览并按设置永久保存。拖动保存节点改变宽度或高度时,原生单图和多图预览会同步使用全部可用区域重新排布并等比缩放,不裁切图片,也不保留旧节点尺寸产生的固定空白。若部分图片失败,成功图仍保留在原序号位置,失败槽位显示独立重试按钮;不同失败槽位可以连续点击并行重试,每个槽位只重新提交自己的原提示词和原素材组合,先完成的重试不会结束或覆盖仍在运行的其他槽位。槽位状态和安全的结果描述会随工作流保存、刷新恢复,且槽位视图与原生预览不会同时叠加。原生下载按钮会替换为白底黑色的重新生成图标;在全成功的多图结果中先选中目标图片,再点击该图标,即可沿用当前参数和新的随机种子只生成 1 张新图,且不会修改生成面板中原来选择的生图数量。生成过程中仍保留顶部细进度条,不显示百分比文案。 旧工作流加载时,会把保存节点原有的「文件名前缀 / 格式 / 保存位置 / 命名规则」迁移到相连的「o1key 图片生成」节点;保存节点自身的旧控件值随后清除。迁移不会改动节点 ID 或图像连线。 @@ -243,6 +245,10 @@ Nano Banana 与 GPT Image 2 的最终 UTF-8 JSON 请求体(含 Base64)都按 `Grok Video Edit` 使用独立的编辑和延长接口,并共用同一任务查询端点。两种操作都可选择上述两个模型。编辑输入视频不能超过 8.7 秒,输出保持原时长和宽高比且最高 720p;延长时长为 2~10 秒,最终总时长等于输入时长加延长时长。节点会先校验模式、模型、素材数量、分辨率和时长,再上传临时素材并提交任务;完成后立即下载结果并输出 ComfyUI 原生 `VIDEO`。 +### K 视频生成 / Kling 4.0 + +`K 视频生成` 保留原有 `K3Video` 节点 ID,并在模型下拉框追加 `v4`。选择 `v4` 后显示“文生视频 / 关键帧 / 全能参考”生成模式:文生只提交提示词;关键帧使用首帧,可再连接最多 8 张中间帧和 1 张尾帧;全能参考使用最多 10 张参考图和 5 段参考视频。Kling 4.0 支持 3~30 秒、720p/1080p,以及智能、16:9、9:16、1:1、21:9 宽高比;关键帧模式按首帧比例提交,原生音频由 Kling 4.0 默认生成。素材会先上传到当前 O1Key 线路,再通过对应的 Kling `/text2video`、`/image2video` 或 `/omni-video` 任务接口提交、轮询和下载。旧 v3、v2.6 和 v3-omni 分支的输入顺序与请求行为保持兼容。 + ### 视频裁剪 「视频裁剪」只需点击节点内的「上传视频」选择文件,也可连接上游 `VIDEO`;上传后的内部文件路径会随工作流保存,但不显示为用户参数。视频加载后可直接预览并拖动时间轴。固定时长大于 0 时,绿色选区会保持该长度并可整体拖动;固定时长为 0 时使用开始、结束时间自由裁剪。 diff --git a/__init__.py b/__init__.py index a0989b9..8db4068 100644 --- a/__init__.py +++ b/__init__.py @@ -72,7 +72,7 @@ if not getattr(asyncio, "_o1key_new_event_loop_patched", False): asyncio._o1key_new_event_loop_patched = True from .nodes import NanoBananaPro, BatchNanoBananaPro, GoogleGemini, LoadFile, LoadImagesFromFolder, ImageStitchPro, BatchCleanMetadata, VideoPreview, GoogleVeo, Google31Video, MiniMaxH3Video, FluxImageEdit, UniversalLLMChat, BatchImagesO1key, SeedanceMultiModal, StreamPreview, DoubaoImage, O1keyGPTImage, O1keyGPTImageBatch, O1keyGrokImage, O1keyGrokVideo, O1keyGrokVideoEdit -from .nodes import K3Video, K3MotionControl, SaveImageFormat +from .nodes import K3Video, K3MotionControl, SaveImageFormat, O1keySaveGIF from .nodes import O1keySavePSD from .nodes import O1keyRemoveBackground from .nodes import O1keyGridSplitter @@ -85,6 +85,7 @@ from .nodes import O1keyAutoRedCast from .nodes import O1keyImageGenerator, O1keyImageSave from .nodes import O1keyVideoGenerator, O1keyVideoResult from .nodes import O1keyOmniFlashVideo +from .nodes import O1keyMJImage # 报错弹框友好文案(不修改原节点代码,仅在外层统一处理) _MSG_TIMEOUT = "API 请求超时,请稍后重试或检查网络。" @@ -148,6 +149,7 @@ NODE_CLASS_MAPPINGS = { "K3Video": K3Video, "K3MotionControl": K3MotionControl, "SaveImageFormat": SaveImageFormat, + "O1keySaveGIF": O1keySaveGIF, "O1keySavePSD": O1keySavePSD, "O1keyRemoveBackground": O1keyRemoveBackground, "O1keyGridSplitter": O1keyGridSplitter, @@ -162,12 +164,14 @@ NODE_CLASS_MAPPINGS = { "O1keyVideoGenerator": O1keyVideoGenerator, "O1keyVideoResult": O1keyVideoResult, "O1keyOmniFlashVideo": O1keyOmniFlashVideo, + "O1keyMJImage": O1keyMJImage, } NODE_DISPLAY_NAME_MAPPINGS = { "O1keyVideoGenerator": "o1key 视频生成", "O1keyVideoResult": "o1key 视频结果", "O1keyOmniFlashVideo": "Omni Flash 视频生成", + "O1keyMJImage": "o1key MJ图片生成", "NanoBanana": "Nano Banana", "BatchNanoBananaPro": "Nano Banana 批量跑图", "GoogleGemini": "Google Gemini", @@ -195,6 +199,7 @@ NODE_DISPLAY_NAME_MAPPINGS = { "K3Video": "K 视频生成", "K3MotionControl": "K 动作模仿", "SaveImageFormat": "保存图像(格式转换)", + "O1keySaveGIF": "保存 GIF", "O1keySavePSD": "保存 PSD(分层)", "O1keyRemoveBackground": "去背景(rembg)", "O1keyGridSplitter": "合并图智能切割", diff --git a/clients/gpt_image_client.py b/clients/gpt_image_client.py index d173434..cf8bffb 100644 --- a/clients/gpt_image_client.py +++ b/clients/gpt_image_client.py @@ -42,9 +42,14 @@ from ..utils.http2_client import ( from ..utils.o1key_image_catalog import ( GPT_IMAGE_BACKGROUND_OPTIONS, GPT_IMAGE_MODEL_OPTIONS, - GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, + resolve_gpt_image_complexity, + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + resolve_gpt_image_output_format, + validate_gpt_image_vector_output, UNIFIED_IMAGE_ROUTE_OPTIONS, ) +from ..utils.gpt_image_media import materialize_result_images try: from comfy.model_management import processing_interrupted, InterruptProcessingException @@ -63,15 +68,21 @@ _ENDPOINT_ASYNC_TASK = "/async/v1/tasks/{task_id}" # ── 主模型与模型线路映射(界面值 → API 模型名)────────────────────────────── GPT_IMAGE_ROUTE_OPTIONS = UNIFIED_IMAGE_ROUTE_OPTIONS GPT_IMAGE_MODEL_MATRIX = { - ("gpt-image-2", "畅速"): "gpt-image-2-c-sp", - ("gpt-image-2", "直连"): "gpt-image-2-c-sd", - ("gpt-image-2", "专线"): "gpt-image-2", + ("gpt-image-2.6-sunburst", "畅速"): "gpt-image-2.6-sunburst-sp", + ("gpt-image-2.6-sunburst", "直连"): "gpt-image-2.6-sunburst-sd", + ("gpt-image-2.6-sunburst", "专线"): "gpt-image-2.6-sunburst", + ("gpt-image-2.6-flare", "畅速"): "gpt-image-2.6-flare-sp", + ("gpt-image-2.6-flare", "直连"): "gpt-image-2.6-flare-sd", + ("gpt-image-2.6-flare", "专线"): "gpt-image-2.6-flare", ("gpt-image-2.5-sunburst", "畅速"): "gpt-image-2.5-sunburst-sp", ("gpt-image-2.5-sunburst", "直连"): "gpt-image-2.5-sunburst-sd", ("gpt-image-2.5-sunburst", "专线"): "gpt-image-2.5-sunburst", ("gpt-image-2.5-flare", "畅速"): "gpt-image-2.5-flare-sp", ("gpt-image-2.5-flare", "直连"): "gpt-image-2.5-flare-sd", ("gpt-image-2.5-flare", "专线"): "gpt-image-2.5-flare", + ("gpt-image-2", "畅速"): "gpt-image-2-c-sp", + ("gpt-image-2", "直连"): "gpt-image-2-c-sd", + ("gpt-image-2", "专线"): "gpt-image-2", } _MODEL_NAME_MAP = { "畅速": "gpt-image-2-c-sp", @@ -246,13 +257,15 @@ class GptImageClient: session: aiohttp.ClientSession, url: str, label: str, - ) -> tuple[Image.Image, int, float]: - """Download and fully decode an image, retrying interrupted GET reads.""" + requested_format: Optional[str] = None, + ) -> tuple[list[Image.Image], int, float]: + """Download and fully decode result bytes, retrying interrupted GET reads.""" download_started = time.perf_counter() for attempt in range(_RESPONSE_READ_MAX_RETRIES + 1): try: async with session.get(url, allow_redirects=True) as resp: image_bytes, diagnostics = await read_response_body_with_diagnostics(resp) + content_type = str(resp.headers.get("Content-Type") or "") if resp.status != 200: print( f"[o1key GPT Image] 结果下载传输追踪" @@ -263,10 +276,12 @@ class GptImageClient: raise _RetryableResultHTTPError(message) raise RuntimeError(message) - image = Image.open(BytesIO(image_bytes)) - image.load() - _attach_original_image_info(image, image_bytes) - return image, len(image_bytes), time.perf_counter() - download_started + images = materialize_result_images( + image_bytes, + requested_format=requested_format, + content_type=content_type, + ) + return images, len(image_bytes), time.perf_counter() - download_started except ( aiohttp.ClientError, asyncio.TimeoutError, @@ -807,19 +822,26 @@ class GptImageClient: raise RuntimeError(f"{label} base64 解码失败: {e}") from None @staticmethod - def _decode_inline_result_image(b64: str, label: str) -> tuple[Image.Image, int]: - """Strictly decode and fully load a completed task's inline image.""" + def _decode_inline_result_image( + b64: str, + label: str, + requested_format: Optional[str] = None, + ) -> tuple[list[Image.Image], int]: + """Strictly decode and fully load a completed task's inline image/media.""" try: if not isinstance(b64, str) or not b64: raise ValueError("empty base64 payload") image_bytes = base64.b64decode(b64, validate=True) if not image_bytes: raise ValueError("decoded image is empty") - image = Image.open(BytesIO(image_bytes)) - image.load() - _attach_original_image_info(image, image_bytes) - return image, len(image_bytes) - except (binascii.Error, ValueError, OSError, UnidentifiedImageError) as exc: + images = materialize_result_images( + image_bytes, + requested_format=requested_format, + ) + if not images: + raise ValueError("decoded image is empty") + return images, len(image_bytes) + except (binascii.Error, ValueError, OSError, UnidentifiedImageError, RuntimeError) as exc: raise _IncompleteInlineImageError(f"{label}不完整或无法解码: {exc}") from None async def _append_images_from_payload( @@ -1064,21 +1086,37 @@ class GptImageClient: background: str = "auto", moderation: Optional[str] = None, resize_mode: Optional[str] = None, + complexity: Optional[str] = None, + frame_count=None, + frame_duration_ms=None, ) -> dict: if int(n) != 1: raise ValueError("GPT Image 单次请求的 n 必须为 1;多图请使用外层并发") - output_format = str(output_format or "png").strip().lower() background = str(background or "auto").strip().lower() moderation = str(moderation).strip().lower() if moderation is not None else None - if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: - raise ValueError("GPT Image 输出格式无效") if background not in GPT_IMAGE_BACKGROUND_OPTIONS: raise ValueError("GPT Image 背景参数无效") if moderation not in {None, "low"}: raise ValueError("GPT Image 内容审查强度无效") - if background == "transparent" and output_format == "jpeg": - raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") api_model = _MODEL_NAME_MAP.get(model, model) + base_model = next((base for base in GPT_IMAGE_MODEL_OPTIONS + if api_model in {base, base + "-sp", base + "-sd"}), api_model) + output_format = resolve_gpt_image_output_format(base_model, output_format) + if background == "transparent" and output_format not in {"png", "webp"}: + raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") + has_images = bool(image_list) + has_mask = mask_tensor is not None + validate_gpt_image_vector_output( + base_model, + output_format, + has_images=has_images, + has_mask=has_mask, + ) + frame_count_value = resolve_gpt_image_frame_count(output_format, frame_count) + frame_duration_value = resolve_gpt_image_frame_duration_ms( + output_format, frame_duration_ms + ) + complexity_value = resolve_gpt_image_complexity(base_model, complexity) assets: List[Dict[str, Any]] = [] image_keys: List[str] = [] mask_key = None @@ -1133,6 +1171,12 @@ class GptImageClient: body["mask"] = { "image_url": self._png_bytes_to_data_url(asset_bytes[mask_key]) } + if complexity_value is not None: + body["complexity"] = complexity_value + if frame_count_value is not None: + body["frame_count"] = frame_count_value + if frame_duration_value is not None: + body["frame_duration_ms"] = frame_duration_value if moderation == "low": body["moderation"] = "low" return body @@ -1273,6 +1317,7 @@ class GptImageClient: result_url_callback: Optional[Callable[[str], None]] = None, log_downloads: bool = True, log_prefix: str = "[o1key GPT Image]", + requested_format: Optional[str] = None, ) -> List[Image.Image]: data = task.get("data", {}) image_items = data.get("images") if isinstance(data, dict) else None @@ -1297,42 +1342,47 @@ class GptImageClient: f"第 {idx} 张内联 data URL 缺少有效 Base64 头" ) started = time.perf_counter() - img, byte_count = self._decode_inline_result_image( + decoded, byte_count = self._decode_inline_result_image( b64_data, f"第 {idx} 张内联 data URL 图片", + requested_format=requested_format, ) - images.append(img) + images.extend(decoded) if log_downloads: + first = decoded[0] print( f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 data URL,无网络下载 | " - f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | " + f"{first.size[0]}×{first.size[1]}×{len(decoded)} | {self._format_transfer_size(byte_count)} | " f"解码={time.perf_counter() - started:.2f}s" ) elif url and isinstance(url, str) and url.startswith("http"): if log_downloads: print(f"{log_prefix} 下载图像 {idx}/{len(image_items)} 开始") - img, byte_count, elapsed = await self._download_image_with_response_retry( - session, url, f"第 {idx} 张图片" + downloaded, byte_count, elapsed = await self._download_image_with_response_retry( + session, url, f"第 {idx} 张图片", requested_format=requested_format, ) - images.append(img) + images.extend(downloaded) result_urls.append(url) if log_downloads: + first = downloaded[0] print( f"{log_prefix} 下载图像 {idx}/{len(image_items)} 完成 | " - f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | " + f"{first.size[0]}×{first.size[1]}×{len(downloaded)} | {self._format_transfer_size(byte_count)} | " f"{elapsed:.2f}s | {self._format_transfer_rate(byte_count, elapsed)}" ) elif b64: started = time.perf_counter() - img, byte_count = self._decode_inline_result_image( + decoded, byte_count = self._decode_inline_result_image( b64, f"第 {idx} 张内联 Base64 图片", + requested_format=requested_format, ) - images.append(img) + images.extend(decoded) if log_downloads: + first = decoded[0] print( f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 base64,无网络下载 | " - f"{img.size[0]}×{img.size[1]} | {self._format_transfer_size(byte_count)} | " + f"{first.size[0]}×{first.size[1]}×{len(decoded)} | {self._format_transfer_size(byte_count)} | " f"解码={time.perf_counter() - started:.2f}s" ) else: @@ -1366,6 +1416,7 @@ class GptImageClient: result_url_callback: Optional[Callable[[str], None]] = None, log_downloads: bool = True, log_prefix: str = "[o1key GPT Image]", + requested_format: Optional[str] = None, ) -> tuple[dict, List[Image.Image]]: """Re-fetch a completed task when its inline image is incomplete.""" current_task = task @@ -1377,6 +1428,7 @@ class GptImageClient: result_url_callback=result_url_callback, log_downloads=log_downloads, log_prefix=log_prefix, + requested_format=requested_format, ) return current_task, images except _IncompleteInlineImageError as exc: @@ -1422,6 +1474,9 @@ class GptImageClient: log_request_start: bool = True, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, resize_mode: Optional[str] = None, + complexity: Optional[str] = None, + frame_count=None, + frame_duration_ms=None, ) -> List[Image.Image]: body = self._build_async_generate_body( prompt=prompt, @@ -1435,6 +1490,9 @@ class GptImageClient: background=background, moderation=moderation, resize_mode=resize_mode, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) mode = "图像编辑" if mask_tensor is not None else ("图生图" if image_tensor else "文生图") @@ -1470,6 +1528,7 @@ class GptImageClient: result_url_callback=_on_result_url, log_downloads=log_downloads, log_prefix=log_prefix, + requested_format=output_format, ) if task_completed_callback: task_completed_callback(task_id, len(images), time.time() - task_started, upstream_urls) @@ -1496,6 +1555,9 @@ class GptImageClient: log_request_start: bool = True, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, resize_mode: Optional[str] = None, + complexity: Optional[str] = None, + frame_count=None, + frame_duration_ms=None, ) -> List[Image.Image]: """多图生成:并发提交 n 个单图任务,每个请求固定传 n=1。""" request_count = max(1, int(n)) @@ -1540,6 +1602,9 @@ class GptImageClient: log_request_start=log_request_start, task_completed_callback=task_completed_callback, resize_mode=resize_mode, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) ) for task_index in range(request_count) @@ -1870,6 +1935,9 @@ class GptImageClient: log_request_start: bool = True, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, resize_mode: Optional[str] = None, + complexity: Optional[str] = None, + frame_count=None, + frame_duration_ms=None, ) -> List[Image.Image]: """异步公共入口;多图始终拆成并发的 n=1 单图请求。""" requested_n = max(1, int(n)) @@ -1894,6 +1962,9 @@ class GptImageClient: log_request_start=log_request_start, task_completed_callback=task_completed_callback, resize_mode=resize_mode, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) return await self._generate_image_task_async( prompt=prompt, @@ -1915,6 +1986,9 @@ class GptImageClient: log_request_start=log_request_start, task_completed_callback=task_completed_callback, resize_mode=resize_mode, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) def generate_image_async_sync( @@ -1939,6 +2013,9 @@ class GptImageClient: log_request_start: bool = True, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, resize_mode: Optional[str] = None, + complexity: Optional[str] = None, + frame_count=None, + frame_duration_ms=None, ) -> List[Image.Image]: """ 新版异步任务入口,供节点调用。 @@ -1965,6 +2042,9 @@ class GptImageClient: log_request_start=log_request_start, task_completed_callback=task_completed_callback, resize_mode=resize_mode, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) def _run(): diff --git a/clients/kling_video_client.py b/clients/kling_video_client.py new file mode 100644 index 0000000..3bb5191 --- /dev/null +++ b/clients/kling_video_client.py @@ -0,0 +1,144 @@ +"""Kling 4.0 request helpers. + +The released K video node still owns the HTTP task lifecycle. This module +keeps the Kling 4.0 capability matrix and request shape in one testable place +so the node only has to upload media and call the existing poll/download +pipeline. +""" + +from __future__ import annotations + + +KlingV4GenerationMode = str + +GENERATION_MODES = { + "text": "文生视频", + "keyframes": "关键帧", + "omni": "全能参考", +} + +ENDPOINTS = { + "text": ("/kling/v1/videos/text2video", "/kling/v1/videos/text2video/{task_id}"), + "keyframes": ("/kling/v1/videos/image2video", "/kling/v1/videos/image2video/{task_id}"), + "omni": ("/kling/v1/videos/omni-video", "/kling/v1/videos/omni-video/{task_id}"), +} + +_RESOLUTION_MODE = {"720p": "std", "1080p": "pro"} +_ASPECT_RATIOS = {"智能", "16:9", "9:16", "1:1", "21:9"} + + +def canonical_generation_mode(value: str) -> str: + """Return the wire value for a displayed Kling 4.0 generation mode.""" + + if value in GENERATION_MODES: + return value + for wire_value, display_value in GENERATION_MODES.items(): + if value == display_value: + return wire_value + raise ValueError(f"不支持的 Kling 4.0 生成模式:{value}") + + +def build_kling_v4_body( + *, + generation_mode: str, + prompt: str, + negative_prompt: str = "", + duration: int = 5, + resolution: str = "720p", + aspect_ratio: str = "智能", + first_frame: str | None = None, + middle_frames: list[str] | None = None, + last_frame: str | None = None, + reference_images: list[str] | None = None, + reference_videos: list[str] | None = None, + keep_original_sound: bool = False, +) -> dict: + """Build a Kling 4.0 proxy request without credentials or media bytes. + + The proxy accepts the legacy Kling envelope (`model_name`, `mode`, and + `metadata`) and maps the metadata fields to the official Kling 4.0 + contents/settings representation. Keyframes and Omni references are + mutually exclusive at the provider boundary. + """ + + mode = canonical_generation_mode(generation_mode) + prompt = str(prompt or "").strip() + if not prompt: + raise ValueError("Kling 4.0 生成模式下提示词不能为空") + if resolution not in _RESOLUTION_MODE: + raise ValueError("Kling 4.0 仅支持 720p 或 1080p") + try: + duration = int(duration) + except (TypeError, ValueError): + raise ValueError("Kling 4.0 时长必须是整数秒") from None + if duration < 3 or duration > 30: + raise ValueError("Kling 4.0 时长必须在 3~30 秒之间") + if aspect_ratio not in _ASPECT_RATIOS: + raise ValueError(f"Kling 4.0 不支持宽高比:{aspect_ratio}") + + middle_frames = list(middle_frames or []) + reference_images = list(reference_images or []) + reference_videos = list(reference_videos or []) + if len(middle_frames) > 8: + raise ValueError("Kling 4.0 最多支持 8 张中间关键帧") + if len(reference_images) > 10: + raise ValueError("Kling 4.0 最多支持 10 张参考图") + if len(reference_videos) > 5: + raise ValueError("Kling 4.0 最多支持 5 段参考视频") + + body = { + "model_name": "kling-v4", + "prompt": prompt, + "duration": duration, + "mode": _RESOLUTION_MODE[resolution], + "watermark_info": {"enabled": False}, + } + if negative_prompt and str(negative_prompt).strip(): + body["negative_prompt"] = str(negative_prompt).strip() + + if mode == "text": + if first_frame or middle_frames or last_frame or reference_images or reference_videos: + raise ValueError("文生视频模式不能连接图片或视频素材") + elif mode == "keyframes": + if not first_frame: + raise ValueError("关键帧模式必须提供首帧图片") + if reference_images or reference_videos: + raise ValueError("关键帧模式不能同时使用全能参考素材") + if last_frame and not first_frame: + raise ValueError("尾帧必须与首帧一起提供") + if len([first_frame, *middle_frames, last_frame] if last_frame else [first_frame, *middle_frames]) > 10: + raise ValueError("Kling 4.0 关键帧总数不能超过 10 张") + metadata = {"first_frame": first_frame} + if middle_frames: + metadata["middle_frames"] = middle_frames + if last_frame: + metadata["last_frame"] = last_frame + body["metadata"] = metadata + else: + if first_frame or middle_frames or last_frame: + raise ValueError("全能参考模式不能同时使用关键帧") + if not reference_images and not reference_videos: + raise ValueError("全能参考模式至少需要一张参考图或一段参考视频") + if len(reference_images) + len(reference_videos) > 15: + raise ValueError("Kling 4.0 全能参考素材总数不能超过 15 个") + metadata = {} + if reference_images: + metadata["refer_images"] = reference_images + if reference_videos: + metadata["videos"] = reference_videos + if keep_original_sound: + body["keep_original_sound"] = True + body["metadata"] = metadata + + # The first frame determines the output shape. For text/Omni requests, + # "智能" is represented by the provider's adaptive ratio value. + if mode != "keyframes": + body["aspect_ratio"] = "adaptive" if aspect_ratio == "智能" else aspect_ratio + return body + + +def endpoint_for(generation_mode: str) -> tuple[str, str]: + """Return create/status paths for a canonical or displayed mode.""" + + return ENDPOINTS[canonical_generation_mode(generation_mode)] + diff --git a/clients/mj_image_client.py b/clients/mj_image_client.py new file mode 100644 index 0000000..cb542a5 --- /dev/null +++ b/clients/mj_image_client.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +"""Thin Midjourney image client on O1Key's shared async generateImage stack.""" + +from __future__ import annotations + +import asyncio +import io +import time +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Callable, List, Optional, Sequence + +from PIL import Image + +from ..utils.config import get_api_key_or_raise, get_base_url_by_route +from ..utils.http2_client import create_http_client +from ..utils.image_utils import pil_to_tensor, tensor_to_pil +from ..utils.mj_prompt import ( + MJ_CONTENT_REF_MAX, + MJ_MODEL_ID, + MJ_STYLE_REF_MAX, + MJ_SW_DEFAULT, + build_mj_prompt, +) +from ..utils.nano_banana_async import ( + parse_completed_async_image_task, + poll_async_image_task, + submit_async_image_task, + upload_images_to_temp_urls, +) + +MJ_EXPECTED_IMAGE_COUNT = 4 +MJ_REFERENCE_MAX_BYTES = 7 * 1024 * 1024 +MJ_DEFAULT_TIMEOUT_SECONDS = 180 +MJ_NODE_LABEL = "o1key MJ图片生成" + + +def build_mj_submit_body( + *, + prompt: str, + image_urls: Optional[Sequence[str]] = None, + model: str = MJ_MODEL_ID, +) -> dict[str, Any]: + """Build the paid Midjourney request body. + + API only accepts at most one URL in ``images[]``. Extra content references + must already be embedded in the prompt text. + """ + normalized_prompt = str(prompt or "").strip() + if not normalized_prompt: + raise ValueError("提示词不能为空") + if model != MJ_MODEL_ID: + raise ValueError(f"Midjourney 模型无效:{model}") + + urls = [str(url or "").strip() for url in (image_urls or ())] + urls = [url for url in urls if url] + if len(urls) > 1: + raise ValueError("Midjourney images[] 最多 1 张(多内容参考请写入 Prompt)") + if any(not url.startswith("https://") for url in urls): + raise ValueError("Midjourney 参考图必须使用临时素材 HTTPS URL") + + body: dict[str, Any] = { + "model": model, + "prompt": normalized_prompt, + } + if urls: + body["images"] = urls + return body + + +def validate_mj_reference_image(image: Image.Image, *, label: str = "参考图") -> None: + """Validate Midjourney reference limits before upload.""" + if image is None: + raise ValueError(f"{label}为空") + width, height = int(image.width), int(image.height) + if width <= 0 or height <= 0: + raise ValueError(f"{label}尺寸无效:{width}×{height}") + + buf = io.BytesIO() + image.save(buf, format="PNG") + size = len(buf.getvalue()) + if size > MJ_REFERENCE_MAX_BYTES: + raise ValueError( + f"{label}不能超过 7MB,当前为 {size / 1024 / 1024:.2f}MB" + ) + + +class MjImageClient: + """Upload content/style refs, submit one MJ task, poll, decode images.""" + + def __init__(self, *, base_url: Optional[str] = None, api_key: Optional[str] = None): + self.base_url = str(base_url or get_base_url_by_route()).rstrip("/") + self.api_key = api_key or get_api_key_or_raise("O1KEY_API_KEY") + + async def generate_async( + self, + *, + session: Any, + prompt: str, + aspect_ratio: str = "1:1", + quality: int = 2, + hd: bool = False, + image_weight: float = 1.0, + raw: bool = False, + stylize: int = 250, + chaos: int = 0, + seed: int = -1, + weird: int = 0, + tile: bool = False, + exp: int = 0, + draft: bool = False, + no_text: str = "", + style_weight: int = MJ_SW_DEFAULT, + images: Optional[Sequence[Image.Image]] = None, + style_images: Optional[Sequence[Image.Image]] = None, + timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS, + check_interrupt: Optional[Callable[[], None]] = None, + progress_callback: Optional[Callable[[float], None]] = None, + log_downloads: bool = True, + log_task_success: bool = True, + ) -> List[Image.Image]: + content_images = list(images or ()) + style_refs = list(style_images or ()) + if len(content_images) > MJ_CONTENT_REF_MAX: + raise ValueError(f"内容参考图最多 {MJ_CONTENT_REF_MAX} 张") + if len(style_refs) > MJ_STYLE_REF_MAX: + raise ValueError(f"风格参考图最多 {MJ_STYLE_REF_MAX} 张") + for index, image in enumerate(content_images, start=1): + validate_mj_reference_image(image, label=f"参考图{index}") + for index, image in enumerate(style_refs, start=1): + validate_mj_reference_image(image, label=f"风格参考图{index}") + + started = time.time() + timeout = max(30, int(timeout_seconds)) + + def _guard() -> None: + if check_interrupt: + check_interrupt() + elapsed = time.time() - started + if elapsed > timeout: + raise TimeoutError( + f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」" + ) + + _guard() + upload_batch = content_images + style_refs + uploaded_urls = await upload_images_to_temp_urls( + session=session, + base_url=self.base_url, + api_key=self.api_key, + images=upload_batch, + node_label=MJ_NODE_LABEL, + check_interrupt=_guard, + log_success=log_task_success, + ) + content_urls = list(uploaded_urls[: len(content_images)]) + style_urls = list(uploaded_urls[len(content_images) :]) + + # API images[] accepts only 1 URL; remaining content refs go into prompt. + images_field = content_urls[:1] + prompt_content_urls = content_urls[1:] + + assembled = build_mj_prompt( + prompt, + aspect_ratio=aspect_ratio, + quality=quality, + hd=hd, + image_weight=image_weight, + raw=raw, + stylize=stylize, + chaos=chaos, + seed=seed, + has_reference_image=bool(content_urls), + content_ref_urls=prompt_content_urls, + style_ref_urls=style_urls, + style_weight=style_weight, + weird=weird, + tile=tile, + exp=exp, + draft=draft, + no_text=no_text, + ) + body = build_mj_submit_body(prompt=assembled, image_urls=images_field) + + if log_task_success: + if content_urls and style_urls: + mode = "内容+风格参考" + elif content_urls: + mode = "图生图" + elif style_urls: + mode = "风格参考" + else: + mode = "文生图" + print( + f"[{MJ_NODE_LABEL}] {mode} | model={MJ_MODEL_ID} | " + f"timeout={timeout}s | content_refs={len(content_urls)} | " + f"style_refs={len(style_urls)} | prompt={assembled[:120]}" + f"{'…' if len(assembled) > 120 else ''}" + ) + + task_id = await submit_async_image_task( + session, + self.base_url, + self.api_key, + body, + MJ_NODE_LABEL, + log_body_enabled=False, + log_success=log_task_success, + ) + task_payload = await poll_async_image_task( + session, + self.base_url, + self.api_key, + task_id, + MJ_NODE_LABEL, + check_interrupt=_guard, + log_body_enabled=False, + progress_callback=progress_callback, + log_success=log_task_success, + ) + _guard() + task_payload, parsed = await parse_completed_async_image_task( + task_payload, + session, + self.base_url, + self.api_key, + task_id, + MJ_NODE_LABEL, + check_interrupt=_guard, + result_url_callback=None, + log_downloads=log_downloads, + ) + if isinstance(parsed, tuple) and len(parsed) == 2: + result_images = parsed[0] + else: + result_images = parsed + + if draft: + if len(result_images) < 1: + raise RuntimeError( + f"{MJ_NODE_LABEL} 草稿模式应至少返回 1 张图," + f"实际返回 {len(result_images)} 张(task_id={task_id})" + ) + elif len(result_images) != MJ_EXPECTED_IMAGE_COUNT: + raise RuntimeError( + f"{MJ_NODE_LABEL} 应返回 {MJ_EXPECTED_IMAGE_COUNT} 张图," + f"实际返回 {len(result_images)} 张(task_id={task_id})" + ) + + if log_task_success: + print( + f"[{MJ_NODE_LABEL}] 完成 | task_id={task_id} | " + f"生成={len(result_images)} 张 | 耗时={time.time() - started:.1f}s" + ) + return list(result_images) + + def generate_sync( + self, + *, + prompt: str, + aspect_ratio: str = "1:1", + quality: int = 2, + hd: bool = False, + image_weight: float = 1.0, + raw: bool = False, + stylize: int = 250, + chaos: int = 0, + seed: int = -1, + weird: int = 0, + tile: bool = False, + exp: int = 0, + draft: bool = False, + no_text: str = "", + style_weight: int = MJ_SW_DEFAULT, + images: Optional[Sequence[Image.Image]] = None, + style_images: Optional[Sequence[Image.Image]] = None, + timeout_seconds: int = MJ_DEFAULT_TIMEOUT_SECONDS, + check_interrupt: Optional[Callable[[], None]] = None, + progress_callback: Optional[Callable[[float], None]] = None, + ) -> List[Image.Image]: + timeout = max(30, int(timeout_seconds)) + + async def _run_async() -> List[Image.Image]: + async with create_http_client( + http2=True, + max_connections=8, + max_keepalive_connections=4, + ) as session: + return await self.generate_async( + session=session, + prompt=prompt, + aspect_ratio=aspect_ratio, + quality=quality, + hd=hd, + image_weight=image_weight, + raw=raw, + stylize=stylize, + chaos=chaos, + seed=seed, + weird=weird, + tile=tile, + exp=exp, + draft=draft, + no_text=no_text, + style_weight=style_weight, + images=images, + style_images=style_images, + timeout_seconds=timeout, + check_interrupt=check_interrupt, + progress_callback=progress_callback, + ) + + def _run() -> List[Image.Image]: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + return loop.run_until_complete(_run_async()) + finally: + loop.close() + + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(_run) + try: + return future.result(timeout=timeout + 60) + except TimeoutError as exc: + raise TimeoutError( + f"{MJ_NODE_LABEL} 超时({timeout}秒),请稍后重试或调大「超时秒数」" + ) from exc + + +def tensors_to_reference_images( + image_tensor, + *, + max_count: int = MJ_CONTENT_REF_MAX, + label: str = "参考图", +) -> List[Image.Image]: + """Convert an optional Comfy IMAGE tensor into up to ``max_count`` PIL images.""" + if image_tensor is None: + return [] + images = tensor_to_pil(image_tensor) + if not images: + return [] + if len(images) > max_count: + raise ValueError(f"{label}最多 {max_count} 张(当前输入为 {len(images)} 张)") + return list(images) + + +def pil_images_to_output_tensor(images: Sequence[Image.Image]): + return pil_to_tensor(list(images)) + + +__all__ = [ + "MJ_DEFAULT_TIMEOUT_SECONDS", + "MJ_EXPECTED_IMAGE_COUNT", + "MJ_NODE_LABEL", + "MJ_REFERENCE_MAX_BYTES", + "MjImageClient", + "build_mj_submit_body", + "pil_images_to_output_tensor", + "tensors_to_reference_images", + "validate_mj_reference_image", +] diff --git a/docs/architecture.md b/docs/architecture.md index 02b79db..949b5cd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -87,6 +87,19 @@ invalid model, duration, resolution, mode, media count, or edit clip length cannot consume an upload or paid generation request. Saved workflows retain the `O1keyGrokVideo` ID and are migrated according to [ADR 0006](decisions/0006-grok-video-api-and-workflow-migration.md). +`K3Video` keeps its released node ID and appends a `v4` DynamicCombo branch. The +branch adds a generation-mode selector with text-to-video, keyframes, and Omni +reference paths. Existing v3/v2.6/v3-omni branches retain their original +DynamicCombo option order and positional widgets. Kling 4.0 keyframe sockets +and additional Omni reference sockets are appended after the released widget +block, so saved workflows do not shift their values. `clients/kling_video_client.py` +owns the v4 capability checks and builds the proxy-compatible `model_name`, +resolution `mode`, `aspect_ratio`, and `metadata` fields; the node reuses the +existing R2 upload and interruption-aware task lifecycle. Keyframes use +`metadata.first_frame`, `metadata.middle_frames`, and `metadata.last_frame`; +Omni references use `metadata.refer_images` and `metadata.videos`. The shared +video result parser also accepts Kling 4.0's `output.media[].url` envelope. + ### Shared utilities `utils/` contains cross-provider infrastructure: @@ -150,7 +163,7 @@ The generator's local `格式` input defaults to `原始` and is visible only fo The panel displays model-route labels as `特价 / 优质 / 企业`, but serializes and submits the established internal values `畅速 / 直连 / 专线`. This label/value separation is mandatory: changing the serialized values would require a workflow migration and provider-matrix compatibility work. -The unified image generator retains its DOM panel, grouped sections, top batch controls, reference upload/canvas-picker header, empty add-reference tile, prompt-local AI writing action, inline seed randomizer, and bottom generate action. The released schema widgets remain hidden and provide the stable execution/serialization boundary. CSS presents generation/save parameters in one vertical list with left labels and right controls. Nodes 1.0 uses ComfyUI input theme tokens; inside the Nodes 2.0 widget host it uses component-node tokens. All buttons use the same neutral theme surface as the inputs. Switching renderers retains the same panel and values; it does not replace the panel with native schema widgets or append action rows. +The unified image generator retains its DOM panel for the prompt, reference upload/canvas-picker header, empty add-reference tile, prompt-local AI writing action, inline seed randomizer, mask action, and bottom generate action. LiteGraph renders the released parameter widgets natively after that panel, so each parameter keeps the host's title/value frame and renderer-specific spacing; the native seed widget is replaced by one compact DOM row to keep its randomizer beside the value. Internal prompt and manifest widgets stay hidden. The schema widget order remains unchanged and `serializeGeneratorWidgets` writes only the ordered backend fields, keeping the DOM panel and hidden helpers out of saved `widgets_values`. Nodes 1.0 uses ComfyUI input theme tokens; inside the Nodes 2.0 widget host it uses component-node tokens. All buttons use the same neutral theme surface as the inputs. Switching renderers retains the same panel, native parameter values, and capability visibility without duplicating parameter controls or appending action rows. LiteGraph includes UI widgets with `options.serialize:false` in workflow arrays, even though prompt serialization omits them. The generator serializes only its ordered backend widget values, excluding the hidden automatic seed control and the panel widget. Hidden automatic seed controls also set `widget.serialize = false` during panel creation and restoration: LiteGraph checks that widget-level flag when assigning saved values, so references, masks, batch settings, and save settings remain aligned after copy/paste or workflow loading. The seed randomizer remains inside its input row. Old hidden `control_after_generate` values after `seed` and the full-layout trailing empty panel value are removed by narrow idempotent migrations, including inside subgraphs. Node/input/output IDs and provider payloads stay unchanged. [ADR 0015](decisions/0015-image-generator-workflow-values.md) records this compatibility boundary. @@ -164,7 +177,7 @@ New reference, source, target, and mask uploads use ComfyUI's native `/upload/im Reference, source, and target thumbnails expose a bottom-right replacement action that uploads one local image through the existing non-overwriting queue and swaps only the original manifest entry after success. The original image and order survive validation or upload failure. The same thumbnails expose the browser-only image editor from their top-left action. `web/js/o1keyReferenceImageEditor.js` owns its modal, crop geometry, pointer drawing, single upper sticker layer, vector-arrow annotations, undo history, and PNG composition. Fixed aspect-ratio presets create the largest centred crop and allow repositioning; free mode also allows a new crop or corner resizing. The visual mask brush, coloured annotation brush, and arrows are flattened into the exported pixels and never become a ComfyUI `MASK` value. An arrow stores its exact source-coordinate start and end points; its tip is the pointer-release position, and its filled head scales with line width. A sticker is read from a temporary browser object URL, initially fitted and centred, and represented in source-image coordinates by centre, dimensions, rotation, and opacity. Its selection border, corner scale handles, and rotation handle are interaction chrome only. The source object URL is revoked when the editor closes and is never serialized or uploaded independently; only the flattened final pixels leave the modal. Sticker pixels are composed above the base image, then arrows and brush annotations are composed above the sticker so positional guidance stays visible. Applying an edit creates a non-overwriting PNG through the existing serialized `/upload/image` queue and atomically replaces that exact manifest entry; it does not overwrite the source file, add a workflow field, or change provider transport. If the entry is removed while the modal is open, the exported file is not attached to another position. -Optional source/target batching adds a pairing dimension without changing normal-mode task expansion. The panel calls the two roles `素材图` and `目标图`; these terms cover objects, elements, styles, materials, structures, or any other source content applied to a destination image. The legacy serialized value `一组搭配+多模特` treats all uploaded source references as one ordered group and appends exactly one target reference per pairing; because a provider request still accepts at most ten references, that mode allows nine source images plus one target image. The legacy value `全部搭配×全部模特` creates the source-major Cartesian product and sends exactly one source plus one target per task, allowing ten uploaded sources and ten uploaded targets to produce 100 pairings. The appended value `单图素材批量` creates one task per source image, sends that image as the sole provider reference, ignores the target manifest, and hides the target lane in the panel. This supports changing poses or expressions across several model images without an additional comparison reference. The complete order is prompt-major, then source/target pairing or source index, then copies for `每组生图数`; the 1000-task ceiling applies after all dimensions are expanded. Background jobs snapshot only the manifests used by the selected mode, retain reference indexes in the task plan, and resolve the exact references immediately before each paid request. Direct V3 execution uses the same task-plan helper. GPT masks are rejected while batch generation is enabled because a single edit mask cannot safely describe multiple changing reference sets. +Optional source/target batching adds a pairing dimension without changing normal-mode task expansion. The panel calls the two roles `素材图` and `目标图`; these terms cover objects, elements, styles, materials, structures, or any other source content applied to a destination image. The value `整组素材→多个目标` treats all uploaded source references as one ordered group and appends exactly one target reference per pairing; because a provider request still accepts at most ten references, that mode allows nine source images plus one target image. The value `每张素材×每张目标` creates the source-major Cartesian product and sends exactly one source plus one target per task, allowing ten uploaded sources and ten uploaded targets to produce 100 pairings. The value `每张素材单独出图` creates one task per source image, sends that image as the sole provider reference, ignores the target manifest, and hides the target lane in the panel. This supports changing poses, expressions, colours, or type treatments across several source images without an additional comparison reference. The three labels are displayed verbatim, so they must stay industry-neutral; pre-rename labels are accepted through `IMAGE_BATCH_MODE_ALIASES` in Python and `BATCH_MODE_ALIASES` in the panel, and the loader rewrites them in `widgets_values`. The complete order is prompt-major, then source/target pairing or source index, then copies for `每组生图数`; the 1000-task ceiling applies after all dimensions are expanded. Background jobs snapshot only the manifests used by the selected mode, retain reference indexes in the task plan, and resolve the exact references immediately before each paid request. Direct V3 execution uses the same task-plan helper. GPT masks are rejected while batch generation is enabled because a single edit mask cannot safely describe multiple changing reference sets. The panel exposes both manifest identity and provider-request position on every batch thumbnail. The group mode labels sources as request images `图1...图N` and every target as `图N+1` in its own request; Cartesian mode always labels the current source as `图1` and current target as `图2`; single-reference mode labels every source as `图1` because it is the sole reference in its request. Historical widget names and the first two batch-mode values remain unchanged for saved-workflow compatibility. @@ -261,7 +274,9 @@ Completed videos are atomically promoted into the configured output location wit - Standard and panel-triggered unified image runs reuse a connected blank `O1keyImageSave` before creating another result node, and never overwrite populated sibling save nodes. - Unified GPT Image requests preserve the selected background and output format; transparent backgrounds are limited to PNG and WebP. - Unified GPT Image requests omit the retired moderation parameter. -- `GPT Image 2.5 Sunburst` and `GPT Image 2.5 Flare` share GPT Image 2's resolution/aspect-ratio matrix and capability controls. Their `畅速 / 直连 / 专线` route values resolve to API IDs ending in `-sp / -sd /` no suffix, respectively. +- `GPT Image 2.5 Sunburst / Flare` and `GPT Image 2.6 Sunburst / Flare` share GPT Image 2's resolution/aspect-ratio matrix and existing raster controls. Their `畅速 / 直连 / 专线` route values resolve to API IDs ending in `-sp / -sd /` no suffix, respectively; both newer series accept `xhigh / max` quality. +- GPT Image 2.6 adds an append-only `复杂度` widget (unified index 23, after the existing layer-decomposition flag). The shared catalog validates `low / medium / high`, defaults to `high`, and omits the field for older models. Direct generation, standalone single/batch nodes, immutable background-job snapshots and client parallel fan-out carry the same selection. The control is hidden for other models without deleting its saved value. Existing node IDs, defaults and widget positions remain stable; older arrays use the appended widget's schema default. Standalone workflow migration temporarily removes a recognized complexity tail while existing tail-based rules run, then restores it; root and subgraph reloads remain idempotent. +- GPT Image 2.6 adds SVG/GIF to the gated output-format menu (not the 2.0/2.5 raster list). SVG/GIF are generation-only and reject reference images/masks. GIF requests may send `frame_count` / `frame_duration_ms`; results expand to an IMAGE frame batch while original GIF bytes are preserved for playable preview/save. SVG writes a `.svg` file and returns a rasterized IMAGE preview (cairosvg/ImageMagick/Inkscape when available; otherwise a placeholder preview). The separate provider `markup` input remains out of scope. - The GPT Image batch node pairs every populated folder through its selected pairing mode and runs the resulting tasks concurrently. It has no random-folder selector or concurrency widget; workflow migration removes both values from older saved nodes. - The Nano Banana batch node's optional colour correction never resizes the generated image, uses only reference image 1, and runs exactly once after generation and before save; its standalone counterpart and `O1keyImageGenerator` have no correction stage. - Route-label changes never alter the serialized values `畅速`, `直连`, and `专线`. diff --git a/docs/decisions/0016-kling-v4-generation-modes.md b/docs/decisions/0016-kling-v4-generation-modes.md new file mode 100644 index 0000000..6b50883 --- /dev/null +++ b/docs/decisions/0016-kling-v4-generation-modes.md @@ -0,0 +1,40 @@ +# 0016: Add Kling 4.0 modes to the released K video node + +- Status: Accepted +- Date: 2026-10-30 +- Owners: Maintainers + +## Context + +Kling 4.0 introduces separate text, keyframe, and Omni reference request +paths. The package already ships `K3Video`, and replacing it with a new node or +moving its widgets would invalidate saved workflows. + +## Decision + +Keep the `K3Video` node ID and append a `v4` DynamicCombo option. The v4 option +owns a `生成模式` selector with `文生视频`, `关键帧`, and `全能参考`. New keyframe +and reference sockets are appended after the released input block. Request body +validation lives in `clients/kling_video_client.py`; the node continues to use +the shared upload, polling, cancellation, and download lifecycle. + +## Consequences + +Existing v3, v2.6, and v3-omni workflows retain their positional widget +values. Kling 4.0 supports 3–30 seconds, 720p/1080p, up to ten keyframes, ten +reference images, and five reference videos through the new branch. Audio +voice-profile inputs and named elements remain outside this first integration +because the released node has no compatible AUDIO or element-ID sockets. + +## Alternatives considered + +- A new `Kling4Video` node would avoid a larger schema, but would split the K + video user experience and require a second registration and migration path. +- Reusing the v3 Omni payload without a mode selector would make text-only and + keyframe requests ambiguous and could send mutually exclusive media fields. + +## Validation + +`tests/test_kling_video.py` covers all three payload shapes, capability limits, +mutual exclusions, endpoint selection, and the Kling 4.0 result envelope. + diff --git a/docs/decisions/0017-remove-retired-unified-nano-models.md b/docs/decisions/0017-remove-retired-unified-nano-models.md new file mode 100644 index 0000000..dc7aa67 --- /dev/null +++ b/docs/decisions/0017-remove-retired-unified-nano-models.md @@ -0,0 +1,19 @@ +# 0017: Remove retired Nano Banana models from the unified image generator + +- Status: Accepted +- Date: 2026-11-08 + +## Context + +The unified `O1keyImageGenerator` exposed `Nano Banana 2 Lite` and `Nano Banana` even though the current supported panel set is `Nano Banana 2.1`, `Nano Banana 2`, and `Nano Banana Pro`. Removing those values from the schema without a workflow migration lets ComfyUI replace an old combo value with the first option while configuring a graph after restart. + +## Decision + +The unified catalog and panel expose only the three supported Nano Banana models. Saved unified workflows containing either retired value are migrated before widget restoration to `Nano Banana 2`; the old Lite `512` resolution is migrated to `1K`, which is the closest valid resolution in the replacement model. Standalone `NanoBanana` and `BatchNanoBananaPro` keep their released model values and route mappings. + +The panel normalizes retired values as a defensive fallback for graphs received without the frontend migration. The model label and selected value share one bordered control so the panel matches ComfyUI's native combo-widget presentation. + +## Validation + +- `tests/test_o1key_image_generator.py` verifies the unified schema model list. +- `tests/test_o1key_image_generator_frontend.mjs` verifies retired-model normalization, idempotent workflow migration, and the unified model list. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 6b84943..a5cd1ea 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -27,3 +27,5 @@ Use ADRs for decisions that constrain future changes: node ID compatibility, pac - [0013: Remove batch Nano Banana random image selection](0013-remove-batch-nano-random-image-selection.md) - [0014: Publish the current code as a new release baseline](0014-new-release-code-baseline.md) - [0015: Canonical image-generator workflow values](0015-image-generator-workflow-values.md) +- [0016: Add Kling 4.0 modes to the released K video node](0016-kling-v4-generation-modes.md) +- [0017: Remove retired Nano Banana models from the unified image generator](0017-remove-retired-unified-nano-models.md) diff --git a/docs/development.md b/docs/development.md index 4637b8a..9a3fa40 100644 --- a/docs/development.md +++ b/docs/development.md @@ -54,7 +54,7 @@ For Omni Flash, keep `O1keyOmniFlashVideo` as the sole node ID. Its `execute` va - Add or extend a Node-based test for logic that can run without a browser. - For display-only Combo aliases, set `widget.options.getOptionLabel` in an idempotent frontend extension; keep the actual option values unchanged so prompt payloads and saved workflows remain compatible. -For the image generator, preserve the existing DOM panel and its interaction hierarchy. Keep batch controls and reference upload actions at the top, AI writing inside the prompt area, the randomizer inside the seed row, and generation at the bottom. Restrict style requests to CSS: a single parameter column with left labels/right controls and current ComfyUI theme colours, without button accents. Use legacy input tokens outside the Nodes 2.0 widget host and component-node tokens inside it. Keep backend widgets hidden in both renderers, reapply visibility when renderer options are replaced, and never reorder schema widgets. Serialize only ordered backend values so hidden seed controls and the panel cannot shift later settings. Set `widget.serialize = false` on hidden seed controls before restoration; `options.serialize:false` alone only excludes API prompts. Cover panel identity/action placement, renderer visibility, model switching, upload-to-copy/paste round trips using LiteGraph's restoration loop, and root/subgraph migration with the offline frontend test; compare both renderers and themes using a disposable browser workflow. +For the image generator, preserve the existing DOM panel and its interaction hierarchy. Keep batch controls and reference upload actions at the top, AI writing inside the prompt area, the randomizer inside the seed row, and generation at the bottom. Restrict style requests to CSS: a single parameter column with left labels/right controls and current ComfyUI theme colours, without button accents. Use legacy input tokens outside the Nodes 2.0 widget host and component-node tokens inside it. Keep internal prompt/manifest widgets hidden in both renderers, while the released parameter widgets remain visible for LiteGraph's native rows; the native seed widget is replaced by one compact DOM row so its randomizer stays beside the value. Reapply capability visibility when renderer options are replaced, and do not change the relative order of schema widgets. Serialize only ordered backend values so the DOM panel and hidden internal fields cannot shift later settings. Set `widget.serialize = false` on hidden `control_after_generate` widgets before restoration; keep the backend seed value serializable even though its visual widget is replaced. `options.serialize:false` alone only excludes API prompts. Cover panel identity/action placement, native parameter visibility, model switching, upload-to-copy/paste round trips using LiteGraph's restoration loop, and root/subgraph migration with the offline frontend test; compare both renderers and themes using a disposable browser workflow. Panel-triggered image batches must be represented in ComfyUI's native task queue, not by task-state text or a cancel action inside `O1keyImageGenerator`. Keep the jobs API bridge idempotent, retain a distinct queue item and expected-output count per batch, route native single and bulk cancellation to `/o1key/image/jobs/{batch_id}/cancel`, and leave the generator action available for consecutive submissions. Preserve native queue/history records returned by ComfyUI when merging o1key records, hydrate persisted terminal summaries before returning the first history page, and keep queue clearing semantics limited to waiting batches. History persistence must remain bounded, atomic, credential-free, and synchronized with native delete/clear actions; a persistence failure must never change the result of a paid generation or successful image save. @@ -66,7 +66,9 @@ In automatic multimodal mode, render reference images, videos, and audio cards i The video generator defaults new nodes to multimodal mode. Its custom panel is created before saved widget values may be applied, so restore every visible control and material track from the configured node state in `onConfigure`; `loadedGraphNode` must repeat that restoration after graph loading. Never let panel initialization write defaults over a returning workflow's prompt, parameters, manual asset IDs, or `o1keyVideoMedia` properties. -Keep source/target batching behind the append-only `批量出图` switch. The visible panel must use the industry-neutral names `素材图`, `目标图`, `整组素材 → 多个目标`, `全匹配(素材 × 目标)`, and `单图批量(每张素材独立)`; the historical widget and first two mode values remain compatibility identifiers. Render references as a `102 × 102` horizontal card track with upload and canvas-picker actions in the track header. Every track must retain a trailing add card after its uploaded and pending thumbnails; both that card and the complete track accept external image-file drops. Stop accepted file-drop propagation before ComfyUI's canvas handler while leaving internal thumbnail sorting drags untouched. A drop handled by a nested upload card must clear the `drag` class from both that card and its parent track; the track must not retain a coloured background or outline after the file is released. Track images must use the bounded `/o1key/image/thumbnail` representation, must not decode pending local blobs, and must retain the original `/view` descriptor only for the lightbox; never substitute thumbnail bytes into manifests, prompt optimization, or provider requests. Normal mode shows one `参考图` track; paired batch modes show separate `素材图` and `目标图` tracks, while single-reference mode hides the target track. Header hints must include the current manifest count and the active participation rule. Make the complete thumbnail the pointer drag target rather than rendering a separate handle. During a drag, dim and scale the source card, label it `移动中`, highlight its track, and use a thick insertion edge plus target displacement; suppress the immediate post-drag preview click. Keep `Alt + Arrow/Home/End` ordering on the focused thumbnail as the keyboard path. With the switch off, ignore the stored target manifest and preserve the historical reference/prompt path. With it on, use `expand_image_generation_tasks` as the shared ordering authority for direct and background execution: prompts first, then pairings or source indexes, then per-pair copies. Batch manifests cap at fifty images, but provider requests remain capped at ten references: group mode therefore allows nine sources plus one target, while its target manifest may hold fifty; Cartesian and single-reference source manifests may hold fifty because each task selects one source. Snapshot only manifests used by the active mode, never serialize file paths into a workflow, and reconstruct task-specific references from validated indexes. Load large batch manifests only for active tasks, serialize reference preprocessing to bound full-resolution decode pressure while preserving request order, and release task-local images/tensors immediately after their last consumer. A failed-slot retry must flatten only that slot's exact references into a one-task normal-mode request. Keep request-position thumbnail badges derived from the same ordering. Treat ordered manifests as the source of truth for sorting and persist moves immediately. Uploaded thumbnails must reuse ComfyUI's `MediaLightbox` interaction contract; do not expose signed URLs or open a browser tab. Keep the batch summary hidden until all inputs required by the active mode are present, then show the exact task count, per-item count, prompt multiplier, and total. +Keep source/target batching behind the append-only `批量出图` switch. The visible panel must use the industry-neutral names `素材图`, `目标图`, `整组素材→多个目标`, `每张素材×每张目标`, and `每张素材单独出图`; those three strings are the serialized `批量模式` values in both the backend combo and the panel select, so renaming them requires a matching entry in `IMAGE_BATCH_MODE_ALIASES` and in the `migrateUnifiedBatchModeLabels` workflow migration. The widget name `模特图清单` remains a compatibility identifier and is never shown to users. Render references as a `102 × 102` horizontal card track. The track header carries only the lane title and the `画布取图` button; there is no header upload button, and the trailing add card is the single upload entry point (it calls `requestReferenceUpload`, which opens the hidden file input kept beside the track). Every track must retain a trailing add card after its uploaded and pending thumbnails; both that card and the complete track accept external image-file drops. Stop accepted file-drop propagation before ComfyUI's canvas handler while leaving internal thumbnail sorting drags untouched. A drop handled by a nested upload card must clear the `drag` class from both that card and its parent track; the track must not retain a coloured background or outline after the file is released. Track images must use the bounded `/o1key/image/thumbnail` representation, must not decode pending local blobs, and must retain the original `/view` descriptor only for the lightbox; never substitute thumbnail bytes into manifests, prompt optimization, or provider requests. Normal mode shows one `参考图` track; paired batch modes show separate `素材图` and `目标图` tracks, while single-reference mode hides the target track. Header hints show the manifest count only in normal mode (`N 张 · 最多 10 张`); with batching on they are hidden through the `hidden` class because the preview row below the tracks already reports the counts. Make the complete thumbnail the pointer drag target rather than rendering a separate handle. During a drag, dim and scale the source card, label it `移动中`, highlight its track, and use a thick insertion edge plus target displacement; suppress the immediate post-drag preview click. Keep `Alt + Arrow/Home/End` ordering on the focused thumbnail as the keyboard path. With the switch off, ignore the stored target manifest and preserve the historical reference/prompt path. With it on, use `expand_image_generation_tasks` as the shared ordering authority for direct and background execution: prompts first, then pairings or source indexes, then per-pair copies. Batch manifests cap at fifty images, but provider requests remain capped at ten references: group mode therefore allows nine sources plus one target, while its target manifest may hold fifty; Cartesian and single-reference source manifests may hold fifty because each task selects one source. Snapshot only manifests used by the active mode, never serialize file paths into a workflow, and reconstruct task-specific references from validated indexes. Load large batch manifests only for active tasks, serialize reference preprocessing to bound full-resolution decode pressure while preserving request order, and release task-local images/tensors immediately after their last consumer. A failed-slot retry must flatten only that slot's exact references into a one-task normal-mode request. Keep request-position thumbnail badges derived from the same ordering. Treat ordered manifests as the source of truth for sorting and persist moves immediately. Uploaded thumbnails must reuse ComfyUI's `MediaLightbox` interaction contract; do not expose signed URLs or open a browser tab. Keep the batch summary hidden until all inputs required by the active mode are present, then show the pairing detail and the total on one line, in the form `整组 3 张素材 × 4 个目标 = 4 组 · 每组 2 张 · 2 条提示词` plus a highlighted `共 16 张`. `batchGenerationPreview` is the only place that computes this total, and the row must refresh on reference/target changes, mode switches, `生图数量` changes, and prompt edits. + +The generator node's height has exactly one source of truth: `fitNode` plus the dragged-out delta `properties.o1keyPanelExtraHeight`. A `setSize()` that the engine fires on its own (node creation, workflow restore, or the Vue body re-measuring after rows appear) must never move that delta, so `onResize` only treats a resize as a drag when the node has settled **and** the press started on this node's DOM subtree. Use `document.elementFromPoint` for that check on Vue nodes: their DOM box and `canvas.ds.offset` disagree, and the geometry fallback both rejected real grip drags and accepted presses on menus. `onConfigure` has to call `resetCanvasPointerGesture()`, because a press swallowed by a menu row (重启 / 设置) never delivers its `pointerup` and the stale flag then reads every following re-layout as a drag. Bound the accepted pointer travel with `GENERATOR_DRAG_OVERSHOOT` so a stale press cannot fold a screen-wide mouse jump into the panel height. Finally, keep the `GENERATOR_FIT_TOLERANCE` dead zone in `fitNode`: `computeSize` re-derives its number from the laid-out DOM and is noisy by ~18 px, so without a tolerance the node has no fixed point and flips between two heights forever, which reads as the node growing on its own. Keep reference-image editing frontend-only and descriptor-based. The top-left thumbnail action may crop and flatten visual mask/brush/arrow marks plus one transformed upper sticker layer into a new PNG, but it must not create a `MASK` value or mutate the GPT mask widget. Keep sticker placement and arrow endpoints in source-image coordinates so preview resizing cannot alter the exported geometry; the arrow tip must remain the exact pointer-release position. Compose annotations above the sticker and never export selection handles. Revoke local sticker object URLs on close and never serialize them. Save through the shared serialized native upload queue with `overwrite=false`, replace the original descriptor only after upload succeeds, and leave the source file untouched. Keep crop math, sticker fit/hit geometry, arrow-head geometry, and filename normalization independently testable in `tests/test_o1key_reference_image_editor.mjs`; run that test together with `test_o1key_image_generator_frontend.mjs` after editor changes. @@ -74,7 +76,10 @@ When changing `O1keyImageSave`, preserve the mutually-exclusive preview rules do When adding a model to `O1keyImageGenerator`, update `utils/o1key_image_catalog.py`, the frontend model descriptions/capability switch, the job payload validator, and the model-family executor together. Preserve the existing route values even when their labels change. Provider-specific multi-image parameters must not bypass the unified scheduler: each selected output image is one concurrent provider request, and GPT Image always receives `n=1`. Keep GPT-only controls appended after the original generator widgets so old workflow arrays do not shift. -`utils/nano_banana_models.py` owns the shared Nano Banana model list and route IDs for `NanoBanana`, `BatchNanoBananaPro`, and unified image generation. `Nano Banana 2.1` is first in the model lists and the default in all three schemas, the unified execution method, and frontend fallbacks. Its `畅速 / 直连 / 专线` IDs are `gemini-nano-banana-2.1-sp / gemini-nano-banana-2.1-sd / gemini-nano-banana-2.1`; it shares Nano Banana 2's thinking, online-search, and extended-aspect-ratio support. Keep saved model selections intact, and include every new model in the migration model-recognition set without changing widget order. Verify model IDs, defaults, and parameter forwarding with the Nano Banana dynamic-input, unified image-generator, image-job, and image-generator frontend tests. +GPT Image 2.6's `复杂度` remains the last widget in both standalone schemas and at index 23 in the unified schema. Keep its catalog resolver shared by direct execution, background-job normalization/execution and the client. Older models omit `complexity` even if the hidden widget retains a value. SVG/GIF stay gated to GPT Image 2.6 via catalog helpers and frontend format menus; keep append-only `帧数` / `帧时长ms` after `复杂度`. Preserve GIF dual delivery (IMAGE frames + original bytes/path) and SVG path + raster preview. Run `test_gpt_image_nodes.py`, `test_o1key_image_generator.py`, `test_o1key_image_jobs.py`, `test_gpt_image_quality_frontend.mjs` and `test_o1key_image_generator_frontend.mjs`; preserve the nested-graph migration and complexity-value copy/paste cases. + + +`utils/nano_banana_models.py` owns the shared Nano Banana model list and route IDs for `NanoBanana` and `BatchNanoBananaPro`; the unified image generator publishes the supported first three entries from that list. `Nano Banana 2.1` is first in the model lists and the default in all three schemas, the unified execution method, and frontend fallbacks. Its `畅速 / 直连 / 专线` IDs are `gemini-nano-banana-2.1-sp / gemini-nano-banana-2.1-sd / gemini-nano-banana-2.1`; it shares Nano Banana 2's thinking, online-search, and extended-aspect-ratio support. The unified node migrates retired `Nano Banana 2 Lite` and `Nano Banana` workflow values to `Nano Banana 2` before ComfyUI restores widgets; legacy standalone nodes keep recognizing their released values. Verify model IDs, defaults, migration, and parameter forwarding with the Nano Banana dynamic-input, unified image-generator, image-job, and image-generator frontend tests. For Seedream, keep the stable workflow value `Seedream 5.0 Pro` separate from API model ID `dola-seedream-5-0-pro-260628-ep`. Treat the unified panel's default `智能` resolution as an omitted provider `size`; resolve explicit `1K / 2K` plus aspect ratio through the catalog's exact size matrix, submit one image per async task with `n=1`, pass the selected `png / jpeg` as `output_format`, and always send `watermark=false` without adding a widget. Upload ordered references through `{base_url}/v1/o1key/uploads` and submit only the returned HTTPS URL strings; never log those temporary URLs. Layer decomposition is the exception to the normal size/prompt rules: accept exactly one reference, optional prompt text, `智能 / 1K / 1.5K / 2K`, forced PNG, and no batching. Keep all returned images in `z_index` order, preserve transparent provider bytes, expose alpha as MASK in direct execution, and sanitize metadata before it reaches descriptors, history, or workflows. @@ -82,11 +87,11 @@ Keep batch-prompt behavior model-independent. A `---` line is the only prompt se Do not add a download semaphore or an independent download-concurrency limit to `O1keyImageGenerator`. Ready result URLs must download immediately; the active provider-task scheduler is the only natural bound. The shared Nano transport may retain its optional semaphore for other released nodes, but unified direct and background paths must pass no limiter. -For GPT Image, keep resolution/aspect-ratio pairs in the catalog size matrix rather than duplicating exact pixel labels in the panel. `智能` is the first and default unified resolution for every model; it must become `None` at the provider boundary so Nano Banana, GPT Image, and Seedream request builders omit `size` entirely. Explicit tiers retain their existing mappings. Keep active user controls in one persistent vertical list with labels on the left and controls on the right, but apply the model capability matrix when synchronizing the model: thinking level and online search are available to Nano Banana 2 and 2.1, resize mode is shared by Nano and GPT Image, and quality, background, API output format, plus mask are GPT Image-only. Online search defaults to `关闭`; omit `google_search` unless it is `打开`, then submit top-level `google_search: true`. The local `格式` field is visible only for Banana models; `命名规则`, `filename_prefix`, and `保存位置` are shared. Hide unsupported fields in place instead of rebuilding them so values and listeners survive model switching. Display `JPEG` but serialize and submit lowercase `jpeg`; new GPT panel selections use `png` while saved values remain intact. Reject `transparent + jpeg` before any paid request and keep JPEG out of the frontend list while transparency is active. +For GPT Image, keep resolution/aspect-ratio pairs in the catalog size matrix rather than duplicating exact pixel labels in the panel. `智能` is the first and default unified resolution for every model; it must become `None` at the provider boundary so Nano Banana, GPT Image, and Seedream request builders omit `size` entirely. Explicit tiers retain their existing mappings. New unified image-generator nodes default to `思考等级=高` and `缩放图片=智能缩放`; saved widget values remain unchanged when a workflow is restored. The unified node leaves prompt/reference interactions in its custom DOM panel but lets LiteGraph render the parameter widgets natively; do not duplicate those native controls in the panel. Apply the model capability matrix when synchronizing the model: thinking level and online search are available to Nano Banana 2 and 2.1, resize mode is shared by Nano and GPT Image, and quality, background, API output format, plus mask are GPT Image-only. Online search defaults to `关闭`; omit `google_search` unless it is `打开`, then submit top-level `google_search: true`. The local `格式` field is visible only for Banana models; `命名规则`, `filename_prefix`, and `保存位置` are shared. Hide unsupported fields in place instead of rebuilding them so values and listeners survive model switching. Display `JPEG` but serialize and submit lowercase `jpeg`; new GPT panel selections use `png` while saved values remain intact. The closed select control shows only the selected value; descriptions remain available in the expanded menu. Reject `transparent + jpeg` before any paid request and keep JPEG out of the frontend list while transparency is active. Keep prompt writing behind dedicated server routes. The unified image and video prompt actions must retain both the magic-wand icon and the visible `AI帮写` label so their purpose is understandable without hover; the image compatibility route remains `/o1key/image/prompt-optimize`, while video uses `/o1key/video/prompt-write` and a separate video-only system preset. The frontend must submit input descriptors rather than API credentials or filesystem paths. The server must enforce the input-root boundary, preserve reference order, cap the exact multimodal request body, use `gpt-5.6-sol` with high reasoning, and return only the optimized prompt. Tests must mock the upstream completion call and generate reference images at runtime; never add encoded reference fixtures or log complete data URLs. -Keep unified-generator post-processing, batch, and save widgets in their established order; migrate any removed middle widget before ComfyUI restores saved values. The retired `色彩纠正` value is removed from legacy index 13 before later values are mapped; `背景` occupies index 13; the retired `内容审查强度` value is removed from legacy index 14 after the old-layout migrations. Batch fields occupy indexes 14–16, generator save fields 17–20, `在线搜索` index 21, and Seedream `图层拆分` index 22. `migrateWorkflow.js` must first remove the retired value and fill older generator defaults, then move the connected legacy save node's four positional values into those slots, append later defaults, and clear the old save-node array idempotently. The original `IMAGE` output remains first; new provider-specific outputs must be appended. Display-only collapsing of provider-specific outputs must restore them when their mode is enabled and must never hide a connected output. Layer-decomposition background generation must save the returned descriptors once, then route the base descriptor to the output-0 save node and the remaining descriptors to its paired output-1 layer save node. The frontend, direct V3 execution path, and background job payload must use the same save settings; GPT forces local `格式=原始`. +Keep unified-generator post-processing, batch, and save widgets in their established order; migrate any removed middle widget before ComfyUI restores saved values. The retired `色彩纠正` value is removed from legacy index 13 before later values are mapped; `背景` occupies index 13; the retired `内容审查强度` value is removed from legacy index 14 after the old-layout migrations. Batch fields occupy indexes 14–16, generator save fields 17–19, `保存位置` index 20, and Seedream `图层拆分` index 21; the retired `在线搜索` value is removed right after the saved value at index 21 (a string) followed by the `图层拆分` flag. `migrateWorkflow.js` must first remove the retired value and fill older generator defaults, then move the connected legacy save node's four positional values into those slots, append later defaults, and clear the old save-node array idempotently. The original `IMAGE` output remains first; new provider-specific outputs must be appended. Display-only collapsing of provider-specific outputs must restore them when their mode is enabled and must never hide a connected output. Layer-decomposition background generation must save the returned descriptors once, then route the base descriptor to the output-0 save node and the remaining descriptors to its paired output-1 layer save node. The frontend, direct V3 execution path, and background job payload must use the same save settings; GPT forces local `格式=原始`. Keep the unified generator's canvas-image picker descriptor-based. Discover current-graph images from public execution outputs and native preview descriptors, fetch them through `/view`, and reuse the serialized `/upload/image` queue before adding them to a reference role. Do not pass `output` or `temp` descriptors to the image-job API, do not serialize picker state, and keep candidate text and filenames out of `innerHTML`. diff --git a/nodes/K3_video.py b/nodes/K3_video.py index 7562eed..a976570 100644 --- a/nodes/K3_video.py +++ b/nodes/K3_video.py @@ -25,6 +25,10 @@ import aiohttp from comfy_api.latest import io +from ..clients.kling_video_client import ( + build_kling_v4_body, + endpoint_for as kling_v4_endpoint_for, +) from ..utils.config import get_api_key_or_raise, get_base_url_by_route from ..utils.image_utils import tensor_to_pil from ..utils.r2_uploader import upload_image @@ -104,6 +108,11 @@ _REFERENCE_VIDEO_MIN_FPS = 24.0 _REFERENCE_VIDEO_MAX_FPS = 60.0 _REFERENCE_VIDEO_MIN_RATIO = 1 / 2.5 _REFERENCE_VIDEO_MAX_RATIO = 2.5 +_V4_REFERENCE_VIDEO_MAX_BYTES = 300 * 1024 * 1024 +_V4_REFERENCE_VIDEO_MIN_DURATION = 3.0 +_V4_REFERENCE_VIDEO_MAX_DURATION = 30.0 +_V4_REFERENCE_VIDEO_MIN_RATIO = 2 / 5 +_V4_REFERENCE_VIDEO_MAX_RATIO = 5 / 2 # ── 工具函数 ─────────────────────────────────────────────────────────────────── @@ -428,6 +437,30 @@ def _validate_reference_video(video_path: str, model: str) -> None: ) +def _validate_kling_v4_reference_video(video_path: str) -> float: + """Validate one Kling 4.0 Omni reference clip and return its duration.""" + ext = os.path.splitext(video_path)[1].lower() + if ext not in (".mp4", ".mov"): + raise RuntimeError(f"Kling 4.0 参考视频仅支持 MP4/MOV,当前为 {ext or '无扩展名'}。") + size = os.path.getsize(video_path) + if size > _V4_REFERENCE_VIDEO_MAX_BYTES: + raise RuntimeError( + f"Kling 4.0 参考视频不能超过 300MB,当前为 {size / 1024 / 1024:.1f}MB。" + ) + meta = _probe_video_with_ffprobe(video_path) or _probe_video_with_cv2(video_path) + if not meta or not meta.get("width") or not meta.get("height") or not meta.get("duration"): + raise RuntimeError("无法读取 Kling 4.0 参考视频的尺寸和时长。") + duration = float(meta["duration"]) + if not _V4_REFERENCE_VIDEO_MIN_DURATION <= duration <= _V4_REFERENCE_VIDEO_MAX_DURATION: + raise RuntimeError( + f"Kling 4.0 单段参考视频时长需在 3~30 秒之间,当前为 {duration:.2f} 秒。" + ) + ratio = float(meta["width"]) / float(meta["height"]) + if not _V4_REFERENCE_VIDEO_MIN_RATIO <= ratio <= _V4_REFERENCE_VIDEO_MAX_RATIO: + raise RuntimeError("Kling 4.0 参考视频宽高比需在 2:5~5:2 之间。") + return duration + + def _collect_shots(分镜模式: dict, 时长: int) -> list: """从 DynamicCombo 的 dict 收集分镜参数并校验。 @@ -605,6 +638,38 @@ def _v3_omni_subs(): ] +def _v4_subs(): + """Kling 4.0 generation mode and its capability-limited parameters.""" + return [ + io.Combo.Input( + "生成模式", + options=["文生视频", "关键帧", "全能参考"], + default="文生视频", + tooltip="文生视频:只使用提示词;关键帧:首帧可加中间帧和尾帧;全能参考:使用参考图或参考视频。", + ), + io.Int.Input( + "时长", + default=5, + min=3, + max=30, + display_mode=io.NumberDisplay.slider, + tooltip="Kling 4.0 支持 3~30 秒。", + ), + io.Combo.Input( + "模式", + options=["720p", "1080p"], + default="720p", + tooltip="Kling 4.0 支持 720p 和 1080p。", + ), + io.Combo.Input( + "宽高比", + options=["智能", "16:9", "9:16", "1:1", "21:9"], + default="智能", + tooltip="关键帧模式跟随首帧比例;文生和全能参考支持智能、16:9、9:16、1:1、21:9。", + ), + ] + + def _build_model_input(): """构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。 @@ -637,8 +702,11 @@ def _build_model_input(): io.DynamicCombo.Option("v3-omni", _v3_omni_subs()), io.DynamicCombo.Option("v2-6", _v26_subs()), io.DynamicCombo.Option("v3", _v3_subs()), + # Append the new branch so existing DynamicCombo option order and + # saved v3/v2.6 workflows remain unchanged. + io.DynamicCombo.Option("v4", _v4_subs()), ], - tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理", + tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理;v4: 文生、关键帧、全能参考,3-30s。", ) @@ -706,6 +774,28 @@ class K3Video(io.ComfyNode): tooltip="seed 仅控制节点是否重新运行,结果本身不可复现。"), # 负向提示词置于最下方(全局生效,两种模式都可用) io.String.Input("负向提示词", multiline=True, default=""), + # Kling 4.0 sockets are appended after the released layout so + # positional widgets in existing K3Video workflows do not move. + *[ + io.Image.Input(f"中间帧{i}", optional=True, + tooltip="Kling 4.0 关键帧模式使用;按连接顺序插入首帧与尾帧之间。") + for i in range(1, 9) + ], + *[ + io.Image.Input(f"参考图{i}", optional=True, + tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。") + for i in range(6, 11) + ], + io.Image.Input( + "参考图1", + optional=True, + tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。", + ), + *[ + io.Video.Input(f"参考视频{i}", optional=True, + tooltip="Kling 4.0 全能参考模式使用;最多 5 段参考视频。") + for i in range(2, 6) + ], ], outputs=[io.Video.Output(display_name="视频")], accept_all_inputs=True, @@ -730,6 +820,49 @@ class K3Video(io.ComfyNode): "Content-Type": "application/json", } shots = _collect_shots(分镜模式, 时长) + if 模型代号 == "v4": + generation_mode = 模型.get("生成模式", "文生视频") + middle_frames = [ + _kwargs.get(f"中间帧{i}") + for i in range(1, 9) + if _kwargs.get(f"中间帧{i}") is not None + ] + reference_images = [ + image for image in ( + _kwargs.get("参考图1"), + 参考图2, 参考图3, 参考图4, 参考图5, + *[_kwargs.get(f"参考图{i}") for i in range(6, 11)], + ) if image is not None + ] + reference_videos = [ + video for video in ( + 参考视频, + *[_kwargs.get(f"参考视频{i}") for i in range(2, 6)], + ) if video is not None + ] + v4_prompt = ( + (分镜模式.get("正向提示词") or "") + if not shots else shots[0]["prompt"] + ) + save_path = await cls._build_v4( + base_url, + headers, + generation_mode, + v4_prompt, + 负向提示词, + 时长, + 模式, + 宽高比, + 起始帧, + middle_frames, + 尾帧, + reference_images, + reference_videos, + shots, + ) + if _FOLDER_PATHS_OK: + return io.NodeOutput(InputImpl.VideoFromFile(save_path)) + return io.NodeOutput(save_path) # 正向提示词仅在「禁用」(单段)时存在;选故事板后腾讯忽略主 Prompt,故隐藏。 提示词 = (分镜模式.get("正向提示词") or "") if not shots else "" @@ -1028,6 +1161,89 @@ class K3Video(io.ComfyNode): ) # ── 标准 image2video 端点(v3 / v2-6)──────────────────────── + @classmethod + async def _build_v4( + cls, + base_url, + headers, + generation_mode, + prompt, + negative_prompt, + duration, + resolution, + aspect_ratio, + first_frame, + middle_frame_inputs, + last_frame, + reference_image_inputs, + reference_video_inputs, + shots, + ): + """Build and run one Kling 4.0 text/keyframe/Omni task.""" + from ..utils.r2_uploader import upload_video + + async def upload_frame(image, label): + if image is None: + return None + print(f"[Kling 4.0] uploading {label}...") + return await upload_image(_prepare_image_for_upload(image), base_url=base_url) + + validated_video_paths = [] + reference_video_seconds = 0.0 + for video in reference_video_inputs: + video_path = _resolve_reference_video_path(video) + reference_video_seconds += _validate_kling_v4_reference_video(video_path) + validated_video_paths.append(video_path) + if reference_video_seconds > _V4_REFERENCE_VIDEO_MAX_DURATION: + raise RuntimeError("Kling 4.0 参考视频总时长不能超过 30 秒。") + + first_url = await upload_frame(first_frame, "first frame") + middle_urls = [ + await upload_frame(image, f"middle frame {index}") + for index, image in enumerate(middle_frame_inputs, start=1) + ] + last_url = await upload_frame(last_frame, "last frame") + + reference_image_urls = [ + await upload_frame(image, f"reference image {index}") + for index, image in enumerate(reference_image_inputs, start=1) + ] + reference_video_urls = [] + for index, video_path in enumerate(validated_video_paths, start=1): + print(f"[Kling 4.0] uploading reference video {index}...") + reference_video_urls.append(await upload_video(video_path, base_url=base_url)) + + body = build_kling_v4_body( + generation_mode=generation_mode, + prompt=prompt, + negative_prompt=negative_prompt, + duration=duration, + resolution=resolution, + aspect_ratio=aspect_ratio, + first_frame=first_url, + middle_frames=middle_urls, + last_frame=last_url, + reference_images=reference_image_urls, + reference_videos=reference_video_urls, + ) + if shots: + body["multi_shot"] = True + body["shot_type"] = "customize" + body["multi_prompt"] = [ + {"index": shot["index"], "prompt": shot["prompt"], "duration": shot["duration"]} + for shot in shots + ] + + create_path, status_path = kling_v4_endpoint_for(generation_mode) + return await _run_video_task( + base_url, + headers, + body, + create_path, + status_path, + f"Kling 4.0 {generation_mode} submit: ", + ) + @classmethod async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None): """标准图生视频接口:POST /kling/v1/videos/image2video diff --git a/nodes/__init__.py b/nodes/__init__.py index 1161e8a..f93a07a 100644 --- a/nodes/__init__.py +++ b/nodes/__init__.py @@ -28,6 +28,7 @@ from .grok_video import O1keyGrokVideo, O1keyGrokVideoEdit from .K3_video import K3Video from .K3_motion_control import K3MotionControl from .save_image_format import SaveImageFormat +from .save_gif import O1keySaveGIF from .save_psd import O1keySavePSD from .remove_bg import O1keyRemoveBackground from .grid_splitter import O1keyGridSplitter @@ -40,5 +41,6 @@ from .seedance_autopass_batch import SeedanceAutoPassBatch from .o1key_image_generator import O1keyImageGenerator, O1keyImageSave from .o1key_video_generator import O1keyVideoGenerator, O1keyVideoResult from .omni_flash_video import O1keyOmniFlashVideo +from .mj_image import O1keyMJImage -__all__ = ['NanoBanana', 'BatchNanoBananaPro', 'GoogleGemini', 'LoadFile', 'LoadImagesFromFolder', 'ImageStitchPro', 'BatchCleanMetadata', 'VideoPreview', 'GoogleVeo', 'Google31Video', 'MiniMaxH3Video', 'FluxImageEdit', 'UniversalLLMChat', 'BatchImagesO1key', 'SeedanceMultiModal', 'StreamPreview', 'DoubaoImage', 'O1keyGPTImage', 'O1keyGPTImageBatch', 'O1keyGrokImage', 'O1keyGrokVideo', 'O1keyGrokVideoEdit', 'K3Video', 'K3MotionControl', 'SaveImageFormat', 'O1keySavePSD', 'O1keyRemoveBackground', 'O1keyGridSplitter', 'O1keyAutoRedCast', 'O1keyPromptMultiFunction', 'O1keyVideoTrim', 'SeedanceElementCreate', 'SeedanceAutoPass', 'SeedanceAutoPassBatch', 'O1keyImageGenerator', 'O1keyImageSave', 'O1keyVideoGenerator', 'O1keyVideoResult', 'O1keyOmniFlashVideo'] +__all__ = ['NanoBanana', 'BatchNanoBananaPro', 'GoogleGemini', 'LoadFile', 'LoadImagesFromFolder', 'ImageStitchPro', 'BatchCleanMetadata', 'VideoPreview', 'GoogleVeo', 'Google31Video', 'MiniMaxH3Video', 'FluxImageEdit', 'UniversalLLMChat', 'BatchImagesO1key', 'SeedanceMultiModal', 'StreamPreview', 'DoubaoImage', 'O1keyGPTImage', 'O1keyGPTImageBatch', 'O1keyGrokImage', 'O1keyGrokVideo', 'O1keyGrokVideoEdit', 'K3Video', 'K3MotionControl', 'SaveImageFormat', 'O1keySaveGIF', 'O1keySavePSD', 'O1keyRemoveBackground', 'O1keyGridSplitter', 'O1keyAutoRedCast', 'O1keyPromptMultiFunction', 'O1keyVideoTrim', 'SeedanceElementCreate', 'SeedanceAutoPass', 'SeedanceAutoPassBatch', 'O1keyImageGenerator', 'O1keyImageSave', 'O1keyVideoGenerator', 'O1keyVideoResult', 'O1keyOmniFlashVideo', 'O1keyMJImage'] diff --git a/nodes/gpt_image.py b/nodes/gpt_image.py index f005de5..d232f58 100644 --- a/nodes/gpt_image.py +++ b/nodes/gpt_image.py @@ -1,6 +1,6 @@ """ o1key GPT Image 节点 -支持 GPT Image 2 / 2.5 系列的文生图、图生图和带蒙版图像编辑 +支持 GPT Image 2 / 2.5 / 2.6 系列的文生图、图生图和带蒙版图像编辑 """ import os @@ -20,12 +20,29 @@ from ..utils.image_utils import parse_batch_prompts, pil_to_tensor, tensor_to_pi from ..utils.config import get_base_url_by_route from ..utils.o1key_image_catalog import ( GPT_IMAGE_BACKGROUND_OPTIONS, + GPT_IMAGE_COMPLEXITY_OPTIONS, + GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS, + GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + GPT_IMAGE_GIF_FRAME_COUNT_MAX, + GPT_IMAGE_GIF_FRAME_COUNT_MIN, + GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + GPT_IMAGE_GIF_FRAME_DURATION_MAX, + GPT_IMAGE_GIF_FRAME_DURATION_MIN, + resolve_gpt_image_complexity, + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + resolve_gpt_image_output_format, + validate_gpt_image_vector_output, GPT_IMAGE_EXACT_SIZE_OPTIONS, - GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, GPT_IMAGE_25_QUALITY_OPTIONS, resolve_gpt_image_quality, resolve_gpt_image_size, ) +from ..utils.gpt_image_media import ( + animation_bytes_from_images, + svg_bytes_from_image, + write_bytes_atomic, +) from ..utils.file_utils import ( ImageInfo, generate_timestamp_filename, @@ -142,13 +159,17 @@ class O1keyGPTImage(io.ComfyNode): io.Combo.Input( "模型", options=GPT_IMAGE_MODEL_OPTIONS, - default="gpt-image-2.5-sunburst", + default="gpt-image-2.6-sunburst", ), io.Combo.Input( "模型线路", options=GPT_IMAGE_ROUTE_OPTIONS, default="畅速", ), + io.Combo.Input( + "复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高", + tooltip="仅 GPT Image 2.6 生效:低 / 中 / 高;越高规划越充分、耗时越长。", + ), io.Combo.Input( "分辨率", options=GPT_IMAGE_EXACT_SIZE_OPTIONS, @@ -168,13 +189,13 @@ class O1keyGPTImage(io.ComfyNode): "质量", options=GPT_IMAGE_25_QUALITY_OPTIONS, default="自动", - tooltip="GPT Image 2 支持高/中/低/自动;GPT Image 2.5 另支持超高=xhigh、最高=max。", + tooltip="GPT Image 2 支持高/中/低/自动;GPT Image 2.5 / 2.6 另支持超高=xhigh、最高=max。", ), io.Combo.Input( "输出格式", - options=["png", "jpeg", "webp"], + options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS, default="png", - tooltip="Generated image output format", + tooltip="2.6 另支持 svg / gif;svg/gif 仅纯文生图可用。", ), io.Combo.Input( "背景", @@ -204,8 +225,29 @@ class O1keyGPTImage(io.ComfyNode): control_after_generate=io.ControlAfterGenerate.randomize, tooltip="Random seed (0 = not specified)", ), + io.Int.Input( + "帧数", + default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_COUNT_MIN, + max=GPT_IMAGE_GIF_FRAME_COUNT_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="仅输出格式为 gif 时生效:2–64,默认 9。", + ), + io.Int.Input( + "帧时长ms", + default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_DURATION_MIN, + max=GPT_IMAGE_GIF_FRAME_DURATION_MAX, + step=10, + display_mode=io.NumberDisplay.number, + tooltip="仅输出格式为 gif 时生效:20–2000ms,默认 200,按 10ms 取整。", + ), + ], + outputs=[ + io.Image.Output(display_name="IMAGE"), + io.String.Output("FILE", display_name="文件路径"), ], - outputs=[io.Image.Output(display_name="IMAGE")], # 兼容 Autogrow 改造前保存的参考图1~参考图9端口。 accept_all_inputs=True, ) @@ -214,7 +256,7 @@ class O1keyGPTImage(io.ComfyNode): def execute( cls, prompt: str, - 模型: str = "gpt-image-2.5-sunburst", + 模型: str = "gpt-image-2.6-sunburst", 模型线路: str = "畅速", 分辨率: str = "智能", 质量: str = "自动", @@ -224,6 +266,9 @@ class O1keyGPTImage(io.ComfyNode): 遮罩=None, 缩放图片: str = "智能缩放", 背景: str = "auto", + 复杂度: str = "高", + 帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + 帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, **kwargs, ) -> io.NodeOutput: result = cls.generate( @@ -238,15 +283,21 @@ class O1keyGPTImage(io.ComfyNode): 遮罩=遮罩, 缩放图片=缩放图片, 背景=背景, + 复杂度=复杂度, + 帧数=帧数, + 帧时长ms=帧时长ms, **kwargs, ) - return io.NodeOutput(*result) + tensor, file_path, preview = result + if preview is not None: + return io.NodeOutput(tensor, file_path, ui=preview) + return io.NodeOutput(tensor, file_path) @classmethod def generate( cls, prompt: str, - 模型: str = "gpt-image-2.5-sunburst", + 模型: str = "gpt-image-2.6-sunburst", 模型线路: str = "畅速", 分辨率: str = "智能", 质量: str = "自动", @@ -256,6 +307,9 @@ class O1keyGPTImage(io.ComfyNode): 遮罩=None, 缩放图片: str = "智能缩放", 背景: str = "auto", + 复杂度: str = "高", + 帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + 帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, **kwargs, ): """ @@ -285,12 +339,19 @@ class O1keyGPTImage(io.ComfyNode): raise ValueError("提供了遮罩但未提供图片,请同时提供图片和遮罩") if 缩放图片 not in {"不缩放", "智能缩放"}: raise ValueError("缩放图片参数无效") - if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: - raise ValueError("GPT Image 输出格式无效") if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: raise ValueError("GPT Image 背景参数无效") - if 背景 == "transparent" and 输出格式 == "jpeg": + 输出格式 = resolve_gpt_image_output_format(模型, 输出格式) + if 背景 == "transparent" and 输出格式 not in {"png", "webp"}: raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") + validate_gpt_image_vector_output( + 模型, + 输出格式, + has_images=bool(图片), + has_mask=遮罩 is not None, + ) + frame_count = resolve_gpt_image_frame_count(输出格式, 帧数) + frame_duration_ms = resolve_gpt_image_frame_duration_ms(输出格式, 帧时长ms) # ── 2. 解析分辨率显示值 → API 参数值 ────────────────────────────────── size = _resolve_async_size(分辨率) @@ -300,6 +361,7 @@ class O1keyGPTImage(io.ComfyNode): # ── 2c. 解析质量显示值 → API 参数值 ─────────────────────────────────── quality = resolve_gpt_image_quality(模型, 质量) + complexity = resolve_gpt_image_complexity(模型, 复杂度) # ── 3. 创建客户端 ───────────────────────────────────────────────────── try: @@ -348,6 +410,9 @@ class O1keyGPTImage(io.ComfyNode): mask_tensor=遮罩, output_format=输出格式, background=背景, + **({"complexity": complexity} if complexity is not None else {}), + **({"frame_count": frame_count} if frame_count is not None else {}), + **({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}), progress_callback=_make_node_progress_callback(progress_bar, idx, total), special_price_parallel=True, task_submitted_callback=_submitted, @@ -381,6 +446,9 @@ class O1keyGPTImage(io.ComfyNode): mask_tensor=遮罩, output_format=输出格式, background=背景, + **({"complexity": complexity} if complexity is not None else {}), + **({"frame_count": frame_count} if frame_count is not None else {}), + **({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}), progress_callback=_make_node_progress_callback(progress_bar, 1, 1), special_price_parallel=True, task_submitted_callback=_submitted, @@ -402,6 +470,37 @@ class O1keyGPTImage(io.ComfyNode): raise RuntimeError("所有提示词均生成失败,无可用图像输出") # ── 7. PIL → tensor ─────────────────────────────────────────────── + file_path = "" + preview = None + anim = animation_bytes_from_images(all_pil_images) + svg = svg_bytes_from_image(all_pil_images[0]) if all_pil_images else None + if _FOLDER_PATHS_AVAILABLE and (anim is not None or svg is not None): + media_root = ( + folder_paths.get_temp_directory() + if anim is not None + else folder_paths.get_output_directory() + ) + os.makedirs(media_root, exist_ok=True) + target = generate_timestamp_filename( + output_folder=media_root, + prefix="gpt_image", + extension=".gif" if anim is not None else ".svg", + ) + if anim is not None: + # Durable copy lives in output via the dedicated「保存 GIF」node. + # Temp here only backs the「文件路径」output — no in-node preview + # (user request: gpt image itself should not preview GIFs). + write_bytes_atomic(target, anim) + file_path = target + preview = None + print( + f"[o1key GPT Image] GIF 已写入 temp(持久保存请接「保存 GIF」): {file_path}" + ) + else: + write_bytes_atomic(target, svg) + file_path = target + print(f"[o1key GPT Image] SVG 已保存: {file_path}") + output_tensor = GptImageClient._pil_list_to_tensor(all_pil_images) # ── 8. 完成日志 ─────────────────────────────────────────────────── @@ -412,7 +511,7 @@ class O1keyGPTImage(io.ComfyNode): f"{output_tensor.shape[2]}×{output_tensor.shape[1]}" ) - return (output_tensor,) + return (output_tensor, file_path, preview) finally: cls._print_balance(client) diff --git a/nodes/gpt_image_batch.py b/nodes/gpt_image_batch.py index 5af64b7..13ef101 100644 --- a/nodes/gpt_image_batch.py +++ b/nodes/gpt_image_batch.py @@ -29,8 +29,22 @@ from ..utils.file_utils import ( from ..utils.image_utils import parse_batch_prompts, pil_to_tensor, tensor_to_pil from ..utils.o1key_image_catalog import ( GPT_IMAGE_BACKGROUND_OPTIONS, + GPT_IMAGE_COMPLEXITY_OPTIONS, + GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS, + GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + GPT_IMAGE_GIF_FRAME_COUNT_MAX, + GPT_IMAGE_GIF_FRAME_COUNT_MIN, + GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + GPT_IMAGE_GIF_FRAME_DURATION_MAX, + GPT_IMAGE_GIF_FRAME_DURATION_MIN, + resolve_gpt_image_complexity, + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + resolve_gpt_image_output_format, + validate_gpt_image_vector_output, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, ) +from ..utils.gpt_image_media import animation_bytes_from_images, svg_bytes_from_image, write_bytes_atomic try: from comfy.model_management import InterruptProcessingException @@ -134,14 +148,18 @@ class O1keyGPTImageBatch(io.ComfyNode): tooltip="可用独占一行的 --- 分隔多条提示词。"), io.Combo.Input( "模型", options=GPT_IMAGE_MODEL_OPTIONS, - default="gpt-image-2.5-sunburst", + default="gpt-image-2.6-sunburst", ), io.Combo.Input("模型线路", options=GPT_IMAGE_ROUTE_OPTIONS, default="畅速"), + io.Combo.Input( + "复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高", + tooltip="仅 GPT Image 2.6 生效:低 / 中 / 高;越高规划越充分、耗时越长。", + ), io.Combo.Input("分辨率", options=_RESOLUTION_OPTIONS, default="智能"), io.Int.Input("生图数量", default=1, min=1, max=8, step=1), io.Combo.Input( "质量", options=GPT_IMAGE_25_QUALITY_OPTIONS, default="自动", - tooltip="GPT Image 2.5 另支持超高=xhigh、最高=max。", + tooltip="GPT Image 2.5 / 2.6 另支持超高=xhigh、最高=max。", ), io.DynamicCombo.Input( "图片路径数量", @@ -151,7 +169,7 @@ class O1keyGPTImageBatch(io.ComfyNode): io.Mask.Input("遮罩", optional=True, tooltip="应用到每个任务的第一张参考图。"), references, - io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP"], + io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP", "SVG", "GIF"], default="原始"), io.Combo.Input( "背景", @@ -173,6 +191,24 @@ class O1keyGPTImageBatch(io.ComfyNode): "seed", default=0, min=0, max=2**31 - 1, step=1, control_after_generate=io.ControlAfterGenerate.randomize, ), + io.Int.Input( + "帧数", + default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_COUNT_MIN, + max=GPT_IMAGE_GIF_FRAME_COUNT_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="仅图片输出格式为 GIF 时生效。", + ), + io.Int.Input( + "帧时长ms", + default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_DURATION_MIN, + max=GPT_IMAGE_GIF_FRAME_DURATION_MAX, + step=10, + display_mode=io.NumberDisplay.number, + tooltip="仅图片输出格式为 GIF 时生效;按 10ms 取整。", + ), ], outputs=[io.Image.Output(display_name="输出图像")], accept_all_inputs=True, @@ -238,13 +274,33 @@ class O1keyGPTImageBatch(io.ComfyNode): naming_rule: str, task_index: int, base_filename: Optional[str], ) -> List[str]: saved = [] + anim = animation_bytes_from_images(images) + svg = svg_bytes_from_image(images[0]) if images else None + if anim is not None or svg is not None: + ext = ".gif" if anim is not None else ".svg" + data = anim if anim is not None else svg + if naming_rule == "自然数字": + stem = str(task_index + 1) + else: + stem = base_filename or f"task_{task_index + 1}" + path = os.path.join(folder, f"{stem}{ext}") + collision = 1 + while os.path.exists(path): + path = os.path.join(folder, f"{stem}+{collision}{ext}") + collision += 1 + write_bytes_atomic(path, data) + saved.append(path) + if svg is not None: + # also save raster preview frames/image next to svg + pass + return saved for image_index, image in enumerate(images, 1): if image_format == "原始": fmt = str(getattr(image, "format", None) or "PNG").upper() fmt = "JPEG" if fmt in ("JPG", "JPEG") else "WEBP" if fmt == "WEBP" else "PNG" else: fmt = image_format.upper() - ext = {"JPEG": ".jpg", "WEBP": ".webp"}.get(fmt, ".png") + ext = {"JPEG": ".jpg", "WEBP": ".webp", "GIF": ".gif", "SVG": ".svg"}.get(fmt, ".png") if naming_rule == "自然数字": stem = str(task_index + 1) if image_index > 1: @@ -284,7 +340,8 @@ class O1keyGPTImageBatch(io.ComfyNode): cls, client, pair, task_prompt, task_index, total_tasks, model, quality, size, image_count, seed, mask, output_format, background, resize_mode, - folder, naming_rule, save_lock, progress_callback, + folder, naming_rule, save_lock, progress_callback, complexity=None, + frame_count=None, frame_duration_ms=None, ) -> dict: try: task_started = time.time() @@ -294,6 +351,7 @@ class O1keyGPTImageBatch(io.ComfyNode): image_tensor=[pil_to_tensor([item.image]) for item in pair], mask_tensor=mask, output_format=output_format, background=background, + **({"complexity": complexity} if complexity is not None else {}), progress_callback=progress_callback, special_price_parallel=True, log_downloads=True, @@ -328,7 +386,8 @@ class O1keyGPTImageBatch(io.ComfyNode): async def _process_async( cls, client, task_defs, model, quality, size, image_count, seed, mask, output_format, background, resize_mode, - folder, naming_rule, pbar, + folder, naming_rule, pbar, complexity=None, + frame_count=None, frame_duration_ms=None, ) -> List[dict]: total = len(task_defs) progress_values = [0] * total @@ -338,7 +397,8 @@ class O1keyGPTImageBatch(io.ComfyNode): client, pair, prompt, index, total, model, quality, size, image_count, seed, mask, output_format, background, resize_mode, folder, naming_rule, - save_lock, cls._progress_callback(progress_values, index, pbar), + save_lock, cls._progress_callback(progress_values, index, pbar), complexity, + frame_count, frame_duration_ms, )) for index, pair, prompt in task_defs ] @@ -357,10 +417,11 @@ class O1keyGPTImageBatch(io.ComfyNode): @classmethod def execute( - cls, prompt, 模型="gpt-image-2.5-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1, + cls, prompt, 模型="gpt-image-2.6-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1, 质量="自动", 图片路径数量=None, 遮罩=None, seed=0, 图片输出格式="原始", 图片保存命名规则="和原始图片名保持一致", - 图片保存路径="", 缩放图片="智能缩放", 背景="auto", **kwargs, + 图片保存路径="", 缩放图片="智能缩放", 背景="auto", 复杂度="高", + 帧数=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, 帧时长ms=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, **kwargs, ) -> io.NodeOutput: if not prompt or not str(prompt).strip(): raise ValueError("提示词不能为空") @@ -369,6 +430,7 @@ class O1keyGPTImageBatch(io.ComfyNode): if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: raise ValueError("GPT Image 背景参数无效") + complexity = resolve_gpt_image_complexity(模型, 复杂度) actual_model = resolve_gpt_image_model(模型, 模型线路) # 兼容旧节点通过命名参数调用时使用的字段名。 @@ -419,11 +481,22 @@ class O1keyGPTImageBatch(io.ComfyNode): folder = cls._output_folder(图片保存路径) quality = resolve_gpt_image_quality(模型, 质量) - output_format = {"原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp"}.get(图片输出格式, "png") - if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: - raise ValueError("GPT Image 输出格式无效") - if 背景 == "transparent" and output_format == "jpeg": + output_format = { + "原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp", + "SVG": "svg", "GIF": "gif", + "jpeg": "jpeg", "png": "png", "webp": "webp", "svg": "svg", "gif": "gif", + }.get(图片输出格式, "png") + output_format = resolve_gpt_image_output_format(模型, output_format) + if 背景 == "transparent" and output_format not in {"png", "webp"}: raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") + frame_count = resolve_gpt_image_frame_count(output_format, 帧数) + frame_duration_ms = resolve_gpt_image_frame_duration_ms(output_format, 帧时长ms) + validate_gpt_image_vector_output( + 模型, + output_format, + has_images=True, + has_mask=遮罩 is not None, + ) client = GptImageClient() client.base_url = get_base_url_by_route() client.response_log_enabled = False @@ -443,7 +516,8 @@ class O1keyGPTImageBatch(io.ComfyNode): client, task_defs, actual_model, quality, _resolve_size(分辨率), 生图数量, seed, 遮罩, output_format, 背景, 缩放图片, folder, - 图片保存命名规则, pbar, + 图片保存命名规则, pbar, complexity, + frame_count, frame_duration_ms, ) return loop.run_until_complete(client._run_with_interrupt(coro)) finally: diff --git a/nodes/mj_image.py b/nodes/mj_image.py new file mode 100644 index 0000000..6de8728 --- /dev/null +++ b/nodes/mj_image.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +"""o1key MJ图片生成节点(Midjourney v8.2)。""" + +from __future__ import annotations + +import time +from typing import List + +from comfy_api.latest import io + +from ..clients.mj_image_client import ( + MJ_DEFAULT_TIMEOUT_SECONDS, + MJ_NODE_LABEL, + MjImageClient, + pil_images_to_output_tensor, + tensors_to_reference_images, +) +from ..utils.mj_prompt import ( + MJ_ASPECT_RATIO_OPTIONS, + MJ_CHAOS_DEFAULT, + MJ_CHAOS_MAX, + MJ_CHAOS_MIN, + MJ_CONTENT_REF_MAX, + MJ_EXP_DEFAULT, + MJ_EXP_MAX, + MJ_EXP_MIN, + MJ_IW_DEFAULT, + MJ_IW_MAX, + MJ_IW_MIN, + MJ_QUALITY_DEFAULT, + MJ_QUALITY_MAX, + MJ_QUALITY_MIN, + MJ_STYLE_REF_MAX, + MJ_STYLIZE_DEFAULT, + MJ_STYLIZE_MAX, + MJ_STYLIZE_MIN, + MJ_SW_DEFAULT, + MJ_SW_MAX, + MJ_SW_MIN, + MJ_WEIRD_DEFAULT, + MJ_WEIRD_MAX, + MJ_WEIRD_MIN, +) + +try: + from comfy.model_management import InterruptProcessingException, processing_interrupted + + _INTERRUPT_AVAILABLE = True +except ImportError: + _INTERRUPT_AVAILABLE = False + + def processing_interrupted(): + return False + + InterruptProcessingException = RuntimeError + +try: + from comfy.utils import ProgressBar + + _PROGRESS_BAR_AVAILABLE = True +except ImportError: + _PROGRESS_BAR_AVAILABLE = False + + +def _check_interrupt() -> None: + if _INTERRUPT_AVAILABLE and processing_interrupted(): + raise InterruptProcessingException() + + +def _collect_autogrow_inputs(value) -> list: + """收集已连接的 Autogrow 输入,并兼容单个旧值。""" + if value is None: + return [] + if isinstance(value, dict): + return [item for item in value.values() if item is not None] + return [value] + + +def _collect_reference_images( + *, + group_value, + kwargs: dict, + max_count: int, + label: str, + numbered_prefix: str, + legacy_key: str, +) -> List: + """从 Autogrow 组收集参考图;为空时兼容编号口与旧单口。""" + tensors = _collect_autogrow_inputs(group_value) + if not tensors: + tensors = [ + kwargs[f"{numbered_prefix}{i}"] + for i in range(1, max_count + 1) + if kwargs.get(f"{numbered_prefix}{i}") is not None + ] + if not tensors and kwargs.get(legacy_key) is not None: + tensors = [kwargs.get(legacy_key)] + + images: List = [] + for tensor in tensors: + part = tensors_to_reference_images( + tensor, + max_count=max_count, + label=label, + ) + images.extend(part) + if len(images) > max_count: + raise ValueError( + f"{label}最多 {max_count} 张(当前输入为 {len(images)} 张)" + ) + return images + + +class O1keyMJImage(io.ComfyNode): + """独立 Midjourney 生图节点;非草稿固定 4 张,草稿模式接受任意数量。""" + + @classmethod + def define_schema(cls): + content_references = io.Autogrow.Input( + "参考图组", + template=io.Autogrow.TemplateNames( + input=io.Image.Input("参考图"), + names=[f"参考图{i}" for i in range(1, MJ_CONTENT_REF_MAX + 1)], + min=0, + ), + tooltip=( + f"内容/构图参考(对应图生图):约束主体姿势、构图与物体。" + f"接好一张后自动出现下一张;最多 {MJ_CONTENT_REF_MAX} 张。" + f"可与「风格参考图」同时使用;不传则为纯文生图。" + ), + ) + style_references = io.Autogrow.Input( + "风格参考图组", + template=io.Autogrow.TemplateNames( + input=io.Image.Input("风格参考图"), + names=[f"风格参考图{i}" for i in range(1, MJ_STYLE_REF_MAX + 1)], + min=0, + ), + tooltip=( + f"风格/画风参考(写入 --sref):只学色彩、笔触、氛围,不强制同一构图。" + f"接好一张后自动出现下一张;最多 {MJ_STYLE_REF_MAX} 张。" + f"强度由「风格权重」控制。" + ), + ) + return io.Schema( + node_id="O1keyMJImage", + display_name="o1key MJ图片生成", + category="o1key/image", + inputs=[ + io.String.Input( + "提示词", + default="", + multiline=True, + tooltip="画面描述。Midjourney 参数由下方控件写入 prompt;若手写同名参数会被控件值覆盖。", + ), + content_references, + style_references, + io.Float.Input( + "参考图权重", + default=MJ_IW_DEFAULT, + min=MJ_IW_MIN, + max=MJ_IW_MAX, + step=0.1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --iw;仅在有内容参考图时生效,越高越贴合参考结构。", + ), + io.Int.Input( + "风格权重", + default=MJ_SW_DEFAULT, + min=MJ_SW_MIN, + max=MJ_SW_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --sw;仅在有风格参考图时生效,范围 0–1000,默认 100。", + ), + io.String.Input( + "排除内容", + default="", + multiline=False, + tooltip="有内容时写入 --no ...;控件优先,会覆盖提示词里手写的 --no。", + ), + io.Combo.Input( + "画面比例", + options=list(MJ_ASPECT_RATIO_OPTIONS), + default="1:1", + tooltip="写入 --ar;控制比例,不承诺精确像素。", + ), + io.Int.Input( + "渲染质量", + default=MJ_QUALITY_DEFAULT, + min=MJ_QUALITY_MIN, + max=MJ_QUALITY_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --q;v8.2 支持 1–4。", + ), + io.Boolean.Input( + "高清", + default=False, + label_on="开启", + label_off="关闭", + tooltip="开启后写入 --hd;长边约翻倍到 2048。", + ), + io.Boolean.Input( + "草稿模式", + default=False, + label_on="开启", + label_off="关闭", + tooltip="开启后写入 --draft;更快更便宜,出图数量可能不是 4 张。", + ), + io.Boolean.Input( + "原生模式", + default=False, + label_on="开启", + label_off="关闭", + tooltip="开启后写入 --raw;弱化默认美化滤镜。", + ), + io.Int.Input( + "风格化", + default=MJ_STYLIZE_DEFAULT, + min=MJ_STYLIZE_MIN, + max=MJ_STYLIZE_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --s;0–1000,默认 250,越高越艺术化。", + ), + io.Int.Input( + "差异度", + default=MJ_CHAOS_DEFAULT, + min=MJ_CHAOS_MIN, + max=MJ_CHAOS_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --c;仅当大于 0 时写入。越高四张候选差异越大。", + ), + io.Int.Input( + "怪异度", + default=MJ_WEIRD_DEFAULT, + min=MJ_WEIRD_MIN, + max=MJ_WEIRD_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --weird;仅当大于 0 时写入,范围 0–3000。", + ), + io.Boolean.Input( + "无缝平铺纹理", + default=False, + label_on="开启", + label_off="关闭", + tooltip="开启后写入 --tile;适合壁纸、贴图等可无限拼接的无缝纹理。", + ), + io.Int.Input( + "实验值", + default=MJ_EXP_DEFAULT, + min=MJ_EXP_MIN, + max=MJ_EXP_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="写入 --exp;仅当大于 0 时写入,范围 0–100。", + ), + io.Int.Input( + "种子", + default=-1, + min=-1, + max=2**31 - 1, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="-1 表示不指定;≥0 时写入 --seed。", + ), + io.Int.Input( + "超时秒数", + default=MJ_DEFAULT_TIMEOUT_SECONDS, + min=30, + max=900, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="仅客户端轮询超时;单次任务通常 60–170 秒。", + ), + ], + outputs=[ + io.Image.Output(display_name="IMAGE"), + ], + ) + + @classmethod + def execute( + cls, + 提示词: str, + 画面比例: str = "1:1", + 渲染质量: int = MJ_QUALITY_DEFAULT, + 高清: bool = False, + 参考图权重: float = MJ_IW_DEFAULT, + 风格权重: int = MJ_SW_DEFAULT, + 原生模式: bool = False, + 风格化: int = MJ_STYLIZE_DEFAULT, + 差异度: int = MJ_CHAOS_DEFAULT, + 怪异度: int = MJ_WEIRD_DEFAULT, + 无缝平铺纹理: bool = False, + 实验值: int = MJ_EXP_DEFAULT, + 草稿模式: bool = False, + 排除内容: str = "", + 种子: int = -1, + 超时秒数: int = MJ_DEFAULT_TIMEOUT_SECONDS, + **kwargs, + ) -> io.NodeOutput: + start_time = time.time() + _check_interrupt() + + try: + reference_images = _collect_reference_images( + group_value=kwargs.get("参考图组"), + kwargs=kwargs, + max_count=MJ_CONTENT_REF_MAX, + label="参考图", + numbered_prefix="参考图", + legacy_key="参考图", + ) + style_images = _collect_reference_images( + group_value=kwargs.get("风格参考图组"), + kwargs=kwargs, + max_count=MJ_STYLE_REF_MAX, + label="风格参考图", + numbered_prefix="风格参考图", + legacy_key="风格参考图", + ) + except ValueError as exc: + raise ValueError(str(exc)) from None + + progress_bar = ProgressBar(100) if _PROGRESS_BAR_AVAILABLE else None + last_pct = {"value": -1} + + def _progress(fraction: float) -> None: + if progress_bar is None: + return + try: + pct = int(round(max(0.0, min(1.0, float(fraction))) * 100)) + except (TypeError, ValueError): + return + if pct < last_pct["value"]: + return + last_pct["value"] = pct + progress_bar.update_absolute(pct, 100) + + try: + client = MjImageClient() + except ValueError as exc: + if str(exc) == "未授权!": + print(f"[{MJ_NODE_LABEL}] 请联系作者授权后方可使用。") + raise ValueError("未授权!") from None + raise + + opened = list(reference_images) + list(style_images) + try: + pil_images = client.generate_sync( + prompt=提示词, + aspect_ratio=画面比例, + quality=渲染质量, + hd=bool(高清), + image_weight=参考图权重, + raw=bool(原生模式), + stylize=风格化, + chaos=差异度, + seed=种子, + weird=怪异度, + tile=bool(无缝平铺纹理), + exp=实验值, + draft=bool(草稿模式), + no_text=排除内容 or "", + style_weight=风格权重, + images=reference_images, + style_images=style_images, + timeout_seconds=超时秒数, + check_interrupt=_check_interrupt, + progress_callback=_progress, + ) + except InterruptProcessingException: + print(f"[{MJ_NODE_LABEL}] 用户取消") + raise + except Exception as exc: + message = str(exc).split("\n")[0] + print(f"[{MJ_NODE_LABEL}] 失败:{message}") + raise RuntimeError(message) from None + finally: + for image in opened: + try: + image.close() + except Exception: + pass + + if progress_bar is not None: + progress_bar.update_absolute(100, 100) + + output = pil_images_to_output_tensor(pil_images) + elapsed = time.time() - start_time + print( + f"[{MJ_NODE_LABEL}] 节点完成 | 耗时 {elapsed:.1f}s | " + f"输出 {output.shape[0]} 张 {output.shape[2]}x{output.shape[1]}" + ) + return io.NodeOutput(output) + + +__all__ = ["O1keyMJImage"] diff --git a/nodes/o1key_image_generator.py b/nodes/o1key_image_generator.py index e3a5a2c..a082f96 100644 --- a/nodes/o1key_image_generator.py +++ b/nodes/o1key_image_generator.py @@ -23,6 +23,7 @@ from ..clients.seedream_image_client import ( from ..utils.config import get_api_key_or_raise, get_base_url_by_route from ..utils.http2_client import create_http_client from ..utils.image_utils import ( + IMAGE_BATCH_MODE_ALIASES, IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_SINGLE_REFERENCES, IMAGE_BATCH_MODES, @@ -36,6 +37,19 @@ from ..utils.o1key_image_catalog import ( BANANA_RESOLUTION_OPTIONS, GPT_IMAGE_ASPECT_RATIO_OPTIONS, GPT_IMAGE_BACKGROUND_OPTIONS, + GPT_IMAGE_COMPLEXITY_OPTIONS, + resolve_gpt_image_complexity, + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + resolve_gpt_image_output_format, + validate_gpt_image_vector_output, + GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS, + GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + GPT_IMAGE_GIF_FRAME_COUNT_MAX, + GPT_IMAGE_GIF_FRAME_COUNT_MIN, + GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + GPT_IMAGE_GIF_FRAME_DURATION_MAX, + GPT_IMAGE_GIF_FRAME_DURATION_MIN, GPT_IMAGE_COUNTS, GPT_IMAGE_EXACT_SIZE_OPTIONS, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, @@ -258,6 +272,9 @@ async def _generate_gpt_images( resize_mode: str, output_format: str, background: str, + complexity: str | None = None, + frame_count: int | None = None, + frame_duration_ms: int | None = None, ): if mask is not None and not references: raise ValueError("提供了蒙版但未提供参考图,请同时上传参考图") @@ -295,6 +312,9 @@ async def _generate_gpt_images( mask_tensor=mask, output_format=output_format, background=background, + **({"complexity": complexity} if complexity is not None else {}), + **({"frame_count": frame_count} if frame_count is not None else {}), + **({"frame_duration_ms": frame_duration_ms} if frame_duration_ms is not None else {}), resize_mode=resize_mode, special_price_parallel=False, log_downloads=True, @@ -542,7 +562,7 @@ class O1keyImageGenerator(io.ComfyNode): io.Combo.Input( "思考等级", options=["低", "高"], - default="低", + default="高", socketless=True, ), io.Combo.Input( @@ -566,6 +586,7 @@ class O1keyImageGenerator(io.ComfyNode): ), io.Int.Input( "seed", + display_name="种子", default=0, min=0, max=0xFFFFFFFFFFFFFFFF, @@ -587,7 +608,7 @@ class O1keyImageGenerator(io.ComfyNode): ), io.Combo.Input( "输出格式", - options=GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, + options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS, default="jpeg", socketless=True, ), @@ -600,7 +621,7 @@ class O1keyImageGenerator(io.ComfyNode): io.Combo.Input( "缩放图片", options=["不缩放", "智能缩放"], - default="不缩放", + default="智能缩放", tooltip="Nano Banana 与 GPT Image 生效;智能缩放可能发生像素偏移。", socketless=True, ), @@ -616,14 +637,19 @@ class O1keyImageGenerator(io.ComfyNode): default=False, label_on="开启", label_off="关闭", - tooltip="关闭时保持普通参考图生成;开启后按素材图和目标图展开组合。", + tooltip="关闭时按普通参考图生成;开启后把素材图按所选模式与目标图组合,一次排队生成多张。", socketless=True, ), io.Combo.Input( "批量模式", options=list(IMAGE_BATCH_MODES), default=IMAGE_BATCH_MODE_GROUP_TO_MODELS, - tooltip="整组素材:全部素材图作为一组并依次应用到多个目标;全匹配:每张素材图分别与每张目标图组合。", + tooltip=( + "素材图与目标图的配对方式。" + "整组素材→多个目标:整组素材作为一套,依次套用到每张目标图;" + "每张素材×每张目标:两两组合,覆盖最全;" + "每张素材单独出图:不需要目标图,每张素材各自生成。" + ), socketless=True, ), io.String.Input( @@ -659,13 +685,6 @@ class O1keyImageGenerator(io.ComfyNode): tooltip="留空保存到 ComfyUI output 根目录;相对路径是 output 内的子文件夹;绝对路径可保存到任意磁盘目录。", socketless=True, ), - io.Combo.Input( - "在线搜索", - options=["关闭", "打开"], - default="关闭", - tooltip="仅 Nano Banana 2 / 2.1 生效;打开时发送 google_search=true。", - socketless=True, - ), io.Boolean.Input( "图层拆分", default=False, @@ -674,6 +693,31 @@ class O1keyImageGenerator(io.ComfyNode): tooltip="仅 Seedream 生效;必须且只能上传1张参考图,返回底图和最多16个透明图层。", socketless=True, ), + io.Combo.Input( + "复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高", + tooltip="仅 GPT Image 2.6 生效;越高规划越充分、耗时越长。", + socketless=True, + ), + io.Int.Input( + "帧数", + default=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_COUNT_MIN, + max=GPT_IMAGE_GIF_FRAME_COUNT_MAX, + step=1, + display_mode=io.NumberDisplay.number, + tooltip="仅 GPT Image 2.6 且输出 GIF 时生效。", + socketless=True, + ), + io.Int.Input( + "帧时长ms", + default=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, + min=GPT_IMAGE_GIF_FRAME_DURATION_MIN, + max=GPT_IMAGE_GIF_FRAME_DURATION_MAX, + step=10, + display_mode=io.NumberDisplay.number, + tooltip="仅 GPT Image 2.6 且输出 GIF 时生效;按 10ms 取整。", + socketless=True, + ), ], outputs=[ io.Image.Output("IMAGE", display_name="IMAGE"), @@ -690,7 +734,7 @@ class O1keyImageGenerator(io.ComfyNode): prompt: str, 模型: str = "Nano Banana 2.1", 模型线路: str = "畅速", - 思考等级: str = "低", + 思考等级: str = "高", 分辨率: str = UNIFIED_IMAGE_SMART_RESOLUTION, 宽高比: str = "智能", 生图数量: str | int = "1", @@ -708,8 +752,10 @@ class O1keyImageGenerator(io.ComfyNode): filename_prefix: str = "o1key", 格式: str = "原始", 保存位置: str = "", - 在线搜索: str = "关闭", 图层拆分: bool = False, + 复杂度: str = "高", + 帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, + 帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, ) -> io.NodeOutput: layer_decomposition = _is_enabled(图层拆分) if (not prompt or not prompt.strip()) and not ( @@ -719,7 +765,7 @@ class O1keyImageGenerator(io.ComfyNode): if 输出格式 is None: 输出格式 = "png" if is_gpt_image_model(模型) else "jpeg" if 缩放图片 is None: - 缩放图片 = "智能缩放" if is_gpt_image_model(模型) else "不缩放" + 缩放图片 = "智能缩放" save_settings = _normalized_save_settings( 模型, filename_prefix, @@ -729,9 +775,8 @@ class O1keyImageGenerator(io.ComfyNode): ) if 缩放图片 not in {"不缩放", "智能缩放"}: raise ValueError("缩放图片参数无效") - if 在线搜索 not in {"关闭", "打开"}: - raise ValueError("在线搜索参数无效") - google_search = 模型 in {"Nano Banana 2.1", "Nano Banana 2"} and 在线搜索 == "打开" + # 在线搜索已下线:下游客户端仍支持 google_search,这里固定关闭。 + google_search = False image_count = int(生图数量) if is_gpt_image_model(模型): @@ -740,6 +785,8 @@ class O1keyImageGenerator(io.ComfyNode): elif image_count not in UNIFIED_IMAGE_COUNTS: raise ValueError("生图数量仅支持:1、2、4、9") batch_enabled = _is_enabled(批量出图) + # Accept the pre-rename labels so workflows saved with them still run. + 批量模式 = IMAGE_BATCH_MODE_ALIASES.get(批量模式, 批量模式) if 批量模式 not in IMAGE_BATCH_MODES: raise ValueError("批量模式无效") @@ -874,13 +921,21 @@ class O1keyImageGenerator(io.ComfyNode): raise ValueError("GPT Image 分辨率无效") if 宽高比 not in GPT_IMAGE_ASPECT_RATIO_OPTIONS: raise ValueError("GPT Image 宽高比无效") + complexity = resolve_gpt_image_complexity(模型, 复杂度) resolve_gpt_image_quality(模型, 质量) - if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: - raise ValueError("GPT Image 输出格式无效") + 输出格式 = resolve_gpt_image_output_format(模型, 输出格式) if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: raise ValueError("GPT Image 背景参数无效") - if 背景 == "transparent" and 输出格式 == "jpeg": + if 背景 == "transparent" and 输出格式 not in {"png", "webp"}: raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") + validate_gpt_image_vector_output( + 模型, + 输出格式, + has_images=bool(references) or bool(model_references), + has_mask=_parse_mask_manifest(蒙版清单) is not None, + ) + frame_count = resolve_gpt_image_frame_count(输出格式, 帧数) + frame_duration_ms = resolve_gpt_image_frame_duration_ms(输出格式, 帧时长ms) images_with_references: list[tuple[Image.Image, list[Any]]] = [] try: images_with_references = await _generate_gpt_images( @@ -897,6 +952,9 @@ class O1keyImageGenerator(io.ComfyNode): resize_mode=缩放图片, output_format=输出格式, background=背景, + complexity=complexity, + frame_count=frame_count, + frame_duration_ms=frame_duration_ms, ) except Exception as exc: message = format_o1key_image_error(exc) @@ -1009,18 +1067,27 @@ class O1keyImageSave(io.ComfyNode): save_location=settings.get("save_location", ""), naming_rule=settings.get("naming_rule", DEFAULT_SAVE_NAMING_RULE), ) - saved = ui.SavedImages([ - ui.SavedResult( - item["filename"], - item["subfolder"], - ( - io.FolderType.temp - if item.get("type") == "temp" - else io.FolderType.output - ), - ) + animated = any( + str(item.get("filename") or "").lower().endswith(".gif") + or item.get("media") == "gif" + or item.get("animated") is True for item in descriptors - ]) + ) + saved = ui.SavedImages( + [ + ui.SavedResult( + item["filename"], + item["subfolder"], + ( + io.FolderType.temp + if item.get("type") == "temp" + else io.FolderType.output + ), + ) + for item in descriptors + ], + is_animated=animated, + ) return io.NodeOutput(images, ui=saved) diff --git a/nodes/save_gif.py b/nodes/save_gif.py new file mode 100644 index 0000000..3ee12e4 --- /dev/null +++ b/nodes/save_gif.py @@ -0,0 +1,220 @@ +"""o1key 保存 GIF 节点:写入 output,并带可播放动图预览。""" + +from __future__ import annotations + +import os +from io import BytesIO + +import folder_paths +from comfy_api.latest import io, ui +from comfy_api.latest._io import _UIOutput +from PIL import Image + +from ..utils.gpt_image_media import ( + animation_bytes_from_images, + encode_gif_from_pil_images, + is_gif_bytes, + read_gif_bytes_from_path, + resolve_gif_frame_duration_ms, + write_bytes_atomic, +) +from ..utils.image_utils import pil_to_tensor, tensor_to_pil + + +def _tensor_batch_to_pil(images) -> list: + if images is None: + return [] + batch = tensor_to_pil(images) + if isinstance(batch, list): + return batch + return [batch] + + +def _gif_size_hint(data: bytes) -> tuple[int, int]: + try: + with Image.open(BytesIO(data)) as image: + return int(image.size[0]), int(image.size[1]) + except Exception: + return 0, 0 + + +def _pil_frames_from_gif_bytes(data: bytes) -> list: + frames = [] + with Image.open(BytesIO(data)) as opened: + try: + n = int(getattr(opened, "n_frames", 1) or 1) + except Exception: + n = 1 + for index in range(n): + try: + opened.seek(index) + except EOFError: + break + frames.append(opened.copy().convert("RGBA")) + if not frames: + frames = [opened.convert("RGBA")] + return frames + + +class SavedGifPreview(_UIOutput): + """GIF preview payload under a custom UI key. + + Must NOT use ``ui.SavedImages`` / the ``images`` key. Comfy frontend + ``unsafeUpdatePreviews`` reads ``getNodeOutputs(node).images``, loads + them via ``useNodeImage`` into ``node.imgs``, then + ``showCanvasImagePreview`` mounts ``$$canvas-image-preview`` + (IMAGE_PREVIEW) which paints a static frame + ``W x H`` under our + DOM widget. A custom key is ignored by that path; ``gifPreview.js`` + mounts a single playable ```` from ``o1key_gif``. + """ + + UI_KEY = "o1key_gif" + + def __init__(self, results: list[ui.SavedResult]): + super().__init__() + self.results = results + + def as_dict(self) -> dict: + return {self.UI_KEY: self.results} + + +def _preview_ui(file_name: str, subfolder: str) -> SavedGifPreview: + return SavedGifPreview( + [ui.SavedResult(file_name, subfolder, io.FolderType.output)], + ) + + +class O1keySaveGIF(io.ComfyNode): + """将成品 GIF 保存到 ComfyUI output,并在节点上播放预览。 + + 优先透传 gpt image「文件路径」指向的原始 GIF 字节(不重编码)。 + 其次从 IMAGE 批帧上的原始 GIF 元数据透传(接「图像」也能避免重编码)。 + 若只有普通 IMAGE 批帧,则按 fps / 帧时长ms 编码为 GIF。 + """ + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="O1keySaveGIF", + display_name="保存 GIF", + category="o1key/image", + description=( + "保存 GIF 到 output 目录,并显示可播放动图预览。" + "推荐连接 gpt image 的「文件路径」;只接「图像」时也会尽量透传原始 GIF。" + ), + is_output_node=True, + inputs=[ + io.String.Input( + "文件路径", + default="", + optional=True, + tooltip="优先:连接 gpt image 的「文件路径」输出,原样复制 GIF 到 output。", + ), + io.Image.Input( + "图像", + optional=True, + tooltip=( + "可选:IMAGE 批帧。若帧上带有原始 GIF 字节则仍透传;" + "否则按 fps/帧时长编码。推荐优先接「文件路径」。" + ), + ), + io.String.Input( + "文件名前缀", + default="ComfyUI", + tooltip="保存到 output 时的文件名前缀(带计数器)。", + ), + io.Float.Input( + "fps", + default=5.0, + min=0.01, + max=1000.0, + step=0.01, + tooltip="仅编码回退路径使用。默认 5 ≈ 200ms/帧。", + ), + io.Int.Input( + "帧时长ms", + default=0, + min=0, + max=2000, + step=10, + tooltip="仅编码回退路径使用。>0 时覆盖 fps(单位毫秒);0 表示按 fps 计算。", + ), + ], + outputs=[ + io.String.Output("FILE", display_name="文件路径"), + io.Image.Output("IMAGE", display_name="图像"), + ], + ) + + @classmethod + def execute( + cls, + 文件路径: str = "", + 图像=None, + 文件名前缀: str = "ComfyUI", + fps: float = 5.0, + 帧时长ms: int = 0, + ) -> io.NodeOutput: + source_path = str(文件路径 or "").strip().strip('"').strip("'") + gif_bytes = read_gif_bytes_from_path(source_path) + mode = "原样透传" if gif_bytes is not None else None + pil_frames = _tensor_batch_to_pil(图像) if 图像 is not None else [] + + if gif_bytes is None and pil_frames: + embedded = animation_bytes_from_images(pil_frames) + if embedded is not None: + gif_bytes = embedded + mode = "元数据透传" + + if gif_bytes is None: + if source_path and os.path.isfile(source_path) and not pil_frames: + raise ValueError(f"文件不是 GIF,且未提供图像帧: {source_path}") + if not pil_frames: + if source_path: + raise ValueError(f"GIF 文件不存在: {source_path}") + raise ValueError("请连接「文件路径」(推荐)或「图像」批帧") + duration_ms = resolve_gif_frame_duration_ms(fps=fps, frame_duration_ms=帧时长ms) + gif_bytes = encode_gif_from_pil_images(pil_frames, duration_ms=duration_ms) + mode = "帧编码" + if source_path: + print( + "[o1key 保存 GIF] 提示: 已接「图像」且走帧编码;" + "若同时有 gpt image「文件路径」,改接文件路径可避免重编码变大。" + ) + + if not is_gif_bytes(gif_bytes): + raise RuntimeError("内部错误:待保存数据不是 GIF") + + width, height = _gif_size_hint(gif_bytes) + output_dir = folder_paths.get_output_directory() + full_output_folder, filename, counter, subfolder, _prefix = folder_paths.get_save_image_path( + 文件名前缀 or "ComfyUI", + output_dir, + width, + height, + ) + os.makedirs(full_output_folder, exist_ok=True) + while True: + file_name = f"{filename}_{counter:05}_.gif" + target = os.path.join(full_output_folder, file_name) + if not os.path.exists(target): + break + counter += 1 + + write_bytes_atomic(target, gif_bytes) + size_kb = os.path.getsize(target) / 1024.0 + print(f"[o1key 保存 GIF] {mode}: {target} ({size_kb:.0f}KB)") + + preview = _preview_ui(file_name, subfolder) + + if 图像 is not None: + image_out = 图像 + elif pil_frames: + image_out = pil_to_tensor(pil_frames) + else: + image_out = pil_to_tensor(_pil_frames_from_gif_bytes(gif_bytes)) + + return io.NodeOutput(target, image_out, ui=preview) + + +__all__ = ["O1keySaveGIF", "SavedGifPreview"] diff --git a/requirements.txt b/requirements.txt index 2974d3a..58427f9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,3 +4,5 @@ Pillow>=10.0.0 requests>=2.31.0 rembg[cpu]>=2.0.50 imageio-ffmpeg>=0.5.1 +# Optional: better GPT Image SVG raster previews (falls back to placeholder) +# cairosvg>=2.7.0 diff --git a/tests/test_gpt_image_migrate_tail.mjs b/tests/test_gpt_image_migrate_tail.mjs new file mode 100644 index 0000000..e1a2f47 --- /dev/null +++ b/tests/test_gpt_image_migrate_tail.mjs @@ -0,0 +1,124 @@ +/** + * Regression: GPT Image widgets_values must survive reload after 2.6 fields / + * 复杂度 reorder (above 分辨率) and Chinese labels. + * Legacy migrate rules look at the array tail; seed's control_after_generate + * made "补齐缩放和背景" mis-fire and insert 智能缩放/auto before 复杂度. + */ +import assert from "node:assert/strict"; +import test from "node:test"; + +const CONTROL = new Set(["fixed", "increment", "decrement", "randomize"]); +const RESIZE = new Set(["不缩放", "智能缩放"]); +const BG = new Set(["auto", "transparent", "opaque"]); +const MOD = new Set(["自动", "低"]); +const CX = new Set(["low", "medium", "high", "低", "中", "高"]); +const CX_TO_LABEL = Object.freeze({ + low: "低", medium: "中", high: "高", 低: "低", 中: "中", 高: "高", +}); + +function normalizeComplexity(value) { + if (value == null) return "高"; + return CX_TO_LABEL[value] ?? CX_TO_LABEL[String(value).toLowerCase()] ?? "高"; +} + +function placeComplexity(wv, complexity) { + if (CX.has(wv[3])) { + wv[3] = normalizeComplexity(wv[3]); + return; + } + wv.splice(3, 0, normalizeComplexity(complexity === undefined ? "高" : complexity)); +} + +/** Mirrors peel/repair/restore + O1keyGPTImage tail rules in migrateWorkflow.js */ +function migrateGptImageWidgets(values) { + const wv = [...values]; + let frameDuration; + let frameCount; + let complexity; + let controlAfterGenerate; + + const maybeDuration = wv.at(-1); + const maybeCount = wv.at(-2); + const maybeComplexity = wv.at(-3); + if ( + Number.isInteger(maybeDuration) + && Number.isInteger(maybeCount) + && CX.has(maybeComplexity) + ) { + frameDuration = wv.pop(); + frameCount = wv.pop(); + complexity = wv.pop(); + } else if (Number.isInteger(maybeDuration) && Number.isInteger(maybeCount)) { + frameDuration = wv.pop(); + frameCount = wv.pop(); + } else if (["low", "medium", "high"].includes(String(wv.at(-1)).toLowerCase())) { + complexity = wv.pop(); + } + + if (CONTROL.has(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1))) { + wv.splice(wv.length - 2, 2); + } + if (CONTROL.has(wv.at(-1))) { + controlAfterGenerate = wv.pop(); + } + + const alreadyHasTail = ( + (Number.isInteger(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1))) + || (RESIZE.has(wv.at(-3)) && BG.has(wv.at(-2)) && MOD.has(wv.at(-1))) + || (BG.has(wv.at(-3)) && RESIZE.has(wv.at(-2)) && Number.isInteger(wv.at(-1))) + ); + if (!alreadyHasTail) wv.push("智能缩放", "auto", "自动"); + if (RESIZE.has(wv.at(-3)) && BG.has(wv.at(-2)) && MOD.has(wv.at(-1))) wv.pop(); + if (Number.isInteger(wv.at(-3)) && RESIZE.has(wv.at(-2)) && BG.has(wv.at(-1))) { + const start = wv.length - 3; + const [seed, resize, background] = wv.slice(start); + wv.splice(start, 3, background, resize, seed); + } + + if (controlAfterGenerate !== undefined) wv.push(controlAfterGenerate); + placeComplexity(wv, complexity); + if (frameCount !== undefined) wv.push(frameCount); + if (frameDuration !== undefined) wv.push(frameDuration); + return wv; +} + +const healthy26 = [ + "一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "高", "智能", 1, "自动", "gif", + "auto", "智能缩放", 123, "randomize", 9, 200, +]; +const old25 = [ + "prompt", "gpt-image-2.5-sunburst", "畅速", "高", "智能", 1, "自动", "png", + "auto", "智能缩放", 123, "randomize", +]; +const old26TailComplexity = [ + "一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "智能", 1, "自动", "gif", + "auto", "智能缩放", 123, "randomize", "high", 9, 200, +]; +const scrambled = [ + "一个在跳舞的美女", "gpt-image-2.6-sunburst", "专线", "智能", 1, "自动", "gif", + "auto", "智能缩放", 123, "randomize", "智能缩放", "auto", "high", 9, 200, +]; + +test("keeps healthy 2.6 gif widgets_values with mid-list 复杂度", () => { + assert.deepEqual(migrateGptImageWidgets(healthy26), healthy26); +}); + +test("inserts default 复杂度 for pre-2.6 widgets_values", () => { + const input = [ + "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "自动", "png", + "auto", "智能缩放", 123, "randomize", + ]; + assert.deepEqual(migrateGptImageWidgets(input), old25); +}); + +test("moves old tail 复杂度 above 分辨率 and localizes label", () => { + assert.deepEqual(migrateGptImageWidgets(old26TailComplexity), healthy26); +}); + +test("repairs scrambled 复杂度/帧数/帧时长ms shift", () => { + assert.deepEqual(migrateGptImageWidgets(scrambled), healthy26); +}); + +test("repair is idempotent", () => { + assert.deepEqual(migrateGptImageWidgets(migrateGptImageWidgets(scrambled)), healthy26); +}); \ No newline at end of file diff --git a/tests/test_gpt_image_nodes.py b/tests/test_gpt_image_nodes.py index 3d1b182..e1fc72c 100644 --- a/tests/test_gpt_image_nodes.py +++ b/tests/test_gpt_image_nodes.py @@ -3,6 +3,8 @@ import asyncio import os import sys +import tempfile +from pathlib import Path import unittest from io import BytesIO from types import ModuleType @@ -64,15 +66,16 @@ class GPTImageNodeSchemaTests(unittest.TestCase): self.assertEqual(inputs["缩放图片"].options, ["不缩放", "智能缩放"]) self.assertEqual(inputs["缩放图片"].default, "智能缩放") - self.assertEqual(inputs["模型"].default, "gpt-image-2.5-sunburst") + self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst") self.assertNotIn("色彩纠正", inputs) self.assertEqual(inputs["背景"].options, ["auto", "transparent", "opaque"]) self.assertNotIn("内容审查强度", inputs) self.assertEqual( [item.id for item in schema.inputs], [ - "prompt", "模型", "模型线路", "分辨率", "生图数量", "质量", + "prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量", "输出格式", "背景", "遮罩", "参考图组", "缩放图片", "seed", + "帧数", "帧时长ms", ], ) self.assertEqual( @@ -106,7 +109,7 @@ class GPTImageNodeSchemaTests(unittest.TestCase): self.assert_combo_values_are_strings(schema) inputs = {item.id: item for item in schema.inputs} - self.assertEqual(inputs["模型"].default, "gpt-image-2.5-sunburst") + self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst") self.assertEqual(inputs["缩放图片"].default, "智能缩放") self.assertEqual(inputs["质量"].options, ["高", "中", "低", "自动", "超高", "最高"]) self.assertNotIn("色彩纠正", inputs) @@ -114,9 +117,10 @@ class GPTImageNodeSchemaTests(unittest.TestCase): self.assertEqual( [item.id for item in schema.inputs], [ - "prompt", "模型", "模型线路", "分辨率", "生图数量", "质量", + "prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量", "图片路径数量", "遮罩", "参考图组", "图片输出格式", "背景", "图片保存命名规则", "图片保存路径", "缩放图片", "seed", + "帧数", "帧时长ms", ], ) self.assertNotIn("并发数", inputs) @@ -139,6 +143,114 @@ class GPTImageNodeSchemaTests(unittest.TestCase): ): self.assertFalse(inputs[input_name].advanced, input_name) +class GPTImage26Tests(unittest.IsolatedAsyncioTestCase): + def test_schema_and_all_six_routes_preserve_existing_defaults(self): + for node in (O1keyGPTImage, O1keyGPTImageBatch): + inputs = {item.id: item for item in node.define_schema().inputs} + self.assertEqual(inputs["模型"].default, "gpt-image-2.6-sunburst") + self.assertEqual(list(inputs)[3], "复杂度") + self.assertEqual(list(inputs)[-2], "帧数") + self.assertEqual(list(inputs)[-1], "帧时长ms") + self.assertEqual(inputs["复杂度"].default, "高") + self.assertEqual(inputs["复杂度"].options, ["高", "中", "低"]) + self.assertEqual(inputs["帧数"].default, 9) + self.assertEqual(inputs["帧时长ms"].default, 200) + for variant in ("sunburst", "flare"): + model = f"gpt-image-2.6-{variant}" + self.assertIn(model, inputs["模型"].options) + self.assertEqual(resolve_gpt_image_quality(model, "超高"), "xhigh") + self.assertEqual(resolve_gpt_image_quality(model, "最高"), "max") + for route, suffix in (("畅速", "-sp"), ("直连", "-sd"), ("专线", "")): + with self.subTest(node=node.__name__, model=model, route=route): + self.assertEqual(resolve_gpt_image_model(model, route), model + suffix) + + def test_payload_complexity_is_validated_for_every_26_route_only(self): + client = object.__new__(GptImageClient) + for variant in ("sunburst", "flare"): + for suffix in ("-sp", "-sd", ""): + model = f"gpt-image-2.6-{variant}{suffix}" + for value in (None, "low", "medium", "high"): + with self.subTest(model=model, complexity=value): + body = client._build_async_generate_body( + "test", model, "max", None, 1, complexity=value, + ) + self.assertEqual(body["complexity"], value or "high") + self.assertEqual(body["model"], model) + self.assertEqual(body["n"], 1) + self.assertNotIn("size", body) + self.assertNotIn("input_fidelity", body) + with self.assertRaisesRegex(ValueError, "复杂度"): + client._build_async_generate_body("test", model, "high", None, 1, complexity="invalid") + for model in ("gpt-image-2-c-sp", "gpt-image-2.5-sunburst-sp", "gpt-image-2.5-flare"): + body = client._build_async_generate_body("test", model, "high", None, 1, complexity="low") + self.assertNotIn("complexity", body) + for output_format in ("svg", "gif"): + body = client._build_async_generate_body( + "test", "gpt-image-2.6-flare", "high", None, 1, output_format=output_format, + ) + self.assertEqual(body["output_format"], output_format) + if output_format == "gif": + self.assertEqual(body["frame_count"], 9) + self.assertEqual(body["frame_duration_ms"], 200) + else: + self.assertNotIn("frame_count", body) + self.assertNotIn("frame_duration_ms", body) + with self.assertRaisesRegex(ValueError, "仅支持 GPT Image 2.6"): + client._build_async_generate_body( + "test", "gpt-image-2.5-flare", "high", None, 1, output_format=output_format, + ) + + async def test_single_and_parallel_client_requests_keep_complexity_and_n_one(self): + client = object.__new__(GptImageClient) + generated = Image.new("RGB", (6, 4), "green") + with patch.object(client, "_generate_image_task_async", new=AsyncMock(return_value=[generated])) as generate: + for count in (1, 3): + generate.reset_mock() + images = await client.generate_image_async( + prompt="test", model="gpt-image-2.6-flare-sd", quality="xhigh", + size=None, n=count, seed=0, complexity="medium", log_request_start=False, + ) + self.assertEqual(len(images), count) + self.assertEqual(generate.await_count, count) + for call in generate.await_args_list: + self.assertEqual(call.kwargs["complexity"], "medium") + self.assertEqual(call.kwargs["n"], 1) + + def test_standalone_sync_and_batch_prompt_paths_forward_complexity(self): + calls = [] + class FakeClient: + def generate_image_async_sync(self, **kwargs): + calls.append(kwargs) + return [Image.new("RGB", (6, 4), "green")] + _pil_list_to_tensor = staticmethod(GptImageClient._pil_list_to_tensor) + with patch("comfyui_o1key.nodes.gpt_image.GptImageClient", FakeClient), patch( + "comfyui_o1key.nodes.gpt_image.get_base_url_by_route", return_value="https://example.invalid", + ), patch("builtins.print"): + for prompt in ("test", "first\n---\nsecond"): + O1keyGPTImage.generate( + prompt=prompt, 模型="gpt-image-2.6-sunburst", 模型线路="直连", + 质量="最高", 复杂度="低", + ) + self.assertEqual(len(calls), 3) + self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sd" for call in calls)) + self.assertTrue(all(call["quality"] == "max" for call in calls)) + self.assertTrue(all(call["complexity"] == "low" for call in calls)) + + async def test_batch_orchestrator_forwards_complexity(self): + calls = [] + class FakeClient: + async def generate_image_async(self, **kwargs): + calls.append(kwargs) + return [Image.new("RGB", (6, 4), "green")] + with patch.object(O1keyGPTImageBatch, "_save_images", return_value=["output.png"]), patch("builtins.print"): + results = await O1keyGPTImageBatch._process_async( + FakeClient(), [(0, (), "test")], "gpt-image-2.6-flare-sp", "xhigh", "auto", 1, 0, + None, "png", "auto", "智能缩放", "output", "自然数字", None, "medium", + ) + self.assertTrue(results[0]["success"]) + self.assertEqual(calls[0]["complexity"], "medium") + + class GPTImageNodeExecutionTests(unittest.TestCase): def test_single_node_forwards_request_controls_without_postprocess(self): calls = [] @@ -174,7 +286,7 @@ class GPTImageNodeExecutionTests(unittest.TestCase): self.assertIs(result[0], generated) self.assertEqual(len(calls), 1) - self.assertEqual(calls[0]["model"], "gpt-image-2.5-sunburst-sp") + self.assertEqual(calls[0]["model"], "gpt-image-2.6-sunburst-sp") self.assertEqual(calls[0]["resize_mode"], "智能缩放") self.assertEqual(calls[0]["background"], "transparent") self.assertNotIn("moderation", calls[0]) @@ -326,19 +438,145 @@ class GPTImageDownloadRetryTests(unittest.IsolatedAsyncioTestCase): ), patch("builtins.print") as print_mock, ): - image, byte_count, _elapsed = await client._download_image_with_response_retry( + images, byte_count, _elapsed = await client._download_image_with_response_retry( session, signed_url, "第 1 张图片", ) self.assertEqual(session.calls, 2) - self.assertEqual(image.size, (3, 2)) + self.assertEqual(images[0].size, (3, 2)) self.assertEqual(byte_count, len(image_bytes)) rendered = " ".join(str(value) for call in print_mock.call_args_list for value in call.args) self.assertNotIn(signed_url, rendered) self.assertNotIn("signature=secret", rendered) +class GPTImage26SvgGifTests(unittest.TestCase): + def test_gif_frame_bounds_and_rounding(self): + from comfyui_o1key.utils.o1key_image_catalog import ( + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + ) + self.assertEqual(resolve_gpt_image_frame_count("gif", None), 9) + self.assertEqual(resolve_gpt_image_frame_duration_ms("gif", 205), 200) + with self.assertRaisesRegex(ValueError, "帧数"): + resolve_gpt_image_frame_count("gif", 1) + with self.assertRaisesRegex(ValueError, "帧时长"): + resolve_gpt_image_frame_duration_ms("gif", 10) + + def test_svg_gif_reject_edit_inputs(self): + import torch + client = object.__new__(GptImageClient) + fake = torch.zeros((1, 8, 8, 3)) + for output_format in ("svg", "gif"): + with self.assertRaisesRegex(ValueError, "纯文生图"): + client._build_async_generate_body( + "test", "gpt-image-2.6-sunburst", "high", None, 1, + image_list=[fake], output_format=output_format, + ) + + def test_materialize_gif_expands_frames_and_keeps_bytes(self): + from io import BytesIO + from PIL import Image + from comfyui_o1key.utils.gpt_image_media import ( + animation_bytes_from_images, + materialize_result_images, + ) + buf = BytesIO() + frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue", "green")] + frames[0].save(buf, format="GIF", save_all=True, append_images=frames[1:], duration=100, loop=0) + data = buf.getvalue() + images = materialize_result_images(data, requested_format="gif") + self.assertEqual(len(images), 3) + self.assertEqual(animation_bytes_from_images(images), data) + + def test_gif_preview_ui_uses_custom_key_not_images(self): + # Save GIF must NOT emit SavedImages/images — core would mount + # $$canvas-image-preview (static frame + "W x H"). Custom o1key_gif + # key is read only by web/js/gifPreview.js. + from comfy_api.latest import io, ui + from comfyui_o1key.nodes.save_gif import SavedGifPreview + preview = SavedGifPreview( + [ui.SavedResult("demo.gif", "", io.FolderType.output)], + ) + data = preview.as_dict() + self.assertNotIn("images", data) + self.assertNotIn("animated", data) + self.assertIn(SavedGifPreview.UI_KEY, data) + self.assertEqual(data[SavedGifPreview.UI_KEY][0]["type"], "output") + self.assertTrue(str(data[SavedGifPreview.UI_KEY][0]["filename"]).endswith(".gif")) + + def test_generate_gif_writes_temp_file_without_preview(self): + from io import BytesIO + from types import SimpleNamespace + from unittest.mock import patch + from PIL import Image + import torch + from comfyui_o1key.nodes.gpt_image import O1keyGPTImage + + buf = BytesIO() + frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue")] + frames[0].save(buf, format="GIF", save_all=True, append_images=frames[1:], duration=100, loop=0) + gif_bytes = buf.getvalue() + materialized = [] + from comfyui_o1key.utils.gpt_image_media import materialize_result_images + materialized.extend(materialize_result_images(gif_bytes, requested_format="gif")) + + class FakeClient: + def __init__(self): + self.base_url = "" + self.response_log_enabled = True + self.poll_log_enabled = True + + def generate_image_async_sync(self, **kwargs): + return list(materialized) + + @staticmethod + def _pil_list_to_tensor(images): + return torch.zeros((len(images), 4, 6, 3), dtype=torch.float32) + + def query_balance_sync(self): + return {} + + def format_balance_info(self, _data): + return "" + + with tempfile.TemporaryDirectory() as temp_dir: + folder = SimpleNamespace( + get_temp_directory=lambda: temp_dir, + get_output_directory=lambda: temp_dir, + ) + with ( + patch("comfyui_o1key.nodes.gpt_image.GptImageClient", FakeClient), + patch( + "comfyui_o1key.nodes.gpt_image.get_base_url_by_route", + return_value="https://example.invalid", + ), + patch("comfyui_o1key.nodes.gpt_image._FOLDER_PATHS_AVAILABLE", True), + patch("comfyui_o1key.nodes.gpt_image.folder_paths", folder), + ): + tensor, file_path, preview = O1keyGPTImage.generate( + prompt="gif demo", + 模型="gpt-image-2.6-flare", + 输出格式="gif", + 帧数=2, + 帧时长ms=100, + ) + self.assertTrue(str(file_path).lower().endswith(".gif")) + self.assertTrue(Path(file_path).is_file()) + self.assertEqual(Path(file_path).read_bytes(), gif_bytes) + # gpt image: no node UI preview for GIF (only file path / temp bytes) + self.assertIsNone(preview) + self.assertEqual(tuple(tensor.shape)[0], 2) + + def test_materialize_svg_returns_preview_with_original_bytes(self): + from comfyui_o1key.utils.gpt_image_media import materialize_result_images, svg_bytes_from_image + svg = b"""""" + images = materialize_result_images(svg, requested_format="svg") + self.assertEqual(len(images), 1) + self.assertEqual(svg_bytes_from_image(images[0]), svg) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_gpt_image_quality_frontend.mjs b/tests/test_gpt_image_quality_frontend.mjs index 9e17c04..649ad26 100644 --- a/tests/test_gpt_image_quality_frontend.mjs +++ b/tests/test_gpt_image_quality_frontend.mjs @@ -108,3 +108,58 @@ assert.equal(backgroundWidget.options.getOptionLabel("transparent"), "透明"); assert.equal(backgroundWidget.options.getOptionLabel("opaque"), "不透明"); assert.equal(backgroundWidget.value, "transparent"); assert.deepEqual(Array.from(backgroundWidget.options.values), ["auto", "transparent", "opaque"]); + +for (const nodeType of ["O1keyGPTImage", "O1keyGPTImageBatch"]) { + const node = makeNode("gpt-image-2.6-sunburst", "最高", nodeType); + const size = () => [150, 20]; + const complexity = { name: "复杂度", value: "中", options: {}, computeSize: size }; + node.widgets.push(complexity); + extension.nodeCreated(node); + const callback = node.modelWidget.callback; + extension.nodeCreated(node); + assert.equal(node.modelWidget.callback, callback, "Extension binding remains idempotent"); + assert.equal(node.qualityWidget.value, "最高"); + assert.equal(complexity.hidden, false); + assert.equal(complexity.computeSize, size); + node.modelWidget.value = "gpt-image-2.5-flare"; + node.modelWidget.callback(); + assert.equal(complexity.hidden, true); + assert.equal(complexity.options.hidden, true); + assert.equal(complexity.value, "中"); + assert.deepEqual(Array.from(complexity.computeSize()), [0, -4]); + node.modelWidget.value = "gpt-image-2.6-flare"; + node.onConfigure({}); + extension.loadedGraphNode(node); + assert.equal(complexity.hidden, false); + assert.equal(complexity.computeSize, size); + assert.equal(complexity.value, "中"); + assert.equal(node.qualityWidget.value, "最高"); +} + +for (const nodeType of ["O1keyGPTImage", "O1keyGPTImageBatch"]) { + const node = makeNode("gpt-image-2.6-sunburst", "最高", nodeType); + const size = () => [150, 20]; + const complexity = { name: "复杂度", value: "中", options: {}, computeSize: size }; + const formatName = nodeType === "O1keyGPTImageBatch" ? "图片输出格式" : "输出格式"; + const format = { + name: formatName, + value: nodeType === "O1keyGPTImageBatch" ? "PNG" : "png", + options: { values: [] }, + callback() {}, + }; + const frameCount = { name: "帧数", value: 9, options: {}, computeSize: size }; + const frameDuration = { name: "帧时长ms", value: 200, options: {}, computeSize: size }; + node.widgets.push(complexity, format, frameCount, frameDuration); + extension.nodeCreated(node); + assert.equal(complexity.hidden, false); + assert.ok(format.options.values.includes(nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif")); + assert.equal(frameCount.hidden, true); + format.value = nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif"; + format.callback(); + assert.equal(frameCount.hidden, false); + assert.equal(frameDuration.hidden, false); + node.modelWidget.value = "gpt-image-2"; + node.modelWidget.callback(); + assert.equal(format.options.values.includes(nodeType === "O1keyGPTImageBatch" ? "GIF" : "gif"), false); + assert.equal(frameCount.hidden, true); +} diff --git a/tests/test_kling_video.py b/tests/test_kling_video.py new file mode 100644 index 0000000..a1689f1 --- /dev/null +++ b/tests/test_kling_video.py @@ -0,0 +1,117 @@ +"""Offline regression tests for the Kling 4.0 request contract.""" + +import sys +import types +import unittest +from pathlib import Path + + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(PLUGIN_ROOT.parent)) + +package = types.ModuleType("comfyui_o1key") +package.__path__ = [str(PLUGIN_ROOT)] +sys.modules.setdefault("comfyui_o1key", package) +clients = types.ModuleType("comfyui_o1key.clients") +clients.__path__ = [str(PLUGIN_ROOT / "clients")] +sys.modules.setdefault("comfyui_o1key.clients", clients) +utils = types.ModuleType("comfyui_o1key.utils") +utils.__path__ = [str(PLUGIN_ROOT / "utils")] +sys.modules.setdefault("comfyui_o1key.utils", utils) + +from comfyui_o1key.clients.kling_video_client import ( # noqa: E402 + build_kling_v4_body, + endpoint_for, +) +from comfyui_o1key.utils.video_task import extract_video_url # noqa: E402 + + +class KlingV4RequestTests(unittest.TestCase): + def test_text_mode_uses_resolution_mode_and_adaptive_ratio(self): + body = build_kling_v4_body( + generation_mode="文生视频", + prompt="A slow dolly shot through a rainy market", + duration=30, + resolution="1080p", + aspect_ratio="智能", + ) + + self.assertEqual(body["model_name"], "kling-v4") + self.assertEqual(body["duration"], 30) + self.assertEqual(body["mode"], "pro") + self.assertEqual(body["aspect_ratio"], "adaptive") + self.assertNotIn("metadata", body) + self.assertEqual(endpoint_for("文生视频")[0], "/kling/v1/videos/text2video") + + def test_keyframes_keep_frame_order_and_omit_aspect_ratio(self): + body = build_kling_v4_body( + generation_mode="关键帧", + prompt="Move continuously between the keyframes", + first_frame="https://cdn.example.invalid/first.png", + middle_frames=[ + "https://cdn.example.invalid/middle-1.png", + "https://cdn.example.invalid/middle-2.png", + ], + last_frame="https://cdn.example.invalid/last.png", + ) + + self.assertEqual(body["metadata"], { + "first_frame": "https://cdn.example.invalid/first.png", + "middle_frames": [ + "https://cdn.example.invalid/middle-1.png", + "https://cdn.example.invalid/middle-2.png", + ], + "last_frame": "https://cdn.example.invalid/last.png", + }) + self.assertNotIn("aspect_ratio", body) + self.assertEqual(endpoint_for("关键帧")[0], "/kling/v1/videos/image2video") + + def test_omni_mode_uses_reference_metadata_and_caps_inputs(self): + body = build_kling_v4_body( + generation_mode="全能参考", + prompt="Use the character from @Image1 and the movement from @Video1", + reference_images=["https://cdn.example.invalid/character.png"], + reference_videos=["https://cdn.example.invalid/motion.mp4"], + keep_original_sound=True, + aspect_ratio="21:9", + ) + + self.assertEqual(body["metadata"]["refer_images"], [ + "https://cdn.example.invalid/character.png", + ]) + self.assertEqual(body["metadata"]["videos"], [ + "https://cdn.example.invalid/motion.mp4", + ]) + self.assertTrue(body["keep_original_sound"]) + self.assertEqual(body["aspect_ratio"], "21:9") + self.assertEqual(endpoint_for("全能参考")[0], "/kling/v1/videos/omni-video") + + def test_modes_reject_invalid_combinations_before_upload(self): + with self.assertRaisesRegex(ValueError, "关键帧模式必须提供"): + build_kling_v4_body(generation_mode="关键帧", prompt="move") + with self.assertRaisesRegex(ValueError, "不能连接图片或视频"): + build_kling_v4_body( + generation_mode="文生视频", + prompt="move", + first_frame="https://cdn.example.invalid/frame.png", + ) + with self.assertRaisesRegex(ValueError, "至少需要一张参考图"): + build_kling_v4_body(generation_mode="全能参考", prompt="move") + + def test_v4_output_envelope_is_read_by_shared_parser(self): + self.assertEqual( + extract_video_url({ + "data": { + "status": "succeeded", + "output": { + "media": [{"type": "video", "url": "https://cdn.example.invalid/result.mp4"}], + }, + }, + }), + "https://cdn.example.invalid/result.mp4", + ) + + +if __name__ == "__main__": + unittest.main() + diff --git a/tests/test_mj_prompt.py b/tests/test_mj_prompt.py new file mode 100644 index 0000000..f2e0ff5 --- /dev/null +++ b/tests/test_mj_prompt.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +"""Offline tests for Midjourney prompt assembly and MJ client body/mocks.""" + +from __future__ import annotations + +import asyncio +import os +import sys +import unittest +from types import ModuleType +from unittest.mock import AsyncMock, patch + +from PIL import Image + + +PLUGIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CUSTOM_NODES_DIR = os.path.dirname(PLUGIN_DIR) +COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR) + +for child in ("nodes", "utils", "clients"): + package = ModuleType(f"comfyui_o1key.{child}") + package.__path__ = [os.path.join(PLUGIN_DIR, child)] + sys.modules[package.__name__] = package + +plugin_package = ModuleType("comfyui_o1key") +plugin_package.__path__ = [PLUGIN_DIR] +sys.modules[plugin_package.__name__] = plugin_package + +model_management = ModuleType("comfy.model_management") +model_management.processing_interrupted = lambda: False +model_management.InterruptProcessingException = RuntimeError +sys.modules[model_management.__name__] = model_management + +sys.path.insert(0, COMFY_ROOT) +sys.path.insert(0, CUSTOM_NODES_DIR) + +from comfyui_o1key.utils.mj_prompt import ( # noqa: E402 + MJ_MODEL_ID, + build_mj_prompt, + strip_controlled_mj_flags, +) +from comfyui_o1key.clients import mj_image_client as CLIENT # noqa: E402 + + +class MjPromptTests(unittest.TestCase): + def test_strips_duplicate_user_flags_and_appends_stable_order(self): + prompt = build_mj_prompt( + "a cat --ar 9:16 --q 1 --hd --iw 3 --raw --s 999 --c 50 --seed 7 " + "--weird 10 --tile --exp 5 --draft --no cars --sref https://x/a.png --sw 50", + aspect_ratio="16:9", + quality=2, + hd=True, + image_weight=1.5, + raw=True, + stylize=250, + chaos=12, + seed=42, + has_reference_image=True, + weird=100, + tile=True, + exp=20, + draft=True, + no_text="dogs", + style_ref_urls=["https://upload.example/style.png"], + style_weight=200, + ) + self.assertEqual( + prompt, + "a cat --no dogs --ar 16:9 --q 2 --hd --iw 1.5 " + "--sref https://upload.example/style.png --sw 200 " + "--raw --s 250 --c 12 --weird 100 --tile --exp 20 --draft --seed 42", + ) + + def test_omits_optional_flags_when_disabled(self): + prompt = build_mj_prompt( + " sunset harbor ", + aspect_ratio="1:1", + quality=2, + hd=False, + raw=False, + stylize=250, + chaos=0, + seed=-1, + has_reference_image=False, + weird=0, + tile=False, + exp=0, + draft=False, + no_text="", + ) + self.assertEqual(prompt, "sunset harbor --ar 1:1 --q 2 --s 250") + self.assertNotIn("--hd", prompt) + self.assertNotIn("--iw", prompt) + self.assertNotIn("--raw", prompt) + self.assertNotIn("--c ", prompt) + self.assertNotIn("--seed", prompt) + self.assertNotIn("--weird", prompt) + self.assertNotIn("--tile", prompt) + self.assertNotIn("--exp", prompt) + self.assertNotIn("--draft", prompt) + self.assertNotIn("--no", prompt) + self.assertNotIn("--sref", prompt) + self.assertNotIn("--sw", prompt) + + def test_conditional_weird_exp_tile_draft_no_sw(self): + base = build_mj_prompt("scene", weird=0, exp=0, tile=False, draft=False, no_text=" ") + self.assertNotIn("--weird", base) + self.assertNotIn("--exp", base) + self.assertNotIn("--tile", base) + self.assertNotIn("--draft", base) + self.assertNotIn("--no", base) + + on = build_mj_prompt( + "scene", + weird=1, + exp=1, + tile=True, + draft=True, + no_text="blur", + style_ref_urls=["https://upload.example/s.png"], + style_weight=100, + ) + self.assertIn("--weird 1", on) + self.assertIn("--exp 1", on) + self.assertIn("--tile", on) + self.assertIn("--draft", on) + self.assertIn("--no blur", on) + self.assertIn("--sref https://upload.example/s.png", on) + self.assertIn("--sw 100", on) + + no_style = build_mj_prompt("scene", style_weight=500) + self.assertNotIn("--sw", no_style) + self.assertNotIn("--sref", no_style) + + def test_iw_only_when_reference_present(self): + without_ref = build_mj_prompt( + "portrait", + image_weight=2, + has_reference_image=False, + ) + with_ref = build_mj_prompt( + "portrait", + image_weight=2, + has_reference_image=True, + ) + self.assertNotIn("--iw", without_ref) + self.assertIn("--iw 2", with_ref) + + def test_content_ref_urls_prefixed_and_deduped(self): + url_a = "https://upload.example/a.png" + url_b = "https://upload.example/b.png" + prompt = build_mj_prompt( + f"city night {url_b}", + has_reference_image=True, + content_ref_urls=[url_a, url_b], + image_weight=1.0, + ) + self.assertTrue(prompt.startswith(f"{url_a} city night {url_b}")) + self.assertEqual(prompt.count(url_a), 1) + self.assertEqual(prompt.count(url_b), 1) + self.assertIn("--iw 1", prompt) + + def test_rejects_empty_prompt_after_strip(self): + with self.assertRaisesRegex(ValueError, "提示词不能为空"): + build_mj_prompt(" --ar 1:1 --q 2 ") + self.assertEqual(strip_controlled_mj_flags("hello --stylize 100"), "hello") + self.assertEqual( + strip_controlled_mj_flags("x --weird 9 --tile --exp 2 --draft --no a,b --sref https://u/a --sw 1"), + "x", + ) + + +class MjClientBodyTests(unittest.TestCase): + def test_body_text_only(self): + body = CLIENT.build_mj_submit_body(prompt="a cat --ar 1:1 --q 2 --s 250") + self.assertEqual( + body, + { + "model": MJ_MODEL_ID, + "prompt": "a cat --ar 1:1 --q 2 --s 250", + }, + ) + + def test_body_with_one_https_reference(self): + body = CLIENT.build_mj_submit_body( + prompt="edit outfit --ar 4:5 --q 2 --iw 2 --s 250", + image_urls=["https://upload.example/ref.png"], + ) + self.assertEqual( + body["images"], + ["https://upload.example/ref.png"], + ) + + def test_body_rejects_http_and_multiple_refs(self): + with self.assertRaisesRegex(ValueError, "HTTPS URL"): + CLIENT.build_mj_submit_body( + prompt="x", + image_urls=["http://upload.example/ref.png"], + ) + with self.assertRaisesRegex(ValueError, "最多 1 张"): + CLIENT.build_mj_submit_body( + prompt="x", + image_urls=[ + "https://upload.example/a.png", + "https://upload.example/b.png", + ], + ) + + +class MjClientGenerateMocks(unittest.TestCase): + def test_generate_async_returns_four_images(self): + fake_images = [Image.new("RGB", (64, 64), color=i) for i in range(4)] + + async def _run(): + client = CLIENT.MjImageClient( + base_url="https://example.invalid", + api_key="test-key", + ) + session = object() + with patch( + "comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls", + new=AsyncMock(return_value=[]), + ) as upload_mock, patch( + "comfyui_o1key.clients.mj_image_client.submit_async_image_task", + new=AsyncMock(return_value="task_mj_1"), + ) as submit_mock, patch( + "comfyui_o1key.clients.mj_image_client.poll_async_image_task", + new=AsyncMock(return_value={"status": "SUCCESS"}), + ), patch( + "comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task", + new=AsyncMock( + return_value=( + {"status": "SUCCESS"}, + (fake_images, {"download_bytes": 0, "download_seconds": 0.0, "download_wall_seconds": 0.0, "inline_images": 0}), + ) + ), + ): + result = await client.generate_async( + session=session, + prompt="a small orange cat", + aspect_ratio="1:1", + quality=1, + timeout_seconds=120, + log_task_success=False, + log_downloads=False, + ) + upload_mock.assert_awaited() + submit_mock.assert_awaited() + body = submit_mock.await_args.args[3] + self.assertEqual(body["model"], MJ_MODEL_ID) + self.assertIn("--ar 1:1", body["prompt"]) + self.assertIn("--q 1", body["prompt"]) + self.assertEqual(len(result), 4) + return result + + asyncio.run(_run()) + + def test_generate_async_rejects_wrong_image_count(self): + fake_images = [Image.new("RGB", (32, 32), color=0)] + + async def _run(): + client = CLIENT.MjImageClient( + base_url="https://example.invalid", + api_key="test-key", + ) + with patch( + "comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls", + new=AsyncMock(return_value=[]), + ), patch( + "comfyui_o1key.clients.mj_image_client.submit_async_image_task", + new=AsyncMock(return_value="task_mj_bad"), + ), patch( + "comfyui_o1key.clients.mj_image_client.poll_async_image_task", + new=AsyncMock(return_value={"status": "SUCCESS"}), + ), patch( + "comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task", + new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)), + ): + with self.assertRaisesRegex(RuntimeError, "应返回 4 张图"): + await client.generate_async( + session=object(), + prompt="oops", + log_task_success=False, + log_downloads=False, + ) + + asyncio.run(_run()) + + def test_multi_content_and_style_refs_submit_strategy(self): + fake_images = [Image.new("RGB", (48, 48), color=i) for i in range(4)] + content_pils = [Image.new("RGB", (16, 16), color=10), Image.new("RGB", (16, 16), color=20)] + style_pils = [Image.new("RGB", (16, 16), color=30)] + uploaded = [ + "https://upload.example/c0.png", + "https://upload.example/c1.png", + "https://upload.example/s0.png", + ] + + async def _run(): + client = CLIENT.MjImageClient( + base_url="https://example.invalid", + api_key="test-key", + ) + with patch( + "comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls", + new=AsyncMock(return_value=uploaded), + ) as upload_mock, patch( + "comfyui_o1key.clients.mj_image_client.submit_async_image_task", + new=AsyncMock(return_value="task_mj_multi"), + ) as submit_mock, patch( + "comfyui_o1key.clients.mj_image_client.poll_async_image_task", + new=AsyncMock(return_value={"status": "SUCCESS"}), + ), patch( + "comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task", + new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)), + ): + result = await client.generate_async( + session=object(), + prompt="forest cabin", + images=content_pils, + style_images=style_pils, + style_weight=180, + weird=50, + tile=True, + exp=3, + log_task_success=False, + log_downloads=False, + ) + + upload_mock.assert_awaited() + upload_kwargs = upload_mock.await_args.kwargs + self.assertEqual(len(upload_kwargs["images"]), 3) + + body = submit_mock.await_args.args[3] + self.assertEqual(body["images"], ["https://upload.example/c0.png"]) + self.assertNotIn("https://upload.example/c1.png", body.get("images", [])) + self.assertTrue(body["prompt"].startswith("https://upload.example/c1.png forest cabin")) + self.assertIn("--sref https://upload.example/s0.png", body["prompt"]) + self.assertIn("--sw 180", body["prompt"]) + self.assertIn("--iw 1", body["prompt"]) + self.assertIn("--weird 50", body["prompt"]) + self.assertIn("--tile", body["prompt"]) + self.assertIn("--exp 3", body["prompt"]) + self.assertEqual(len(result), 4) + + asyncio.run(_run()) + + def test_draft_accepts_non_four_images(self): + fake_images = [Image.new("RGB", (24, 512), color=0)] + + async def _run(): + client = CLIENT.MjImageClient( + base_url="https://example.invalid", + api_key="test-key", + ) + with patch( + "comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls", + new=AsyncMock(return_value=[]), + ), patch( + "comfyui_o1key.clients.mj_image_client.submit_async_image_task", + new=AsyncMock(return_value="task_mj_draft"), + ) as submit_mock, patch( + "comfyui_o1key.clients.mj_image_client.poll_async_image_task", + new=AsyncMock(return_value={"status": "SUCCESS"}), + ), patch( + "comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task", + new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)), + ): + result = await client.generate_async( + session=object(), + prompt="drafty", + draft=True, + log_task_success=False, + log_downloads=False, + ) + body = submit_mock.await_args.args[3] + self.assertIn("--draft", body["prompt"]) + self.assertEqual(len(result), 1) + + asyncio.run(_run()) + + def test_non_draft_still_rejects_non_four(self): + fake_images = [Image.new("RGB", (32, 32), color=1) for _ in range(2)] + + async def _run(): + client = CLIENT.MjImageClient( + base_url="https://example.invalid", + api_key="test-key", + ) + with patch( + "comfyui_o1key.clients.mj_image_client.upload_images_to_temp_urls", + new=AsyncMock(return_value=[]), + ), patch( + "comfyui_o1key.clients.mj_image_client.submit_async_image_task", + new=AsyncMock(return_value="task_mj_two"), + ), patch( + "comfyui_o1key.clients.mj_image_client.poll_async_image_task", + new=AsyncMock(return_value={"status": "SUCCESS"}), + ), patch( + "comfyui_o1key.clients.mj_image_client.parse_completed_async_image_task", + new=AsyncMock(return_value=({"status": "SUCCESS"}, fake_images)), + ): + with self.assertRaisesRegex(RuntimeError, "应返回 4 张图"): + await client.generate_async( + session=object(), + prompt="two", + draft=False, + log_task_success=False, + log_downloads=False, + ) + + asyncio.run(_run()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_o1key_image_generator.py b/tests/test_o1key_image_generator.py index 94be44b..4e65704 100644 --- a/tests/test_o1key_image_generator.py +++ b/tests/test_o1key_image_generator.py @@ -20,6 +20,20 @@ COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR) sys.path.insert(0, COMFY_ROOT) sys.path.insert(0, CUSTOM_NODES_DIR) +import types as _types +# Avoid package-wide node registry (CUDA probe) in the portable CPU torch build. +_plugin = _types.ModuleType("comfyui_o1key") +_plugin.__path__ = [PLUGIN_DIR] +sys.modules["comfyui_o1key"] = _plugin +for _child in ("nodes", "utils", "clients"): + _mod = _types.ModuleType(f"comfyui_o1key.{_child}") + _mod.__path__ = [os.path.join(PLUGIN_DIR, _child)] + sys.modules[_mod.__name__] = _mod +_model_management = _types.ModuleType("comfy.model_management") +_model_management.processing_interrupted = lambda: False +_model_management.InterruptProcessingException = RuntimeError +sys.modules[_model_management.__name__] = _model_management + from comfy_api.latest import io # noqa: E402 from comfyui_o1key.clients.gpt_image_client import GptImageClient # noqa: E402 from comfyui_o1key.nodes.o1key_image_generator import ( # noqa: E402 @@ -29,9 +43,11 @@ from comfyui_o1key.nodes.o1key_image_generator import ( # noqa: E402 _parse_upload_manifest, ) from comfyui_o1key.utils.image_utils import ( # noqa: E402 + IMAGE_BATCH_MODE_ALIASES, IMAGE_BATCH_MODE_CARTESIAN, IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_SINGLE_REFERENCES, + IMAGE_BATCH_MODES, expand_image_generation_tasks, pil_to_tensor, tensor_to_pil, @@ -55,15 +71,24 @@ class O1keyImageGeneratorTests(unittest.TestCase): "Nano Banana 2.1", "Nano Banana 2", "Nano Banana Pro", - "gpt-image-2", + "gpt-image-2.6-sunburst", + "gpt-image-2.6-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare", + "gpt-image-2", "Seedream 5.0 Pro", - "Nano Banana 2 Lite", - "Nano Banana", ], ) + schema = O1keyImageGenerator.define_schema() + complexity_input = next(item for item in schema.inputs if item.id == "复杂度") + self.assertEqual(list(complexity_input.options), ["高", "中", "低"]) + self.assertEqual(complexity_input.default, "高") + quality_input = next(item for item in schema.inputs if item.id == "质量") + self.assertEqual(list(quality_input.options)[-2:], ["超高", "最高"]) + format_input = next(item for item in schema.inputs if item.id == "输出格式") + self.assertEqual(list(format_input.options), ["jpeg", "png", "webp", "svg", "gif"]) + def test_schema_is_panel_node_with_image_output(self): schema = O1keyImageGenerator.define_schema() schema.validate() @@ -91,7 +116,7 @@ class O1keyImageGeneratorTests(unittest.TestCase): "宽高比", "生图数量", "seed", "参考图清单", "质量", "输出格式", "蒙版清单", "缩放图片", "背景", "批量出图", "批量模式", "模特图清单", - "命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", + "命名规则", "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms", ], ) count_input = next(item for item in schema.inputs if item.id == "生图数量") @@ -100,21 +125,25 @@ class O1keyImageGeneratorTests(unittest.TestCase): model_input = next(item for item in schema.inputs if item.id == "模型") self.assertEqual(model_input.default, "Nano Banana 2.1") self.assertIn("gpt-image-2", model_input.options) + self.assertIn("gpt-image-2.6-sunburst", model_input.options) + self.assertIn("gpt-image-2.6-flare", model_input.options) self.assertIn("gpt-image-2.5-sunburst", model_input.options) self.assertIn("gpt-image-2.5-flare", model_input.options) self.assertIn("Seedream 5.0 Pro", model_input.options) + self.assertNotIn("Nano Banana 2 Lite", model_input.options) + self.assertNotIn("Nano Banana", model_input.options) thinking_input = next(item for item in schema.inputs if item.id == "思考等级") self.assertEqual(thinking_input.options, ["低", "高"]) - self.assertEqual(thinking_input.default, "低") + self.assertEqual(thinking_input.default, "高") resolution_input = next(item for item in schema.inputs if item.id == "分辨率") self.assertEqual(resolution_input.options[0], "智能") self.assertEqual(resolution_input.default, "智能") resize_input = next(item for item in schema.inputs if item.id == "缩放图片") self.assertEqual(resize_input.options, ["不缩放", "智能缩放"]) - self.assertEqual(resize_input.default, "不缩放") + self.assertEqual(resize_input.default, "智能缩放") self.assertNotIn("色彩纠正", [item.id for item in schema.inputs]) format_input = next(item for item in schema.inputs if item.id == "输出格式") - self.assertEqual(format_input.options, ["jpeg", "png", "webp"]) + self.assertEqual(format_input.options, ["jpeg", "png", "webp", "svg", "gif"]) self.assertEqual(format_input.default, "jpeg") background_input = next(item for item in schema.inputs if item.id == "背景") self.assertEqual(background_input.options, ["auto", "transparent", "opaque"]) @@ -122,6 +151,8 @@ class O1keyImageGeneratorTests(unittest.TestCase): self.assertNotIn("内容审查强度", [item.id for item in schema.inputs]) quality_input = next(item for item in schema.inputs if item.id == "质量") self.assertEqual(quality_input.options[-2:], ["超高", "最高"]) + seed_input = next(item for item in schema.inputs if item.id == "seed") + self.assertEqual(seed_input.display_name, "种子") prompt_input = next(item for item in schema.inputs if item.id == "prompt") self.assertEqual(prompt_input.display_name, "提示词") self.assertTrue(prompt_input.socketless) @@ -150,9 +181,7 @@ class O1keyImageGeneratorTests(unittest.TestCase): self.assertEqual(save_format_input.default, "原始") location_input = next(item for item in schema.inputs if item.id == "保存位置") self.assertEqual(location_input.default, "") - search_input = next(item for item in schema.inputs if item.id == "在线搜索") - self.assertEqual(search_input.options, ["关闭", "打开"]) - self.assertEqual(search_input.default, "关闭") + self.assertNotIn("在线搜索", [item.id for item in schema.inputs]) def test_batch_task_expansion_covers_group_and_cartesian_pairing(self): grouped = expand_image_generation_tasks( @@ -213,6 +242,39 @@ class O1keyImageGeneratorTests(unittest.TestCase): self.assertEqual(len(fifty_single_references), 50) self.assertEqual(fifty_single_references[-1]["reference_indices"], (49,)) + def test_retired_batch_mode_labels_keep_their_pairing(self): + # Labels shipped before the rename must expand exactly like the current ones. + self.assertEqual(len(IMAGE_BATCH_MODE_ALIASES), 3) + for retired, current in IMAGE_BATCH_MODE_ALIASES.items(): + with self.subTest(retired=retired): + retired_tasks = expand_image_generation_tasks( + "套用", + 2, + batch_enabled=True, + batch_mode=retired, + reference_count=3, + model_reference_count=4, + ) + current_tasks = expand_image_generation_tasks( + "套用", + 2, + batch_enabled=True, + batch_mode=current, + reference_count=3, + model_reference_count=4, + ) + self.assertEqual(retired_tasks, current_tasks) + + def test_batch_mode_labels_are_industry_neutral(self): + self.assertEqual( + IMAGE_BATCH_MODES, + ( + "整组素材→多个目标", + "每张素材×每张目标", + "每张素材单独出图", + ), + ) + def test_reference_limit_is_ten(self): accepted = [ {"name": f"{index}.png", "subfolder": "", "type": "input"} @@ -341,7 +403,6 @@ class O1keyImageGeneratorTests(unittest.TestCase): seed=42, 参考图清单="[]", 缩放图片="智能缩放", - 在线搜索="打开", )) self.assertIs(result[0], image) @@ -350,10 +411,10 @@ class O1keyImageGeneratorTests(unittest.TestCase): self.assertEqual(execute.call_args.kwargs["生图数量"], 2) self.assertEqual(execute.call_args.kwargs["参考图组"], {}) self.assertEqual(execute.call_args.kwargs["缩放图片"], "智能缩放") - self.assertIs(execute.call_args.kwargs["_o1key_google_search"], True) + self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False) self.assertIs(execute.call_args.kwargs["_o1key_unlimited_downloads"], True) - def test_online_search_is_ignored_for_other_models(self): + def test_google_search_is_never_requested(self): image = torch.zeros((1, 8, 8, 3), dtype=torch.float32) with patch( "comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute", @@ -363,12 +424,11 @@ class O1keyImageGeneratorTests(unittest.TestCase): prompt="一只宇航猫", 模型="Nano Banana Pro", 分辨率="2K", - 在线搜索="打开", )) self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False) - def test_default_model_delegates_nano_banana_21_with_search_and_thinking(self): + def test_default_model_delegates_nano_banana_21_with_thinking(self): image = torch.zeros((1, 8, 8, 3), dtype=torch.float32) with patch( "comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute", @@ -376,13 +436,13 @@ class O1keyImageGeneratorTests(unittest.TestCase): ) as execute: result = asyncio.run(O1keyImageGenerator.execute( prompt="test", 模型线路="直连", 思考等级="高", - 分辨率="4K", 宽高比="1:8", 在线搜索="打开", + 分辨率="4K", 宽高比="1:8", )) self.assertIs(result[0], image) self.assertEqual(execute.call_args.kwargs["模型"], "Nano Banana 2.1") self.assertEqual(execute.call_args.kwargs["模型线路"], "直连") self.assertEqual(execute.call_args.kwargs["思考等级"], "高") - self.assertIs(execute.call_args.kwargs["_o1key_google_search"], True) + self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False) def test_error_wrappers_apply_to_every_model_family(self): raw = ( @@ -491,22 +551,24 @@ class O1keyImageGeneratorTests(unittest.TestCase): ): result = asyncio.run(O1keyImageGenerator.execute( prompt="一只宇航猫", - 模型="gpt-image-2.5-sunburst", + 模型="gpt-image-2.6-sunburst", 模型线路="畅速", 分辨率="2K", 宽高比="16:9", 生图数量=4, 质量="最高", + 复杂度="中", 输出格式="webp", 背景="transparent", 缩放图片="智能缩放", )) self.assertEqual(tuple(result[0].shape), (4, 4, 6, 3)) + self.assertTrue(all(call["complexity"] == "medium" for call in calls)) self.assertEqual(len(calls), 4) self.assertGreater(maximum_active, 1) self.assertTrue(all(call["n"] == 1 for call in calls)) - self.assertTrue(all(call["model"] == "gpt-image-2.5-sunburst-sp" for call in calls)) + self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sp" for call in calls)) self.assertTrue(all(call["special_price_parallel"] is False for call in calls)) self.assertTrue(all(call["size"] == "3648x2048" for call in calls)) self.assertTrue(all(call["quality"] == "max" for call in calls)) @@ -515,6 +577,75 @@ class O1keyImageGeneratorTests(unittest.TestCase): self.assertTrue(all("moderation" not in call for call in calls)) self.assertTrue(all(call["resize_mode"] == "智能缩放" for call in calls)) + def test_gpt_26_gif_sends_frame_fields_and_rejects_edit(self): + calls = [] + + class FakeClient: + def __init__(self): + self.base_url = "" + self.response_log_enabled = True + self.poll_log_enabled = True + + async def generate_image_async(self, **kwargs): + calls.append(kwargs) + return [Image.new("RGB", (6, 4), "red")] + + @staticmethod + def _pil_list_to_tensor(images): + return torch.zeros((len(images), 4, 6, 3), dtype=torch.float32) + + with ( + patch( + "comfyui_o1key.nodes.o1key_image_generator.GptImageClient", + FakeClient, + ), + patch( + "comfyui_o1key.nodes.o1key_image_generator.get_base_url_by_route", + return_value="https://example.invalid", + ), + ): + result = asyncio.run(O1keyImageGenerator.execute( + prompt="一只宇航猫", + 模型="gpt-image-2.6-flare", + 模型线路="畅速", + 分辨率="智能", + 宽高比="1:1", + 生图数量=1, + 质量="自动", + 复杂度="低", + 输出格式="gif", + 帧数=12, + 帧时长ms=205, + 背景="auto", + 缩放图片="不缩放", + )) + + self.assertEqual(tuple(result[0].shape), (1, 4, 6, 3)) + self.assertEqual(calls[0]["output_format"], "gif") + self.assertEqual(calls[0]["frame_count"], 12) + self.assertEqual(calls[0]["frame_duration_ms"], 200) + self.assertEqual(calls[0]["complexity"], "low") + + fake_ref = torch.zeros((1, 8, 8, 3), dtype=torch.float32) + with ( + patch( + "comfyui_o1key.nodes.o1key_image_generator._load_reference_tensors", + return_value={0: fake_ref}, + ), + self.assertRaisesRegex(ValueError, "纯文生图"), + ): + asyncio.run(O1keyImageGenerator.execute( + prompt="一只宇航猫", + 模型="gpt-image-2.6-sunburst", + 模型线路="畅速", + 分辨率="智能", + 宽高比="1:1", + 生图数量=1, + 质量="自动", + 输出格式="svg", + 参考图清单='[{"name":"a.png","subfolder":"","type":"input"}]', + )) + def test_seedream_direct_execution_sends_exact_size_and_output_format(self): calls = [] session = object() diff --git a/tests/test_o1key_image_generator_frontend.mjs b/tests/test_o1key_image_generator_frontend.mjs index 75feddf..10c4e05 100644 --- a/tests/test_o1key_image_generator_frontend.mjs +++ b/tests/test_o1key_image_generator_frontend.mjs @@ -84,10 +84,18 @@ class Element { this.disabled = false; this.listeners = new Map(); this.dataset = {}; + this.parentElement = null; + this.offsetWidth = 0; + this.offsetHeight = 0; + } + append(...items) { this.adopt(items); this.children.push(...items); } + prepend(...items) { this.adopt(items); this.children.unshift(...items); } + replaceChildren(...items) { this.adopt(items); this.children = [...items]; } + adopt(items) { + for (const item of items) { + if (item && typeof item === "object") item.parentElement = this; + } } - append(...items) { this.children.push(...items); } - prepend(...items) { this.children.unshift(...items); } - replaceChildren(...items) { this.children = [...items]; } contains(element) { return this === element || this.children.some(child => child.contains?.(element)); } addEventListener(type, listener) { this.listeners.set(type, listener); } setAttribute(name, value) { this[name] = value; } @@ -235,12 +243,46 @@ const setStatus = vm.runInContext("setStatus", context); const buildPanel = vm.runInContext("buildPanel", context); const restorePanelFromWidgets = vm.runInContext("restorePanelFromWidgets", context); const serializeGeneratorWidgets = vm.runInContext("serializeGeneratorWidgets", context); +const applyNativeParameterOrder = vm.runInContext("applyNativeParameterOrder", context); +const serializedWidgetNames = vm.runInContext("GENERATOR_SERIALIZED_WIDGETS", context); +const generatorExtraHeight = vm.runInContext("generatorExtraHeight", context); +const setGeneratorExtraHeight = vm.runInContext("setGeneratorExtraHeight", context); +const generatorPanelMinHeight = vm.runInContext("generatorPanelMinHeight", context); +const nextGeneratorExtra = vm.runInContext("nextGeneratorExtra", context); +const syncPanelExtraDomHeight = vm.runInContext("syncPanelExtraDomHeight", context); const makeDropdown = vm.runInContext("makeDropdown", context); const isGeneratedSeedControl = vm.runInContext("isGeneratedSeedControl", context); +const generatorSeed = vm.runInContext("generatorSeed", context); const hideBackendWidgets = vm.runInContext("hideBackendWidgets", context); +const installNativeParameterBridge = vm.runInContext("installNativeParameterBridge", context); +const syncNativeParameterToPanel = vm.runInContext("syncNativeParameterToPanel", context); const queueGeneration = vm.runInContext("queueGeneration", context); const modelOptions = vm.runInContext("MODEL_OPTIONS", context); +const normalizeUnifiedModel = vm.runInContext("normalizeUnifiedModel", context); +const normalizeGptComplexityLabel = vm.runInContext("normalizeGptComplexityLabel", context); +const gptComplexityOptions = vm.runInContext("GPT_COMPLEXITY_OPTIONS", context); const routeOptions = vm.runInContext("ROUTES", context); + +{ + assert.equal(modelOptions.some((option) => option.value === "Nano Banana 2 Lite"), false); + assert.equal(modelOptions.some((option) => option.value === "Nano Banana"), false); + assert.equal(normalizeUnifiedModel("Nano Banana 2 Lite"), "Nano Banana 2"); + assert.equal(normalizeUnifiedModel("Nano Banana"), "Nano Banana 2"); + assert.equal(normalizeUnifiedModel("Nano Banana 2.1"), "Nano Banana 2.1"); +} + +{ + assert.deepEqual( + JSON.parse(JSON.stringify(gptComplexityOptions.map((item) => item.value))), + ["高", "中", "低"], + ); + assert.equal(normalizeGptComplexityLabel("high"), "高"); + assert.equal(normalizeGptComplexityLabel("medium"), "中"); + assert.equal(normalizeGptComplexityLabel("low"), "低"); + assert.equal(normalizeGptComplexityLabel("高"), "高"); + assert.equal(normalizeGptComplexityLabel(undefined), "高"); +} + const maxReferences = vm.runInContext("MAX_REFERENCES", context); const maxRequestReferences = vm.runInContext("MAX_REQUEST_REFERENCES", context); const referenceLimit = vm.runInContext("referenceLimit", context); @@ -250,6 +292,13 @@ const syncGptOutputOptions = vm.runInContext("syncGptOutputOptions", context); const optimizePrompt = vm.runInContext("optimizePrompt", context); const applyGeneratorDefaultSize = vm.runInContext("applyGeneratorDefaultSize", context); const createSaveNodeForBatch = vm.runInContext("createSaveNodeForBatch", context); +const nextHorizontalSaveNodePos = vm.runInContext("nextHorizontalSaveNodePos", context); +const measureNodeExtent = vm.runInContext("measureNodeExtent", context); +const generatorMinimumHeight = vm.runInContext("generatorMinimumHeight", context); +const isVueNodesEnabled = vm.runInContext("isVueNodesEnabled", context); +const SAVE_NODE_LAYOUT_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_GAP_X", context); +const SAVE_NODE_LAYOUT_ORIGIN_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_ORIGIN_GAP_X", context); +const SAVE_NODE_LAYOUT_SIZE = vm.runInContext("SAVE_NODE_LAYOUT_SIZE", context); const acquireSaveNodeForBatch = vm.runInContext("acquireSaveNodeForBatch", context); const acquireLayerSaveNodeForBatch = vm.runInContext("acquireLayerSaveNodeForBatch", context); const splitLayerSaveResults = vm.runInContext("splitLayerSaveResults", context); @@ -366,13 +415,12 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(isGeneratedSeedControl(prefixedGeneratedControl), true); assert.equal(isGeneratedSeedControl(unrelatedControl), false); hideBackendWidgets(node); - assert.equal(seed.hidden, true); - assert.equal(generatedControl.hidden, true); - assert.equal(generatedControl.options.hidden, true); - const hiddenSize = generatedControl.computeSize(); - assert.equal(hiddenSize[0], 0); - assert.equal(hiddenSize[1], -4); - assert.equal(prefixedGeneratedControl.hidden, true); + assert.equal(seed.hidden, false, "The seed row stays a native widget"); + assert.equal(seed.options.hidden, false); + assert.equal(generatedControl.hidden, false, "The native 生成后控制 row stays visible next to seed"); + assert.equal(generatedControl.serialize, false, "生成后控制 never enters widgets_values"); + assert.equal(prefixedGeneratedControl.hidden, false); + assert.equal(prefixedGeneratedControl.serialize, false); assert.equal(unrelatedControl.hidden, undefined); } @@ -380,12 +428,12 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { const names = [ "prompt", "模型", "模型线路", "思考等级", "分辨率", "宽高比", "生图数量", "seed", "参考图清单", "质量", "输出格式", "蒙版清单", "缩放图片", "背景", "批量出图", - "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", + "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms", ]; const values = [ "saved panel prompt", "Nano Banana 2.1", "专线", "高", "2K", "1:8", "4", 123, "[]", "自动", "jpeg", "{}", "不缩放", "auto", false, - "一组搭配+多模特", "[]", "自定义前缀", "kept-prefix", "原始", "kept-location", "打开", false, + "整组素材→多个目标", "[]", "自定义前缀", "kept-prefix", "原始", "kept-location", false, "中", 9, 200, ]; const widgets = names.map((name, index) => ({ name, value: values[index], options: {} })); const node = { @@ -404,18 +452,52 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(node._o1igPanel, panel); assert.equal(node.widgets.length, count); assert.equal(panel.className, "o1ig-panel"); - assert.equal(node.widgets.length, names.length + 1, "Keep one panel rather than appending native action rows"); - assert.deepEqual(node.widgets.slice(0, names.length).map(widget => widget.name), names); + assert.equal(node.widgets.length, names.length + 2, "Keep one panel and one action bar without duplicating backend parameters"); + assert.equal(node.widgets[0].name, "o1key_image_generator_panel", "Place the custom prompt panel before native LiteGraph parameters"); + assert.equal(node.widgets.at(-1).name, "o1key_image_generator_actions", "Pin the action bar under every native parameter row"); + assert.equal(widgets.find(widget => widget.name === "模型").hidden, false, "Native model widget remains visible"); + assert.equal(widgets.find(widget => widget.name === "prompt").hidden, true, "Prompt stays in the custom panel"); + assert.equal(widgets.find(widget => widget.name === "seed").hidden, false, "The seed row is the native widget"); + const displayOrder = [ + "prompt", "批量出图", "批量模式", + ...names.filter(name => !["prompt", "批量出图", "批量模式"].includes(name)), + ]; + assert.deepEqual( + node.widgets + .filter(widget => !["o1key_image_generator_panel", "o1key_image_generator_actions"].includes(widget.name)) + .map(widget => widget.name), + displayOrder, + "批量出图 and 批量模式 render above 模型", + ); + assert.deepEqual( + JSON.parse(JSON.stringify(serializedWidgetNames)), + names, + "widgets_values keeps the backend schema order no matter how the rows are displayed", + ); assert.equal(node._o1igPrompt.tagName, "TEXTAREA"); assert.equal(node._o1igGenerate.tagName, "BUTTON"); assert.equal(node._o1igGenerate.className, "o1ig-generate"); - assert.equal(panel.children.at(-1), node._o1igGenerate, "Start generation stays at the bottom of the panel"); + assert.equal(node._o1igActions.className, "o1ig-actions"); + assert.equal(node._o1igActions.children.at(-1), node._o1igGenerate, "Start generation stays at the bottom of the node"); + assert.equal(node._o1igPanel.children.includes(node._o1igGenerate), false, "The generate button left the prompt panel"); + assert.equal(node._o1igActions.children[0], node._o1igStatus, "Status line stays above the generate button"); + const parameterFields = [...node._o1igToolbar.children]; + assert.ok(parameterFields.length > 0); + assert.ok(parameterFields.every(field => String(field.className).includes("o1ig-field-inline-label"))); + const modelField = node._o1igToolbar.children.find(child => String(child.className).includes("o1ig-field-inline-label")); + assert.ok(modelField); + assert.equal(modelField.children[0].textContent, "模型"); + assert.equal(modelField.children[1], node._o1igModel); const promptWrap = panel.children.find(child => child.className === "o1ig-prompt-wrap"); assert.ok(promptWrap.children.includes(node._o1igPromptOptimize), "AI writing remains inside the prompt area"); - const seedField = node._o1igToolbar.children.find(child => child.children[1]?.className === "o1ig-seed"); - assert.equal(seedField.children[1].children[0], node._o1igSeed); - assert.equal(seedField.children[1].children[1].title, "随机种子"); - assert.ok(node._o1igReferenceHeader.contains(node._o1igAdd)); + assert.equal(node._o1igSeed, undefined, "The standalone seed row is gone"); + assert.equal(node._o1igAdd, undefined, "The header upload button is gone; the add card owns the picker"); + assert.equal(node._o1igModelAdd, undefined); + const referenceActions = node._o1igReferenceHeader.children.at(-1); + assert.equal(referenceActions.className, "o1ig-asset-actions"); + assert.equal(referenceActions.children.length, 1, "画布取图 is the only header action"); + assert.equal(referenceActions.children[0], node._o1igCanvasPick); + assert.ok(node._o1igReferenceInput, "The hidden picker input lives beside the track"); assert.ok(node._o1igReferenceHeader.contains(node._o1igCanvasPick)); assert.equal(node._o1igRefs.children[0].className, "o1ig-empty-reference"); node._o1igBatchToggle.dispatch("click"); @@ -423,25 +505,127 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(node._o1igModelAssets.classList.contains("visible"), true); node._o1igBatchToggle.dispatch("click"); assert.equal(node._o1igBatchEnabled, false); - const computeSize = widgets[0].computeSize; - widgets[0].options = {};widgets[0].hidden = false; + const promptWidget = widgets.find(widget => widget.name === "prompt"); + const computeSize = promptWidget.computeSize; + promptWidget.options = {};promptWidget.hidden = false; restorePanelFromWidgets(node); - assert.equal(widgets[0].options.hidden, true, "Keep backend fields hidden after a renderer switch"); - assert.equal(widgets[0].computeSize, computeSize); + assert.equal(promptWidget.options.hidden, true, "Keep backend fields hidden after a renderer switch"); + assert.equal(promptWidget.computeSize, computeSize); assert.equal(node._o1igModel.value, "Nano Banana 2.1"); - assert.equal(node._o1igSeed.value, "123"); + assert.equal(generatorSeed(node), 123); assert.equal(node._o1igFilenamePrefix.value, "kept-prefix"); assert.equal(node._o1igSaveLocation.value, "kept-location"); const saved = {};serializeGeneratorWidgets(node, saved); assert.equal(saved.widgets_values.length, names.length); + assert.deepEqual( + JSON.parse(JSON.stringify(saved.widgets_values)), + values, + "Saved values follow the schema order, not the display order", + ); assert.equal(saved.widgets_values[7], 123); assert.equal(saved.widgets_values[18], "kept-prefix"); assert.equal(saved.widgets_values[20], "kept-location"); + assert.equal(saved.widgets_values[22], "中"); + assert.equal(node._o1igComplexity.value, "中"); + // Manual resize is remembered as a delta, so dropping rows still shrinks the node. + assert.equal(generatorExtraHeight(node), 0); + setGeneratorExtraHeight(node, 240); + assert.equal(node.properties.o1keyPanelExtraHeight, 240); + assert.equal(generatorExtraHeight(node), 240); + setGeneratorExtraHeight(node, -80); + assert.equal(generatorExtraHeight(node), 0, "A resize below the content height keeps no gap"); + // A width drag moves the pointer horizontally only: the node height changes on its own and + // must never be folded into the dragged-out height (that fed back into a runaway growth). + const dragAnchor = { height: 1000, extra: 240, pointerY: 400 }; + assert.equal( + nextGeneratorExtra(dragAnchor, 400, 276, 1), + null, + "A still pointer means the resize is not vertical, so the panel height stays put", + ); + assert.equal(nextGeneratorExtra(dragAnchor, 470, 320, 1), 310, "A vertical drag follows the pointer"); + assert.equal( + nextGeneratorExtra(dragAnchor, 470, 320, 0.9), + 240 + 70 / 0.9, + "Pointer movement is converted from screen pixels to node pixels", + ); + assert.equal( + nextGeneratorExtra({ height: 1000, extra: 100, pointerY: 0 }, 0, 60, 1), + 160, + "Without a pointer anchor the node height delta is the only signal", + ); + delete node.properties.o1keyPanelExtraHeight; + applyNativeParameterOrder(node); + assert.deepEqual( + node.widgets.filter(widget => ["prompt", "批量出图", "批量模式", "模型"].includes(widget.name)).map(widget => widget.name), + ["prompt", "批量出图", "批量模式", "模型"], + "Applying the display order twice keeps 批量出图 above 模型", + ); + + // The dragged-out height must live on the panel (grid rows follow min-content), so the + // prompt area grows and no slack is left for the action bar. + for (const child of panel.children) child.dataset.o1igHeight = "50"; + const stackedHeight = panel.children.length * 50 + (panel.children.length - 1) * 8 + 18; + const basePanelMin = generatorPanelMinHeight(node); + assert.equal(basePanelMin, stackedHeight + 20, "Panel min height follows the stacked children"); + setGeneratorExtraHeight(node, 120); + assert.equal(generatorPanelMinHeight(node), basePanelMin + 120, "Dragged-out height joins the panel min height"); + syncPanelExtraDomHeight(node); + assert.ok(!node._o1igPanel.style.minHeight, "The canvas layout owns the panel height"); + LiteGraph.vueNodesMode = true; + syncPanelExtraDomHeight(node); + assert.equal(node._o1igPanel.style.minHeight, `${stackedHeight + 120}px`, "Vue nodes grow the panel by the dragged height"); + LiteGraph.vueNodesMode = false; + setGeneratorExtraHeight(node, 0); + syncPanelExtraDomHeight(node); + assert.ok(!node._o1igPanel.style.minHeight, "Clearing the drag drops the inline panel height"); + for (const child of panel.children) delete child.dataset.o1igHeight; + const nativeSeed = widgets.find(widget => widget.name === "seed"); + nativeSeed.callback = function (value) { this.value = value; }; + delete nativeSeed.__o1igNativeParameterBridge; + installNativeParameterBridge(node); + nativeSeed.value = 987; + nativeSeed.callback.call(nativeSeed, 987); + assert.equal(generatorSeed(node), 987, "The native seed widget is the value source"); + const nativeBatchMode = widgets.find(widget => widget.name === "批量模式"); + syncNativeParameterToPanel(node, "批量出图", true); + assert.equal(nativeBatchMode.hidden, false, "Native batch mode appears when batch generation is enabled"); + syncNativeParameterToPanel(node, "批量出图", false); + assert.equal(nativeBatchMode.hidden, true, "Native batch mode hides when batch generation is disabled"); + const nativeModel = widgets.find(widget => widget.name === "模型"); + const nativeLayer = widgets.find(widget => widget.name === "图层拆分"); + nativeModel.value = "Seedream 5.0 Pro"; + syncNativeParameterToPanel(node, "模型", "Seedream 5.0 Pro"); + syncNativeParameterToPanel(node, "图层拆分", true); + assert.equal(node._o1igLayerDecomposition.value, "开启", "Native boolean layer control maps to the panel value"); + nativeModel.value = "Nano Banana 2.1"; + nativeLayer.value = false; + node._o1igModel.value = "gpt-image-2.6-flare"; + syncModelOptions(node); + assert.equal(node._o1igComplexityField.style.display, ""); + node._o1igComplexity.value = "低"; + node._o1igComplexity.dispatch("change"); + assert.equal(widgets.find(widget => widget.name === "复杂度").value, "低"); + restorePanelFromWidgets(node); + assert.equal(node._o1igComplexity.value, "低"); + // Restore the fixture before copy/paste checks below. + widgets.find(widget => widget.name === "复杂度").value = "中"; + restorePanelFromWidgets(node); // ComfyUI inserts this UI widget after seed. Its options.serialize flag // excludes API prompts, while LiteGraph restores using widget.serialize. function WorkflowGenerator() {} WorkflowGenerator.prototype.computeSize = () => [500, 1025]; + WorkflowGenerator.prototype.configure = function (info) { + // Mirrors the bundled LiteGraph: widgets_values is assigned by position over the + // serializable widgets, then onConfigure runs. + let index = 0; + for (const widget of this.widgets) { + if (widget.serialize === false) continue; + if (index >= info.widgets_values.length) break; + widget.value = info.widgets_values[index++]; + } + this.onConfigure?.(info); + }; await app.extension.beforeRegisterNodeDef(WorkflowGenerator, { name: "O1keyImageGenerator" }); const createWorkflowGenerator = (controlName) => { const generator = Object.assign(new WorkflowGenerator(), { @@ -468,14 +652,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { }; const pasteWorkflowGenerator = (data, controlName) => { const generator = createWorkflowGenerator(controlName); - let index = 0; - // Match the bundled LiteGraph configure loop, including UI widgets. - for (const widget of generator.widgets) { - if (widget.serialize === false) continue; - if (index >= data.widgets_values.length) break; - widget.value = data.widgets_values[index++]; - } - generator.onConfigure(data); + generator.configure(data); return generator; }; let workflowMigration; @@ -528,7 +705,11 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { const legacyGraph = { nodes: [{ type: "O1keyImageGenerator", widgets_values: legacyValues }] }; workflowMigration.beforeConfigureGraph(legacyGraph); workflowMigration.beforeConfigureGraph(legacyGraph); - assert.deepEqual(legacyValues, serialized.widgets_values); + assert.deepEqual( + JSON.parse(JSON.stringify(legacyValues)), + JSON.parse(JSON.stringify(serialized.widgets_values)), + "Migration is idempotent for the batch rows", + ); for (const data of [serialized, legacyGraph.nodes[0]]) { const pasted = pasteWorkflowGenerator(JSON.parse(JSON.stringify(data)), controlName); @@ -579,15 +760,20 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { graph, inputs: [], outputs: [{ links: [linkId] }], - widgets: [], - _o1igPrompt: { value: "", focus() {} }, + widgets: [{ name: "seed", value: "0", options: {} }], + _o1igPrompt: (() => { + const prompt = new Element("textarea"); + prompt.value = ""; + prompt.focus = () => {}; + prompt.parentElement = new Element("div"); + return prompt; + })(), _o1igModel: { value: "Nano Banana 2" }, _o1igRoute: { value: "畅速" }, _o1igThinking: { value: "低" }, _o1igResolution: { value: "智能" }, _o1igRatio: { value: "智能" }, _o1igCount: { value: "1" }, - _o1igSeed: { value: "0" }, _o1igReferences: [], _o1igModelReferences: [], _o1igMask: null, @@ -596,7 +782,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { _o1igResize: { value: "不缩放" }, _o1igBackground: { value: "auto" }, _o1igBatchEnabled: false, - _o1igBatchMode: { value: "一组搭配+多模特" }, + _o1igBatchMode: { value: "整组素材→多个目标" }, _o1igNamingRule: { value: "自定义前缀" }, _o1igFilenamePrefix: { value: "o1key" }, _o1igSaveFormat: { value: "原始" }, @@ -635,7 +821,11 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { await queueGeneration(generator); assert.deepEqual(queueCalls, []); - assert.equal(generator._o1igStatus.textContent, "请输入提示词"); + assert.equal(generator._o1igStatus.textContent, "", "An empty prompt raises no status wording"); + assert.ok( + generator._o1igPrompt.parentElement.classList.contains("invalid"), + "An empty prompt is pointed at on the field itself", + ); generator._o1igPrompt.value = "测试替换等待"; generator._o1igReplacing = new Map([[{}, "replacement.png"]]); @@ -1138,7 +1328,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { { const dropdown = makeDropdown(["1K", "2K"], "1K", "分辨率"); const trigger = dropdown.children[0]; - const selectedDescription = trigger.children[1]; const caret = trigger.children[trigger.children.length - 1]; const caretIcon = caret.children[0]; const caretPath = caretIcon.children[0]; @@ -1147,7 +1336,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(caretIcon.viewBox, "0 0 12 12"); assert.equal(caretPath.d, "M2.25 4.25 6 8l3.75-3.75"); assert.equal(caretPath["stroke-linecap"], "round"); - assert.equal(selectedDescription.textContent, ""); + assert.equal(trigger.children.length, 2); assert.equal(caret.textContent, ""); } @@ -1162,15 +1351,14 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { { model: "Nano Banana 2.1", description: "快速,批量", styled: true }, { model: "Nano Banana 2", description: "快速,批量", styled: true }, { model: "Nano Banana Pro", description: "高质量资产", styled: true }, - { model: "GPT Image 2", description: "高质量,编辑", styled: true }, - { model: "GPT Image 2.5 Sunburst", description: "最新,高质量", styled: true }, + { model: "GPT Image 2.6 Sunburst", description: "精修,细节还原", styled: true }, + { model: "GPT Image 2.6 Flare", description: "快速出图", styled: true }, + { model: "GPT Image 2.5 Sunburst", description: "高质量,细节", styled: true }, { model: "GPT Image 2.5 Flare", description: "快速,日常", styled: true }, + { model: "GPT Image 2", description: "高质量,编辑", styled: true }, { model: "Seedream 5.0 Pro", description: "高质量,参考图,分层", styled: true }, - { model: "Nano Banana 2 Lite", description: "快速,草稿", styled: true }, - { model: "Nano Banana", description: "快速,草稿", styled: true }, ]); assert.equal(dropdown._o1igValueLabel.textContent, "Nano Banana 2"); - assert.equal(dropdown._o1igValueDescription.textContent, "快速,批量"); assert.equal(dropdown._o1igTrigger.title, "Nano Banana 2 · 快速,批量"); } @@ -1232,7 +1420,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { const dropdown = makeDropdown(routeOptions, "直连", "模型线路"); assert.equal(dropdown.value, "直连"); assert.equal(dropdown._o1igValueLabel.textContent, "优质"); - assert.equal(dropdown._o1igValueDescription.textContent, "小贵"); assert.deepEqual( JSON.parse(JSON.stringify(dropdown._o1igOptions)), [ @@ -1250,7 +1437,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { { name: "宽高比", value: "智能" }, { name: "输出格式", value: "jpeg" }, { name: "背景", value: "auto" }, - { name: "在线搜索", value: "关闭" }, { name: "命名规则", value: "自定义前缀" }, { name: "filename_prefix", value: "catalog" }, { name: "格式", value: "webp" }, @@ -1267,12 +1453,12 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { _o1igCount: makeDropdown(["1", "2", "4", "9"], "1"), _o1igCountField: { style: {} }, _o1igThinkingField: { style: {} }, - _o1igOnlineSearch: makeDropdown(["关闭", "打开"], "关闭"), - _o1igOnlineSearchField: { style: {} }, _o1igLayerDecomposition: makeDropdown(["关闭", "开启"], "关闭"), _o1igLayerDecompositionField: { style: {} }, _o1igQuality: makeDropdown(["高", "中", "低", "自动"], "自动"), _o1igQualityField: { style: {} }, + _o1igComplexity: makeDropdown(["高", "中", "低"], "中"), + _o1igComplexityField: { style: {} }, _o1igOutputFormat: makeDropdown([ { value: "png", label: "PNG" }, { value: "webp", label: "WebP" }, @@ -1308,7 +1494,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { ); assert.equal(node._o1igResolution.value, "智能"); assert.equal(node._o1igThinkingField.style.display, ""); - assert.equal(node._o1igOnlineSearchField.style.display, ""); assert.equal(node._o1igQualityField.style.display, "none"); assert.equal(node._o1igOutputFormatField.style.display, "none"); assert.equal(node._o1igBackgroundField.style.display, "none"); @@ -1326,25 +1511,21 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { ); assert.equal(node._o1igRatio._o1igOptions.some(option => option.value === "1:8"), true); assert.equal(node._o1igThinkingField.style.display, ""); - assert.equal(node._o1igOnlineSearchField.style.display, ""); assert.equal(node._o1igSaveFormatField.style.display, ""); assert.equal(widgets.find((widget) => widget.name === "模型").value, "Nano Banana 2.1"); node._o1igModel.value = "Nano Banana 2 Lite"; syncModelOptions(node); - assert.equal(node._o1igResolution._o1igOptions.some((option) => option.value === "512"), true); - assert.equal(node._o1igThinkingField.style.display, "none"); - assert.equal(node._o1igOnlineSearchField.style.display, "none"); - assert.equal(node._o1igQualityField.style.display, "none"); - assert.equal(node._o1igResizeField.style.display, ""); - assert.equal(node._o1igMaskField.style.display, "none"); + assert.equal(node._o1igModel.value, "Nano Banana 2"); + assert.equal(widgets.find((widget) => widget.name === "模型").value, "Nano Banana 2"); + assert.equal(node._o1igResolution._o1igOptions.some((option) => option.value === "512"), false); + assert.equal(node._o1igThinkingField.style.display, ""); node._o1igModel.value = "Nano Banana Pro"; syncModelOptions(node); assert.equal(node._o1igResolution._o1igOptions.some((option) => option.value === "512"), false); assert.equal(node._o1igRatio._o1igOptions.some((option) => option.value === "1:8"), false); assert.equal(node._o1igThinkingField.style.display, "none"); - assert.equal(node._o1igOnlineSearchField.style.display, "none"); assert.equal(node._o1igQualityField.style.display, "none"); assert.equal(node._o1igResizeField.style.display, ""); assert.equal(node._o1igMaskField.style.display, "none"); @@ -1353,10 +1534,10 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { syncModelOptions(node); assert.deepEqual( JSON.parse(JSON.stringify(node._o1igResolution._o1igOptions.map((option) => option.value))), - ["智能", "1K"], + ["智能", "1K", "2K", "4K"], ); - assert.equal(node._o1igThinkingField.style.display, "none"); - assert.equal(node._o1igOnlineSearchField.style.display, "none"); + assert.equal(node._o1igModel.value, "Nano Banana 2"); + assert.equal(node._o1igThinkingField.style.display, ""); assert.equal(node._o1igQualityField.style.display, "none"); assert.equal(node._o1igResizeField.style.display, ""); assert.equal(node._o1igMaskField.style.display, "none"); @@ -1373,7 +1554,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { ); assert.equal(node._o1igRatioField.style.display, ""); assert.equal(node._o1igThinkingField.style.display, "none"); - assert.equal(node._o1igOnlineSearchField.style.display, "none"); assert.equal(node._o1igQualityField.style.display, ""); assert.equal(node._o1igOutputFormatField.style.display, ""); assert.equal(node._o1igBackgroundField.style.display, ""); @@ -1396,9 +1576,11 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { save_location: "project/session", naming_rule: "自定义前缀", }); - for (const model of ["gpt-image-2.5-sunburst", "gpt-image-2.5-flare"]) { + for (const model of ["gpt-image-2.5-sunburst", "gpt-image-2.5-flare", "gpt-image-2.6-sunburst", "gpt-image-2.6-flare"]) { node._o1igModel.value = model; syncModelOptions(node); + assert.equal(node._o1igComplexityField.style.display, model.startsWith("gpt-image-2.6-") ? "" : "none"); + assert.equal(node._o1igComplexity.value, "中"); assert.deepEqual( JSON.parse(JSON.stringify(node._o1igResolution._o1igOptions.map((option) => option.value))), ["智能", "1K", "2K", "4K"], @@ -1477,7 +1659,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { node._o1igModel.value = "Nano Banana 2"; syncModelOptions(node); assert.equal(node._o1igThinkingField.style.display, ""); - assert.equal(node._o1igOnlineSearchField.style.display, ""); assert.equal(node._o1igQualityField.style.display, "none"); assert.equal(node._o1igOutputFormatField.style.display, "none"); assert.equal(node._o1igBackgroundField.style.display, "none"); @@ -1681,6 +1862,12 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(first.properties.o1keyBatchIndex, 1); assert.equal(second.properties.o1keyBatchIndex, 2); assert.notDeepEqual(first.pos, second.pos); + // Horizontal equal spacing: first to the right of generator, second to the right of first. + assert.equal(first.pos[0], generator.pos[0] + generator.size[0] + SAVE_NODE_LAYOUT_ORIGIN_GAP_X); + assert.equal(first.pos[1], generator.pos[1] + 30); + assert.equal(second.pos[0], first.pos[0] + first.size[0] + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(second.pos[1], first.pos[1]); + assert.ok(second.pos[0] > first.pos[0]); beginGenerationBatch(generator, first); beginGenerationBatch(generator, second); @@ -2200,7 +2387,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { comfyClass: "O1keyImageGenerator", graph, widgets: [{ name: "seed", value: 0 }], - _o1igSeed: { value: "0" }, _o1igPrompt: { value: "甲\n---\n乙" }, }; graph.nodes.set(saveNode.id, saveNode); @@ -2218,7 +2404,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { prompt: "换装", imageCount: 1, batchEnabled: true, - batchMode: "一组搭配+多模特", + batchMode: "整组素材→多个目标", references: outfits.slice(0, 3), modelReferences: models, }); @@ -2229,7 +2415,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { prompt: "换装", imageCount: 1, batchEnabled: true, - batchMode: "全部搭配×全部模特", + batchMode: "每张素材×每张目标", references: outfits, modelReferences: models, }); @@ -2241,7 +2427,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { prompt: "换个动作", imageCount: 1, batchEnabled: true, - batchMode: "单图素材批量", + batchMode: "每张素材单独出图", references: outfits.slice(0, 3), modelReferences: models, }); @@ -2253,7 +2439,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { const groupedBadgeNode = { _o1igBatchEnabled: true, - _o1igBatchMode: { value: "一组搭配+多模特" }, + _o1igBatchMode: { value: "整组素材→多个目标" }, _o1igReferences: outfits.slice(0, 3), }; assert.deepEqual( @@ -2266,7 +2452,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { ); const cartesianBadgeNode = { _o1igBatchEnabled: true, - _o1igBatchMode: { value: "全部搭配×全部模特" }, + _o1igBatchMode: { value: "每张素材×每张目标" }, _o1igReferences: outfits, }; assert.equal(referenceBadgeDetails(cartesianBadgeNode, "references", 6).label, "图1"); @@ -2274,7 +2460,7 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.deepEqual( JSON.parse(JSON.stringify(referenceBadgeDetails({ _o1igBatchEnabled: true, - _o1igBatchMode: { value: "单图素材批量" }, + _o1igBatchMode: { value: "每张素材单独出图" }, }, "references", 1))), { label: "图1", title: "素材图2 · 作为单张参考图独立生成" }, ); @@ -2391,10 +2577,10 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { ); const referenceList = new Element("div"); - const addReference = new Element("button"); + const pickerInput = { clicks: 0, click() { this.clicks += 1; } }; renderReferenceRole({ _o1igRefs: referenceList, - _o1igAdd: addReference, + _o1igReferenceInput: pickerInput, _o1igReferences: [ { name: "large.png", subfolder: "product", type: "input" }, { name: "second.png", subfolder: "product", type: "input" }, @@ -2406,6 +2592,8 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { assert.equal(trailingUpload.className, "o1ig-empty-reference"); assert.equal(trailingUpload.children[1].textContent, "添加参考图"); assert.equal(trailingUpload.listeners.has("drop"), true); + trailingUpload.dispatch("click"); + assert.equal(pickerInput.clicks, 1, "尾部添加卡片直接打开文件选择器"); const uploadedImage = referenceList.children[0].children[0]; const editButton = referenceList.children[0].children[1]; assert.equal(editButton.className, "o1ig-edit"); @@ -2562,16 +2750,19 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { const summaryNode = { _o1igBatchEnabled: true, - _o1igBatchMode: { value: "一组搭配+多模特" }, + _o1igBatchMode: { value: "整组素材→多个目标" }, _o1igReferences: [], _o1igModelReferences: [], _o1igCount: { value: "2" }, _o1igPrompt: { value: "甲\n---\n乙" }, _o1igBatchSummary: new Element("div"), + _o1igBatchSummaryDetail: new Element("span"), + _o1igBatchSummaryTotal: new Element("span"), _o1igReferenceHint: new Element("span"), }; updateBatchSummary(summaryNode); - assert.equal(summaryNode._o1igBatchSummary.textContent, ""); + assert.equal(summaryNode._o1igBatchSummaryDetail.textContent, ""); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, ""); assert.equal(summaryNode._o1igBatchSummary.classList.contains("visible"), false); summaryNode._o1igModelReferences = models.slice(0, 2); updateBatchSummary(summaryNode); @@ -2580,24 +2771,49 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { updateBatchSummary(summaryNode); assert.equal(summaryNode._o1igBatchSummary.classList.contains("visible"), true); assert.equal( - summaryNode._o1igBatchSummary.textContent, - "1 组素材 × 2 个目标 = 2 个组合 × 每组 2 张 × 2 条提示词,共 8 张", + summaryNode._o1igBatchSummaryDetail.textContent, + "整组 3 张素材 × 2 个目标 = 2 组 · 每组 2 张 · 2 条提示词", ); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 8 张"); + summaryNode._o1igBatchMode.value = "每张素材×每张目标"; + updateBatchSummary(summaryNode); + assert.equal( + summaryNode._o1igBatchSummaryDetail.textContent, + "3 张素材 × 2 个目标 = 6 组 · 每组 2 张 · 2 条提示词", + ); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 24 张"); + summaryNode._o1igBatchMode.value = "每张素材单独出图"; + updateBatchSummary(summaryNode); + assert.equal( + summaryNode._o1igBatchSummaryDetail.textContent, + "3 张素材·各自独立 · 每组 2 张 · 2 条提示词", + ); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 12 张"); + // Retired labels still resolve to the current pairing rules. summaryNode._o1igBatchMode.value = "全部搭配×全部模特"; updateBatchSummary(summaryNode); - assert.equal( - summaryNode._o1igBatchSummary.textContent, - "3 个素材 × 2 个目标 = 6 个组合 × 每组 2 张 × 2 条提示词,共 24 张", - ); - summaryNode._o1igBatchMode.value = "单图素材批量"; + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 24 张"); + // 生图数量 and prompt edits refresh the same preview. + summaryNode._o1igBatchMode.value = "整组素材→多个目标"; + summaryNode._o1igCount.value = "1"; + summaryNode._o1igPrompt.value = "只有一条"; updateBatchSummary(summaryNode); assert.equal( - summaryNode._o1igBatchSummary.textContent, - "3 张素材(每张独立) × 每组 2 张 × 2 条提示词,共 12 张", + summaryNode._o1igBatchSummaryDetail.textContent, + "整组 3 张素材 × 2 个目标 = 2 组 · 每组 1 张", ); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 2 张"); + // Hiding must not detach the spans, otherwise the preview can never come back. + summaryNode._o1igReferences = []; + updateBatchSummary(summaryNode); + assert.equal(summaryNode._o1igBatchSummary.classList.contains("visible"), false); + assert.equal(summaryNode._o1igBatchSummaryDetail.textContent, ""); + summaryNode._o1igReferences = outfits.slice(0, 3); + updateBatchSummary(summaryNode); + assert.equal(summaryNode._o1igBatchSummaryTotal.textContent, "共 2 张"); const hintNode = { _o1igBatchEnabled: true, - _o1igBatchMode: { value: "一组搭配+多模特" }, + _o1igBatchMode: { value: "整组素材→多个目标" }, _o1igReferences: outfits.slice(0, 3), _o1igModelReferences: models.slice(0, 2), _o1igReferenceTitle: new Element("strong"), @@ -2606,18 +2822,22 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { }; updateBatchReferenceHint(hintNode); assert.equal(hintNode._o1igReferenceTitle.textContent, "素材图"); - assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 整组参与"); - assert.equal(hintNode._o1igModelHint.textContent, "2 张 · 每张目标图单独参与组合"); - hintNode._o1igBatchMode.value = "全部搭配×全部模特"; + assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 整组共用"); + assert.equal(hintNode._o1igModelHint.textContent, "2 张 · 每张单独参与组合"); + // 批量模式下轨道标题只保留名称,计数由预览行承担。 + assert.equal(hintNode._o1igReferenceHint.classList.contains("hidden"), true); + assert.equal(hintNode._o1igModelHint.classList.contains("hidden"), true); + hintNode._o1igBatchMode.value = "每张素材×每张目标"; updateBatchReferenceHint(hintNode); - assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 匹配时每张独立"); - hintNode._o1igBatchMode.value = "单图素材批量"; + assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 两两匹配"); + hintNode._o1igBatchMode.value = "每张素材单独出图"; updateBatchReferenceHint(hintNode); - assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 每张独立生成"); + assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 各自独立"); hintNode._o1igBatchEnabled = false; updateBatchReferenceHint(hintNode); assert.equal(hintNode._o1igReferenceTitle.textContent, "参考图"); assert.equal(hintNode._o1igReferenceHint.textContent, "3 张 · 最多 10 张"); + assert.equal(hintNode._o1igReferenceHint.classList.contains("hidden"), false, "普通模式保留张数提示"); initializeSaveSlots(saveNode, prompts.map((prompt, index) => ({ prompt, references: [{ @@ -2726,6 +2946,40 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { document._querySelector = null; } +{ + const generator = { pos: [100, 200], size: [500, 1025] }; + const firstPos = nextHorizontalSaveNodePos(generator, []); + assert.equal(firstPos[0], 100 + 500 + SAVE_NODE_LAYOUT_ORIGIN_GAP_X); + assert.equal(firstPos[1], 200 + 30); + const firstPeer = { pos: [700, 230], size: [300, 260] }; + const secondPos = nextHorizontalSaveNodePos(generator, [firstPeer]); + assert.equal(secondPos[0], 700 + 300 + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(secondPos[1], 230); + const secondPeer = { pos: [1050, 230], size: [407, 440] }; + const thirdPos = nextHorizontalSaveNodePos(generator, [firstPeer, secondPeer]); + assert.equal(thirdPos[0], 1050 + 407 + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(thirdPos[1], 230); + const blocking = { + pos: [700 + 300 + SAVE_NODE_LAYOUT_GAP_X, 230], + size: [...SAVE_NODE_LAYOUT_SIZE], + }; + const blockedPos = nextHorizontalSaveNodePos(generator, [firstPeer, blocking]); + assert.equal(blockedPos[0], blocking.pos[0] + blocking.size[0] + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(blockedPos[1], 230); + assert.equal(isVueNodesEnabled(), false); + assert.equal(generatorMinimumHeight({ _o1igModel: { value: "Nano Banana 2" } }), 1025); + assert.equal( + generatorMinimumHeight({ + _o1igModel: { value: "gpt-image-2" }, + _o1igBatchEnabled: true, + }), + 1300, + ); + assert.ok(generatorPanelMinHeight({ _o1igModel: { value: "Nano Banana 2" } }) >= 292); + assert.equal(measureNodeExtent({ pos: [1, 2], size: [0, 0] }).width, SAVE_NODE_LAYOUT_SIZE[0]); + assert.equal(measureNodeExtent({ pos: [1, 2], size: [410, 500] }).right, 411); +} + { const exactGridNode = { size: [407, 413], @@ -2855,7 +3109,6 @@ function createRecoveryNodes(batchId, generatorId, saveNodeId) { comfyClass: "O1keyImageGenerator", graph, widgets: [{ name: "seed", value: 0 }], - _o1igSeed: { value: "0" }, }; const saveNode = { id: 901, @@ -2912,25 +3165,33 @@ const savePanelSource = source.slice( assert.doesNotMatch(savePanelSource, /addDOMWidget/); assert.doesNotMatch(savePanelSource, /prefixWidget\.hidden = true/); assert.doesNotMatch(source, /installNativeMinimumSize\(nodeType, SAVE_NODE_LAYOUT_SIZE\)/); +assert.doesNotMatch(source, /batchIndex % 3/); +assert.match(source, /function nextHorizontalSaveNodePos\(/); +assert.match(source, /const SAVE_NODE_LAYOUT_GAP_X = 50/); +assert.match(source, /getMinHeight: \(\) => generatorPanelMinHeight\(node\)/); +assert.match(source, /Comfy\.VueNodes\.Enabled/); assert.match(source, /lucide--download.*lucide--refresh-cw/); assert.match(source, /--o1ig-surface:var\(--component-node-widget-background,var\(--comfy-input-bg\)\)/); assert.match(source, /o1ig-select-caret svg\{display:block;width:12px;height:12px/); assert.match(source, /const GENERATOR_DEFAULT_SIZE = \[560, 1035\]/); +assert.match(source, /const PROMPT_DEFAULT_HEIGHT = 106/); assert.doesNotMatch(source, /o1key-save-custom-prefix/); assert.match(source, /const GENERATOR_MIN_SIZE = \[500, 1025\]/); assert.match(source, /const GENERATOR_DENSE_MIN_HEIGHT = 1110/); assert.match(source, /const GENERATOR_BATCH_MIN_HEIGHT = 1215/); assert.match(source, /const GENERATOR_DENSE_BATCH_MIN_HEIGHT = 1300/); -assert.match(source, /\.o1ig-prompt-wrap\{[^\n]*height:auto;min-height:142px;flex:1 1 142px/); -assert.match(source, /\.o1ig-prompt\{[\s\S]*?min-height:142px;max-height:none;resize:none/); +assert.match(source, /\.o1ig-prompt-wrap\{[^\n]*flex:1 1 auto;height:auto;min-height:\$\{PROMPT_DEFAULT_HEIGHT\}px/); +assert.match(source, /\.o1ig-prompt\{[\s\S]*?min-height:\$\{PROMPT_DEFAULT_HEIGHT\}px;height:100%;max-height:none;resize:none/); assert.doesNotMatch(source, /isExternalPromptConnected|useExternalPrompt|o1ig-prompt-input-slot/); assert.match(source, /delete nodeData\.input\.optional\.external_prompt/); assert.doesNotMatch(source, /app\.queuePrompt\(0, 1, \[saveNode\.id\]\)/); assert.match(source, /\.o1ig-refs\{[\s\S]*?flex:0 0 109px[\s\S]*?min-height:109px/); assert.match(source, /\.o1ig-thumb\{[\s\S]*?flex:0 0 102px;height:102px/); assert.match(source, /\.o1ig-thumb img\{[\s\S]*?object-fit:contain;background:var\(--o1ig-surface\)/); -assert.match(source, /referenceActions\.append\(add, canvasPick\)/); -assert.match(source, /modelActions\.append\(modelAdd, modelCanvasPick\)/); +assert.match(source, /referenceActions\.append\(canvasPick\)/); +assert.match(source, /modelActions\.append\(modelCanvasPick\)/); +assert.doesNotMatch(source, /o1ig-add[\s\S]{0,400}?addLabel\.textContent = "上传"/, "头部不再有上传按钮"); +assert.match(source, /upload\.addEventListener\("click", \(\) => requestReferenceUpload\(node, role\)\)/); assert.match(source, /window\.o1keyCanvasImagePicker = Object\.freeze/); assert.equal(typeof context.window.o1keyCanvasImagePicker.open, "function"); assert.equal(context.window.o1keyCanvasImagePicker.readFile, readCanvasImageFile); @@ -2944,16 +3205,17 @@ assert.match(source, /\.o1ig-refs\.o1ig-reordering\{/); assert.match(source, /\.o1ig-thumb\.o1ig-drop-before\{transform:translateX\(7px\)/); assert.match(source, /\.o1ig-empty-reference:hover,\.o1ig-empty-reference\.drag\{/); assert.match(source, /\.o1ig-toolbar\{[^\n]*grid-template-columns:minmax\(0,1fr\)/); -assert.match(source, /\.o1ig-field\{display:grid;grid-template-columns:104px minmax\(0,1fr\)/); -assert.match(source, /makePanelSectionTitle\("画面描述"\)/); -assert.match(source, /makePanelSectionTitle\("生成参数"\)/); -assert.match(source, /makePanelSectionTitle\("保存设置"\)/); +assert.match(source, /\.o1ig-field-inline-label\{display:grid;grid-template-columns:104px minmax\(0,1fr\)/); +assert.doesNotMatch(source, /makePanelSectionTitle\("画面描述"\)/); +assert.doesNotMatch(source, /makePanelSectionTitle\("生成参数"\)/); +assert.doesNotMatch(source, /makePanelSectionTitle\("保存设置"\)/); assert.match(source, /filenamePrefixField\.classList\.add\("o1ig-field-wide"\)/); assert.match(source, /saveLocationField\.classList\.add\("o1ig-field-wide"\)/); assert.match(source, /o1ig-resize-warning\{display:none;grid-column:2;color:var\(--o1ig-muted\)/); assert.match(source, /o1ig-resize-warning\.visible\{display:block/); -assert.match(source, /o1ig-seed\{[\s\S]*grid-template-columns:minmax\(0,1fr\) 28px;gap:0/); -assert.match(source, /o1ig-seed button\{[\s\S]*border-left:1px solid/); +assert.doesNotMatch(source, /o1ig-seed\b/); +assert.doesNotMatch(source, /o1key_image_generator_seed/); +assert.match(source, /o1ig-actions\{[\s\S]*?display:flex;flex-direction:column;gap:7px;justify-content:flex-end/); assert.match(source, /className = "o1ig-prompt-optimize"/); assert.match(source, /className = "o1ig-prompt-optimize-status"/); assert.match(source, /promptOptimizeIcon\.textContent = "✨";[\s\S]*?promptOptimizeLabel\.textContent = "AI帮写";[\s\S]*?promptOptimize\.append\(promptOptimizeIcon, promptOptimizeLabel\)/); @@ -2962,11 +3224,12 @@ assert.match(source, /o1ig-prompt-optimize-icon\{[\s\S]*?font-size:15px/); assert.match(source, /o1ig-prompt-optimize-status\{[\s\S]*?right:112px[\s\S]*?max-width:calc\(100% - 128px\)/); assert.doesNotMatch(source, /o1ig-prompt-guide|promptGuide|updateBatchPromptGuide|描述示例/); assert.doesNotMatch(source, /先上传素材图和目标图|批量任务会在提交前显示总数/); -assert.match(source, /if \(singleReferences \? !outfits : \(!outfits \|\| !models\)\) \{/); -assert.match(source, /modelHint\.textContent = "每张目标图单独参与组合"/); +assert.match(source, /if \(singleReferences \? !sources : \(!sources \|\| !targets\)\) return null;/); +assert.match(source, /_o1igModelHint\.textContent = `\$\{modelCount\} 张 · 每张单独参与组合`/); assert.match(source, /_o1igModelAssets\?\.classList\.toggle\("visible", enabled && !singleReferences\)/); -assert.match(source, /单图批量至少需要上传1张素材图/); -assert.match(source, /summary\.textContent = `\$\{pairingText\} × 每组 \$\{perPair\} 张\$\{promptText\},共 \$\{total\} 张`/); +assert.match(source, /每张素材单独出图至少需要上传1张素材图/); +assert.match(source, /total: `共 \$\{pairCount \* perPair \* promptCount\} 张`/); +assert.doesNotMatch(source, /summary\.textContent = ""/, "预览行不能整段清空,否则子节点会被摘掉"); assert.doesNotMatch(source, /整组参与 \/ 全匹配时每张独立/); assert.match(source, /index\.className = "o1ig-reference-index";[\s\S]*?index\.textContent = badges\.label/); assert.doesNotMatch(source, /o1ig-request-index/); @@ -2984,13 +3247,14 @@ assert.match(source, /o1ig-select-option-description/); assert.match(source, /const THINKING_LEVEL_OPTIONS = \[/); assert.match(source, /value: "低", label: "低", description: "耗时低,智力低"/); assert.match(source, /value: "高", label: "高", description: "耗时高,智力高"/); -assert.match(source, /makeSelect\(THINKING_LEVEL_OPTIONS, findWidget\(node, "思考等级"\)\?\.value \|\| "低"\)/); -assert.match(source, /node\._o1igThinking\.value = findWidget\(node, "思考等级"\)\?\.value \|\| "低"/); +assert.match(source, /makeSelect\(THINKING_LEVEL_OPTIONS, findWidget\(node, "思考等级"\)\?\.value \|\| "高"\)/); +assert.match(source, /node\._o1igThinking\.value = findWidget\(node, "思考等级"\)\?\.value \|\| "高"/); assert.match(source, /value: "不缩放", label: "不缩放", description: "无大图"/); assert.match(source, /value: "智能缩放", label: "智能缩放", description: "有大图"/); +assert.match(source, /findWidget\(node, "缩放图片"\)\?\.value \|\| "智能缩放"/); assert.doesNotMatch(source, /色彩纠正|不改AI图|改AI图/); -assert.match(source, /className = "o1ig-select-selected-description"/); -assert.match(source, /trigger\.append\(valueLabel, valueDescription, caret\)/); +assert.doesNotMatch(source, /className = "o1ig-select-selected-description"/); +assert.match(source, /trigger\.append\(valueLabel, caret\)/); assert.equal(maxReferences, 50); assert.equal(maxRequestReferences, 10); assert.equal(referenceLimit({ _o1igBatchEnabled: false }), 10); @@ -3000,15 +3264,15 @@ assert.equal(referenceLimit({ }), 1); assert.equal(referenceLimit({ _o1igBatchEnabled: true, - _o1igBatchMode: { value: "一组搭配+多模特" }, + _o1igBatchMode: { value: "整组素材→多个目标" }, }, "references"), 9); assert.equal(referenceLimit({ _o1igBatchEnabled: true, - _o1igBatchMode: { value: "全部搭配×全部模特" }, + _o1igBatchMode: { value: "每张素材×每张目标" }, }, "references"), 50); assert.equal(referenceLimit({ _o1igBatchEnabled: true, - _o1igBatchMode: { value: "单图素材批量" }, + _o1igBatchMode: { value: "每张素材单独出图" }, }, "references"), 50); assert.equal(referenceLimit({ _o1igBatchEnabled: true }, "models"), 50); { @@ -3102,17 +3366,15 @@ assert.match(source, /node\._o1igModel\.value === "Seedream 5\.0 Pro"/); assert.match(source, /save_format: saveSettings\.format/); assert.match(source, /jobPayload\.background = node\._o1igBackground\.value/); assert.doesNotMatch(source, /jobPayload\.moderation/); -assert.match(source, /jobPayload\.google_search = true/); +assert.doesNotMatch(source, /jobPayload\.google_search/, "在线搜索已下线,任务不再携带该字段"); assert.match(source, /jobPayload\.layer_decomposition = true/); assert.match(source, /if \(layerDecomposition\) \{\s*layerSaveNode = acquireLayerSaveNodeForBatch\(node, saveNode\);/); assert.match(source, /layerDecomposition,\s*retrySlotIndex,/); -assert.match(source, /\["Nano Banana 2\.1", "Nano Banana 2"\]\.includes\(node\._o1igModel\.value\)/); -assert.match(source, /node\._o1igOnlineSearch\.value === "打开"/); assert.match(source, /batch_enabled: retryTask \? false : Boolean\(node\._o1igBatchEnabled\)/); -assert.match(source, /model_references: retryTask \|\| node\._o1igBatchMode\.value === BATCH_MODE_SINGLE_REFERENCES/); -assert.match(source, /整组素材 → 多个目标/); -assert.match(source, /全匹配(素材 × 目标)/); -assert.match(source, /单图批量(每张素材独立)/); +assert.match(source, /model_references: retryTask \|\| batchModeOf\(node\) === BATCH_MODE_SINGLE_REFERENCES/); +assert.match(source, /整组素材→多个目标/); +assert.match(source, /每张素材×每张目标/); +assert.match(source, /每张素材单独出图/); assert.match(source, /api\.fetchApi\("\/o1key\/image\/save"/); assert.match(source, /const saveSettings = generatorSaveSettings\(findConnectedGenerator\(saveNode\)\)/); assert.match(source, /format: saveSettings\.format/); @@ -3131,8 +3393,8 @@ assert.match(source, /generate\.addEventListener\("click", \(\) => queueGenerati assert.doesNotMatch(source, /取消当前任务/); assert.doesNotMatch(source, /makeAdvancedField\("色彩纠正"/); assert.match(source, /makeAdvancedField\("背景", background\)/); +assert.match(source, /makeInlineLabelField\("模型", model\)/); assert.doesNotMatch(source, /makeAdvancedField\("内容审查强度"/); -assert.match(source, /makeAdvancedField\("在线搜索", onlineSearch\)/); assert.match(source, /makeAdvancedField\("图层拆分", layerDecomposition\)/); assert.match(source, /makeAdvancedField\("输出格式", outputFormat\)/); assert.match(source, /makeAdvancedField\("命名规则", namingRule\)/); @@ -3142,7 +3404,6 @@ assert.match(source, /makeAdvancedField\("保存位置", saveLocation\)/); assert.match(source, /留空为 output;或填写 D:\/图片/); assert.doesNotMatch(source, /色彩纠正/); assert.match(source, /const MODEL_CAPABILITIES = Object\.freeze/); -assert.match(source, /setFieldVisible\(node\._o1igOnlineSearchField, capabilities\.search\)/); assert.match(source, /_o1igResizeField: resizeField/); assert.doesNotMatch(source, /参考图输入/); assert.doesNotMatch(source, /hasConnectedReferenceInput/); @@ -3163,7 +3424,8 @@ assert.match(migrationSource, /移除统一图片生成节点已停用的色彩 assert.match(migrationSource, /wv\.length < 15/); assert.match(migrationSource, /wv\.length < 18/); assert.match(migrationSource, /migrateUnifiedSaveSettings/); -assert.match(migrationSource, /migrateUnifiedOnlineSearch/); +assert.match(migrationSource, /migrateRetiredOnlineSearch/); +assert.match(migrationSource, /RETIRED_ONLINE_SEARCH_VALUES/); assert.match(migrationSource, /migrateUnifiedExternalPromptInput/); assert.match(migrationSource, /type: "MiniMaxH3Video"/); assert.match(migrationSource, /wv\.push\("MiniMax-H3"\)/); @@ -3183,8 +3445,10 @@ assert.match(migrationSource, /原生 seed 参数/); const nativeValues = [ "legacy native prompt", "Nano Banana 2.1", "专线", "高", "2K", "1:8", "4", 678803244, "[]", "最高", "png", "{}", "智能缩放", "transparent", false, - "一组搭配+多模特", "[]", "自定义前缀", "legacy-prefix", "原始", "relative-save", "打开", false, + "整组素材→多个目标", "[]", "自定义前缀", "legacy-prefix", "原始", "relative-save", "打开", false, ]; + // 在线搜索 下线后,迁移要从旧存档里摘掉这一格。 + const expectedNativeValues = nativeValues.filter((value) => value !== "打开"); const oldPanelValues = [...nativeValues]; oldPanelValues.splice(8, 0, "randomize"); oldPanelValues.push(""); @@ -3195,11 +3459,11 @@ assert.match(migrationSource, /原生 seed 参数/); }] }, }; migrationExtension.beforeConfigureGraph(nativeGraph); - assert.deepEqual(nativeGraph.nodes[0].widgets_values, nativeValues); - assert.deepEqual(nativeGraph.definitions.subgraphs[0].nodes[0].widgets_values, nativeValues); + assert.deepEqual(nativeGraph.nodes[0].widgets_values, expectedNativeValues); + assert.deepEqual(nativeGraph.definitions.subgraphs[0].nodes[0].widgets_values, expectedNativeValues); migrationExtension.beforeConfigureGraph(nativeGraph); - assert.deepEqual(nativeGraph.nodes[0].widgets_values, nativeValues); - assert.deepEqual(nativeGraph.definitions.subgraphs[0].nodes[0].widgets_values, nativeValues); + assert.deepEqual(nativeGraph.nodes[0].widgets_values, expectedNativeValues); + assert.deepEqual(nativeGraph.definitions.subgraphs[0].nodes[0].widgets_values, expectedNativeValues); const legacyRedCastGraph = { nodes: [{ type: "O1keyAutoRedCast", widgets_values: legacyRedCastValues }], @@ -3267,7 +3531,29 @@ assert.match(migrationSource, /原生 seed 参数/); nodes: [{ type: "O1keyImageGenerator", widgets_values: legacyValues }], }; migrationExtension.beforeConfigureGraph(graphData); - assert.equal(legacyValues.length, 23); + // 在线搜索 移除后,13 项的老存档补齐到 图层拆分 为止。 + assert.equal(legacyValues.length, 22); + assert.equal(legacyValues[21], false); + + for (const [retiredModel, savedResolution, expectedResolution] of [ + ["Nano Banana 2 Lite", "512", "1K"], + ["Nano Banana", "2K", "2K"], + ]) { + const retiredValues = [ + "prompt", retiredModel, "畅速", "低", savedResolution, "1:1", "1", 0, + "[]", "自动", "png", "{}", "不缩放", "auto", false, + "整组素材→多个目标", "[]", "自定义前缀", "o1key", "原始", "", "关闭", false, + ]; + migrationExtension.beforeConfigureGraph({ + nodes: [{ type: "O1keyImageGenerator", widgets_values: retiredValues }], + }); + assert.equal(retiredValues[1], "Nano Banana 2"); + assert.equal(retiredValues[4], expectedResolution); + migrationExtension.beforeConfigureGraph({ + nodes: [{ type: "O1keyImageGenerator", widgets_values: retiredValues }], + }); + assert.equal(retiredValues[1], "Nano Banana 2"); + } const legacyVideoValues = Array.from({ length: 16 }, (_, index) => `value-${index}`); const legacyVideoGraph = { @@ -3278,9 +3564,10 @@ assert.match(migrationSource, /原生 seed 参数/); assert.equal(legacyVideoValues[16], "auto"); migrationExtension.beforeConfigureGraph(legacyVideoGraph); assert.equal(legacyVideoValues.length, 17); - assert.equal(legacyValues[22], false); + const settledLegacy = [...legacyValues]; migrationExtension.beforeConfigureGraph(graphData); - assert.equal(legacyValues.length, 23); + assert.deepEqual(legacyValues, settledLegacy, "A second migration leaves the legacy graph untouched"); + assert.equal(legacyValues.length, 22); const legacyMiniMaxValues = ["prompt", "文生视频", "16:9", "2K", 5]; const legacyMiniMaxGraph = { @@ -3301,13 +3588,44 @@ assert.match(migrationSource, /原生 seed 参数/); assert.deepEqual(modelOnlyMiniMaxValues.slice(-2), ["MiniMax-H3-MAX", 0]); assert.equal(legacyValues[13], "auto"); assert.equal(legacyValues[14], false); - assert.equal(legacyValues[15], "一组搭配+多模特"); + assert.equal(legacyValues[15], "整组素材→多个目标"); assert.equal(legacyValues[16], "[]"); assert.deepEqual(legacyValues.slice(17, 21), ["自定义前缀", "o1key", "原始", ""]); - assert.equal(legacyValues[21], "关闭"); + assert.equal(legacyValues[21], false, "图层拆分 紧跟在 保存位置 之后"); + const settledLegacyValues = [...legacyValues]; migrationExtension.beforeConfigureGraph(graphData); - assert.equal(legacyValues.length, 23); - assert.equal(legacyValues[22], false); + assert.deepEqual(legacyValues, settledLegacyValues, "老存档再次迁移不再变化"); + + for (const [retiredLabel, currentLabel] of [ + ["一组搭配+多模特", "整组素材→多个目标"], + ["全部搭配×全部模特", "每张素材×每张目标"], + ["单图素材批量", "每张素材单独出图"], + ]) { + const retiredModeValues = [ + "prompt", "Nano Banana 2", "畅速", "高", "2K", "1:1", "1", 0, + "[]", "自动", "png", "{}", "不缩放", "auto", false, + retiredLabel, "[]", "自定义前缀", "o1key", "原始", "", "关闭", false, + ]; + const retiredModeGraph = { + nodes: [{ type: "O1keyImageGenerator", widgets_values: retiredModeValues }], + }; + migrationExtension.beforeConfigureGraph(retiredModeGraph); + assert.equal(retiredModeValues[15], currentLabel); + assert.equal(retiredModeValues.length, 22); + const settledMode = [...retiredModeValues]; + migrationExtension.beforeConfigureGraph(retiredModeGraph); + assert.deepEqual(retiredModeValues, settledMode, "重命名迁移是幂等的"); + } + // Current labels are never rewritten by the rename migration. + const currentModeValues = [ + "prompt", "Nano Banana 2", "畅速", "高", "2K", "1:1", "1", 0, + "[]", "自动", "png", "{}", "不缩放", "auto", false, + "每张素材×每张目标", "[]", "自定义前缀", "o1key", "原始", "", "关闭", false, + ]; + migrationExtension.beforeConfigureGraph({ + nodes: [{ type: "O1keyImageGenerator", widgets_values: currentModeValues }], + }); + assert.equal(currentModeValues[15], "每张素材×每张目标"); const currentValues = [ "prompt", "gpt-image-2", "畅速", "高", "2K", "16:9", "1", 42, @@ -3316,36 +3634,35 @@ assert.match(migrationSource, /原生 seed 参数/); migrationExtension.beforeConfigureGraph({ nodes: [{ type: "O1keyImageGenerator", widgets_values: currentValues }], }); - assert.equal(currentValues.length, 23); - assert.equal(currentValues[22], false); + assert.equal(currentValues.length, 22); + assert.equal(currentValues[21], false); assert.equal(currentValues[10], "webp"); assert.equal(currentValues[13], "transparent"); assert.equal(currentValues[14], false); - assert.equal(currentValues[15], "一组搭配+多模特"); + assert.equal(currentValues[15], "整组素材→多个目标"); assert.equal(currentValues[16], "[]"); assert.deepEqual(currentValues.slice(17, 21), ["自定义前缀", "o1key", "原始", ""]); - assert.equal(currentValues[21], "关闭"); const retiredModerationValues = [ "prompt", "gpt-image-2.5-flare", "直连", "低", "智能", "智能", "9", 17, "[]", "最高", "webp", "{}", "智能缩放", "opaque", "低", - true, "单图素材批量", "[]", "自然数字", "saved", "原始", "archive", "关闭", false, + true, "每张素材单独出图", "[]", "自然数字", "saved", "原始", "archive", "关闭", false, ]; const retiredModerationGraph = { nodes: [{ type: "O1keyImageGenerator", widgets_values: retiredModerationValues }], }; migrationExtension.beforeConfigureGraph(retiredModerationGraph); - assert.equal(retiredModerationValues.length, 23); - assert.deepEqual(retiredModerationValues.slice(13, 17), ["opaque", true, "单图素材批量", "[]"]); + assert.equal(retiredModerationValues.length, 22); + assert.deepEqual(retiredModerationValues.slice(13, 17), ["opaque", true, "每张素材单独出图", "[]"]); assert.equal(retiredModerationValues[9], "最高"); assert.equal(retiredModerationValues[17], "自然数字"); migrationExtension.beforeConfigureGraph(retiredModerationGraph); - assert.equal(retiredModerationValues.length, 23); + assert.equal(retiredModerationValues.length, 22); const movedGeneratorValues = [ "prompt", "Nano Banana 2", "畅速", "低", "2K", "1:1", "1", 0, "[]", "自动", "png", "{}", "不缩放", "不纠正", "auto", "自动", - false, "一组搭配+多模特", "[]", + false, "整组素材→多个目标", "[]", ]; const legacySaveValues = ["legacy-prefix", "jpg", "archive/session", "自然数字"]; const movedGraph = { @@ -3368,9 +3685,8 @@ assert.match(migrationSource, /原生 seed 参数/); ); assert.deepEqual(legacySaveValues, []); migrationExtension.beforeConfigureGraph(movedGraph); - assert.equal(movedGeneratorValues.length, 23); - assert.equal(movedGeneratorValues[22], false); - assert.equal(movedGeneratorValues[21], "关闭"); + assert.equal(movedGeneratorValues.length, 22); + assert.equal(movedGeneratorValues[21], false); assert.deepEqual(legacySaveValues, []); const legacyNanoValues = [ @@ -3526,9 +3842,10 @@ assert.match(migrationSource, /原生 seed 参数/); legacyGPTValues.slice(-3), ["auto", "智能缩放", 0], ); - assert.equal(legacyGPTValues.length, 10); + assert.equal(legacyGPTValues.length, 11); + assert.equal(legacyGPTValues[3], "高"); migrationExtension.beforeConfigureGraph(legacyGPTGraph); - assert.equal(legacyGPTValues.length, 10); + assert.equal(legacyGPTValues.length, 11); const legacyGPTWithColorCorrection = [ "prompt", "gpt-image-2", "畅速", "智能", 1, "自动", "png", 0, @@ -3538,7 +3855,8 @@ assert.match(migrationSource, /原生 seed 参数/); nodes: [{ type: "O1keyGPTImage", widgets_values: legacyGPTWithColorCorrection }], }); assert.deepEqual(legacyGPTWithColorCorrection.slice(-3), ["auto", "不缩放", 0]); - assert.equal(legacyGPTWithColorCorrection.length, 10); + assert.equal(legacyGPTWithColorCorrection.length, 11); + assert.equal(legacyGPTWithColorCorrection[3], "高"); const currentGPT25Values = [ "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "超高", "png", @@ -3548,10 +3866,11 @@ assert.match(migrationSource, /原生 seed 参数/); nodes: [{ type: "O1keyGPTImage", widgets_values: currentGPT25Values }], }; migrationExtension.beforeConfigureGraph(currentGPT25Graph); - assert.equal(currentGPT25Values.length, 10); + assert.equal(currentGPT25Values.length, 11); + assert.equal(currentGPT25Values[3], "高"); assert.deepEqual(currentGPT25Values.slice(-3), ["opaque", "智能缩放", 0]); migrationExtension.beforeConfigureGraph(currentGPT25Graph); - assert.equal(currentGPT25Values.length, 10); + assert.equal(currentGPT25Values.length, 11); const legacyGPT25Values = [ "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "超高", "png", 0, @@ -3561,10 +3880,11 @@ assert.match(migrationSource, /原生 seed 参数/); nodes: [{ type: "O1keyGPTImage", widgets_values: legacyGPT25Values }], }; migrationExtension.beforeConfigureGraph(legacyGPT25Graph); - assert.equal(legacyGPT25Values.length, 10); + assert.equal(legacyGPT25Values.length, 11); + assert.equal(legacyGPT25Values[3], "高"); assert.deepEqual(legacyGPT25Values.slice(-3), ["transparent", "智能缩放", 0]); migrationExtension.beforeConfigureGraph(legacyGPT25Graph); - assert.equal(legacyGPT25Values.length, 10); + assert.equal(legacyGPT25Values.length, 11); const legacyGPTBatchValues = [ "prompt", "gpt-image-2", "畅速", "智能", 1, "自动", @@ -3579,10 +3899,11 @@ assert.match(migrationSource, /原生 seed 参数/); legacyGPTBatchValues.slice(-6), ["原始", "auto", "和原始图片名保持一致", "", "智能缩放", 0], ); - assert.equal(legacyGPTBatchValues.length, 14); - assert.equal(legacyGPTBatchValues[8], "原始"); + assert.equal(legacyGPTBatchValues.length, 15); + assert.equal(legacyGPTBatchValues[3], "高"); + assert.equal(legacyGPTBatchValues[9], "原始"); migrationExtension.beforeConfigureGraph(legacyGPTBatchGraph); - assert.equal(legacyGPTBatchValues.length, 14); + assert.equal(legacyGPTBatchValues.length, 15); const legacyGPTBatchWithRemovedControls = [ "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "最高", @@ -3597,10 +3918,11 @@ assert.match(migrationSource, /原生 seed 参数/); legacyGPTBatchWithRemovedControls.slice(-6), ["PNG", "transparent", "自然数字", "D:\\output", "不缩放", 123], ); - assert.equal(legacyGPTBatchWithRemovedControls.length, 14); - assert.equal(legacyGPTBatchWithRemovedControls[8], "PNG"); + assert.equal(legacyGPTBatchWithRemovedControls.length, 15); + assert.equal(legacyGPTBatchWithRemovedControls[3], "高"); + assert.equal(legacyGPTBatchWithRemovedControls[9], "PNG"); migrationExtension.beforeConfigureGraph(legacyGPTBatchWithRemovedControlsGraph); - assert.equal(legacyGPTBatchWithRemovedControls.length, 14); + assert.equal(legacyGPTBatchWithRemovedControls.length, 15); const legacyGPTBatchTwoPaths = [ "prompt", "gpt-image-2.5-flare", "畅速", "智能", 1, "超高", @@ -3616,10 +3938,11 @@ assert.match(migrationSource, /原生 seed 参数/); legacyGPTBatchTwoPaths.slice(-6), ["WebP", "opaque", "和原始图片名保持一致", "D:\\output", "智能缩放", 456], ); - assert.equal(legacyGPTBatchTwoPaths.length, 16); - assert.equal(legacyGPTBatchTwoPaths[10], "WebP"); + assert.equal(legacyGPTBatchTwoPaths.length, 17); + assert.equal(legacyGPTBatchTwoPaths[3], "高"); + assert.equal(legacyGPTBatchTwoPaths[11], "WebP"); migrationExtension.beforeConfigureGraph(legacyGPTBatchTwoPathsGraph); - assert.equal(legacyGPTBatchTwoPaths.length, 16); + assert.equal(legacyGPTBatchTwoPaths.length, 17); const currentGPTBatchWithRandomSelection = [ "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "最高", @@ -3633,13 +3956,14 @@ assert.match(migrationSource, /原生 seed 参数/); }], }; migrationExtension.beforeConfigureGraph(currentGPTBatchWithRandomSelectionGraph); - assert.equal(currentGPTBatchWithRandomSelection.length, 14); - assert.equal(currentGPTBatchWithRandomSelection[8], "WebP"); + assert.equal(currentGPTBatchWithRandomSelection.length, 15); + assert.equal(currentGPTBatchWithRandomSelection[3], "高"); + assert.equal(currentGPTBatchWithRandomSelection[9], "WebP"); assert.deepEqual(currentGPTBatchWithRandomSelection.slice(-6), [ "WebP", "opaque", "和原始图片名保持一致", "D:\\output", "智能缩放", 789, ]); migrationExtension.beforeConfigureGraph(currentGPTBatchWithRandomSelectionGraph); - assert.equal(currentGPTBatchWithRandomSelection.length, 14); + assert.equal(currentGPTBatchWithRandomSelection.length, 15); const previousGPTBatchWithRemovedControls = [ "prompt", "gpt-image-2.5-sunburst", "畅速", "智能", 1, "最高", @@ -3653,12 +3977,13 @@ assert.match(migrationSource, /原生 seed 参数/); }], }; migrationExtension.beforeConfigureGraph(previousGPTBatchWithRemovedControlsGraph); - assert.equal(previousGPTBatchWithRemovedControls.length, 14); + assert.equal(previousGPTBatchWithRemovedControls.length, 15); + assert.equal(previousGPTBatchWithRemovedControls[3], "高"); assert.deepEqual(previousGPTBatchWithRemovedControls.slice(-6), [ "WebP", "opaque", "和原始图片名保持一致", "D:\\output", "智能缩放", 789, ]); migrationExtension.beforeConfigureGraph(previousGPTBatchWithRemovedControlsGraph); - assert.equal(previousGPTBatchWithRemovedControls.length, 14); + assert.equal(previousGPTBatchWithRemovedControls.length, 15); const legacyGPTBatchInputsNode = { type: "O1keyGPTImageBatch", @@ -4358,6 +4683,27 @@ assert.match(migrationSource, /原生 seed 参数/); assert.equal(taskId.hidden, false); } +{ + let migration; + vm.runInNewContext(migrationSource.replace(/^import .*;\s*$/gm, ""), { + app: { registerExtension(value) { migration = value; } }, + console: { log() {}, warn() {} }, + }); + for (const model of ["gpt-image-2.6-sunburst", "gpt-image-2.6-flare"]) { + const single = { type: "O1keyGPTImage", widgets_values: [ + "prompt", model, "直连", "低", "智能", 1, "最高", "png", "auto", "智能缩放", 42, + ] }; + const batch = { type: "O1keyGPTImageBatch", widgets_values: [ + "prompt", model, "专线", "中", "智能", 1, "超高", "1个路径", "images", "WebP", "opaque", + "和原始图片名保持一致", "output", "智能缩放", 789, + ] }; + const original = JSON.parse(JSON.stringify([single, batch])); + const workflow = { nodes: [single], definitions: { subgraphs: [{ nodes: [batch] }] } }; + migration.beforeConfigureGraph(workflow); + migration.beforeConfigureGraph(workflow); + assert.deepEqual([single, batch], original, "2.6 controls survive root/subgraph migration twice"); + } +} console.log("o1key image generator frontend tests passed"); const nanoThinkingSource = fs.readFileSync(new URL("../web/js/nanoBananaThinkingLevel.js", import.meta.url), "utf8"); @@ -4388,3 +4734,148 @@ const nanoThinkingSource = fs.readFileSync(new URL("../web/js/nanoBananaThinking assert.equal(model.callback, callback); } } + +{ + const names = [ + "prompt", "模型", "模型线路", "思考等级", "分辨率", "宽高比", "生图数量", "seed", + "参考图清单", "质量", "输出格式", "蒙版清单", "缩放图片", "背景", "批量出图", + "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms", + ]; + const values = [ + "gif panel", "gpt-image-2.6-flare", "畅速", "低", "智能", "智能", "1", 0, + "[]", "自动", "png", "{}", "智能缩放", "auto", false, + "整组素材→多个目标", "[]", "自定义前缀", "o1key", "原始", "", "关闭", false, "高", 9, 200, + ]; + const widgets = names.map((name, index) => ({ name, value: values[index], options: {} })); + const node = { + comfyClass: "O1keyImageGenerator", widgets, size: [560, 1035], outputs: [], + addDOMWidget(name, type, element, options) { + const widget = { name, type, element, options }; this.widgets.push(widget); return widget; + }, + computeSize() { return [500, 1025]; }, + setSize(size) { this.size = size; }, + setDirtyCanvas() {}, + }; + buildPanel(node); + syncModelOptions(node); + assert.deepEqual( + Array.from(node._o1igOutputFormat._o1igOptions, (option) => option.value), + ["jpeg", "png", "webp", "svg", "gif"], + ); + node._o1igOutputFormat.value = "gif"; + syncGptOutputOptions(node); + assert.equal(node._o1igFrameCountField.style.display, ""); + assert.equal(node._o1igFrameDurationField.style.display, ""); + node._o1igReferences = [{ name: "a.png", subfolder: "", type: "input" }]; + syncGptOutputOptions(node); + assert.equal(node._o1igOutputFormat._o1igOptions.some((option) => option.value === "gif"), false); +} + +{ + assert.match(source, /function animatedFlagsForSaveResults/); + assert.match(source, /function isGifSaveResult/); + assert.match(source, /output\.animated = animated/); + assert.match(source, /job\.animated = animated/); +} + +{ + // Runaway height guards. A menu click never fires pointerup, so the global "pointer is down" + // flag stayed true and every engine re-layout was read as a user drag: the node inflated on + // its own after 重启. A press outside the node box must not count as a resize, a pointer that + // jumped across the screen is a stale gesture, and a fit must not chase its own noise. + const pointerStartsInsideNode = vm.runInContext("pointerStartsInsideNode", context); + const resetCanvasPointerGesture = vm.runInContext("resetCanvasPointerGesture", context); + const fitTolerance = vm.runInContext("GENERATOR_FIT_TOLERANCE", context); + const overshoot = vm.runInContext("GENERATOR_DRAG_OVERSHOOT", context); + + assert.ok( + fitTolerance >= 16 && fitTolerance <= 40, + "The fit dead zone has to cover the computeSize measurement noise, without hiding real changes", + ); + assert.match( + source, + /Math\.abs\(currentHeight - contentHeight\) <= GENERATOR_FIT_TOLERANCE/, + "fitNode keeps the engine height when it already matches within the tolerance", + ); + + const pointerNode = { + pos: [100, 100], + size: [400, 300], + graph: { canvas: { ds: { scale: 1, offset: [0, 0] } } }, + }; + assert.equal(pointerStartsInsideNode(pointerNode, 300, 250), true, "A press on the node body may resize it"); + assert.equal(pointerStartsInsideNode(pointerNode, 40, 250), false, "A press left of the node must not"); + assert.equal(pointerStartsInsideNode(pointerNode, 300, 20), false, "A press above the node must not"); + assert.equal(pointerStartsInsideNode(pointerNode, 0, 0), false, "A missing client position is no gesture"); + assert.equal( + pointerStartsInsideNode({ pos: [0, 0], size: [10, 10] }, 5, 5), + false, + "Without a canvas the press cannot be located, so it is ignored", + ); + pointerNode.graph.canvas.ds = { scale: 2, offset: [50, 20] }; + assert.equal( + pointerStartsInsideNode(pointerNode, 100 * 2 + 50, 100 * 2 + 20), + true, + "Presses are mapped through the canvas zoom and offset", + ); + assert.equal( + pointerStartsInsideNode(pointerNode, 560 * 2 + 50, 400 * 2 + 20), + false, + "A press past the zoomed node box must not", + ); + + // Vue nodes are DOM boxes whose position the canvas transform does not describe, so the + // browser hit test decides instead of the geometry fallback. + const menu = { kind: "menu" }; + const grip = { kind: "resize-grip" }; + const nodeRoot = { kind: "node-root", contains: (element) => element !== menu }; + const domPanel = { + closest(selector) { return selector === "[data-node-id]" ? nodeRoot : null; }, + }; + const domNode = { + _o1igPanel: domPanel, + pos: [0, 0], + size: [10, 10], + graph: { canvas: { ds: { scale: 0.9, offset: [1234, 5678] } } }, + }; + document.elementFromPoint = (x) => (x === 5 ? grip : menu); + assert.equal( + pointerStartsInsideNode(domNode, 5, 5), + true, + "A press anywhere in the node subtree (its resize grip included) counts", + ); + assert.equal( + pointerStartsInsideNode(domNode, 6, 5), + false, + "A press on a menu outside the node does not, even when the transform math would say otherwise", + ); + delete document.elementFromPoint; + assert.equal( + pointerStartsInsideNode(domNode, 5, 5), + false, + "Without a hit test the DOM node falls back to the (unreliable) transform math", + ); + + vm.runInContext("canvasPointerDown = true; canvasPointerStartX = 640; canvasPointerStartY = 480;", context); + resetCanvasPointerGesture(); + assert.equal(vm.runInContext("canvasPointerDown", context), false, "A workflow (re)load voids the press"); + assert.equal(vm.runInContext("canvasPointerStartX", context), 0); + assert.equal(vm.runInContext("canvasPointerStartY", context), 0); + assert.match(source, /resetCanvasPointerGesture\(\);/, "onConfigure has to drop the stale gesture"); + assert.match( + source, + /if \(!pointerStartsInsideNode\(this, canvasPointerStartX, canvasPointerStartY\)\)/, + "onResize only accepts a drag that started on the node", + ); + + assert.equal( + nextGeneratorExtra({ height: 900, extra: 240, pointerY: 240 }, 240 + overshoot + 40, 10, 1), + null, + "A pointer that jumped far away is a stale gesture, not a drag", + ); + assert.equal( + nextGeneratorExtra({ height: 900, extra: 240, pointerY: 240 }, 240 + overshoot - 40, 10, 1), + 240 + overshoot - 40, + "A real drag stays inside the overshoot bound", + ); +} diff --git a/tests/test_o1key_image_generator_layout.mjs b/tests/test_o1key_image_generator_layout.mjs new file mode 100644 index 0000000..49d2f8a --- /dev/null +++ b/tests/test_o1key_image_generator_layout.mjs @@ -0,0 +1,201 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import vm from "node:vm"; +import { webcrypto } from "node:crypto"; + +const sourcePath = new URL("../web/js/o1keyImageGenerator.js", import.meta.url); +const source = fs.readFileSync(sourcePath, "utf8").replace(/^import .*;\s*$/gm, ""); + +let nextNodeId = 1; +let nextLinkId = 1; +const graph = { + nodes: new Map(), + links: new Map(), + add(node) { + node.id = nextNodeId++; + node.graph = this; + this.nodes.set(node.id, node); + }, + getNodeById(id) { return this.nodes.get(id); }, + beforeChange() {}, + afterChange() {}, + setDirtyCanvas() {}, +}; + +const LiteGraph = { + createNode(type) { + return { + type, + comfyClass: type, + pos: [0, 0], + size: [300, 260], + properties: {}, + inputs: [{ link: null }], + widgets: [], + }; + }, +}; + +const app = { + graph, + ui: { settings: { getSettingValue: () => false } }, + registerExtension() {}, +}; +const api = { + apiURL: (value) => value, + addEventListener() {}, + fetchApi: async () => ({ ok: true, json: async () => ({}) }), +}; + +class Element { + constructor(tagName) { + this.tagName = String(tagName).toUpperCase(); + this.children = []; + this.className = ""; + this.style = {}; + this.dataset = {}; + this.listeners = new Map(); + } + append(...items) { this.children.push(...items); } + prepend(...items) { this.children.unshift(...items); } + replaceChildren(...items) { this.children = [...items]; } + addEventListener(type, listener) { this.listeners.set(type, listener); } + setAttribute(name, value) { this[name] = value; } + classList = { + values: new Set(), + add(v) { this.values.add(v); }, + remove(v) { this.values.delete(v); }, + contains(v) { return this.values.has(v); }, + toggle(v, force) { + const on = force ?? !this.values.has(v); + if (on) this.values.add(v); else this.values.delete(v); + return on; + }, + }; +} + +const document = { + head: { append() {}, appendChild() {} }, + body: { append() {} }, + createElement(tag) { return new Element(tag); }, + createElementNS(_ns, tag) { return new Element(tag); }, + getElementById() { return null; }, + querySelector() { return null; }, + addEventListener() {}, + removeEventListener() {}, +}; + +const context = vm.createContext({ + app, + api, + document, + window: { LiteGraph }, + URL, + URLSearchParams, + FormData, + Event, + openReferenceImageEditor: async () => null, + crypto: webcrypto, + console, + clearTimeout, + setTimeout, + requestAnimationFrame: (cb) => cb(), +}); +vm.runInContext(source, context, { filename: sourcePath.pathname }); + +const createSaveNodeForBatch = vm.runInContext("createSaveNodeForBatch", context); +const nextHorizontalSaveNodePos = vm.runInContext("nextHorizontalSaveNodePos", context); +const measureNodeExtent = vm.runInContext("measureNodeExtent", context); +const generatorPanelMinHeight = vm.runInContext("generatorPanelMinHeight", context); +const generatorMinimumHeight = vm.runInContext("generatorMinimumHeight", context); +const generatorChromeHeight = vm.runInContext("generatorChromeHeight", context); +const isVueNodesEnabled = vm.runInContext("isVueNodesEnabled", context); +const SAVE_NODE_LAYOUT_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_GAP_X", context); +const SAVE_NODE_LAYOUT_ORIGIN_GAP_X = vm.runInContext("SAVE_NODE_LAYOUT_ORIGIN_GAP_X", context); +const SAVE_NODE_LAYOUT_SIZE = vm.runInContext("SAVE_NODE_LAYOUT_SIZE", context); + +assert.equal(isVueNodesEnabled(), false); +assert.equal(SAVE_NODE_LAYOUT_GAP_X, 50); +assert.equal(SAVE_NODE_LAYOUT_ORIGIN_GAP_X, 70); + +{ + const generator = { pos: [100, 200], size: [500, 1025] }; + const firstPos = nextHorizontalSaveNodePos(generator, []); + assert.equal(firstPos[0], 100 + 500 + SAVE_NODE_LAYOUT_ORIGIN_GAP_X); + assert.equal(firstPos[1], 200 + 30); + + const firstPeer = { pos: [700, 230], size: [300, 260] }; + const secondPos = nextHorizontalSaveNodePos(generator, [firstPeer]); + assert.equal(secondPos[0], 700 + 300 + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(secondPos[1], 230); + + const secondPeer = { pos: [1050, 230], size: [407, 440] }; + const thirdPos = nextHorizontalSaveNodePos(generator, [firstPeer, secondPeer]); + assert.equal(thirdPos[0], 1050 + 407 + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(thirdPos[1], 230); + + const blocking = { + pos: [700 + 300 + SAVE_NODE_LAYOUT_GAP_X, 230], + size: [...SAVE_NODE_LAYOUT_SIZE], + }; + const blockedPos = nextHorizontalSaveNodePos(generator, [firstPeer, blocking]); + assert.equal(blockedPos[0], blocking.pos[0] + blocking.size[0] + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(blockedPos[1], 230); +} + +{ + LiteGraph.vueNodesMode = true; + assert.equal(isVueNodesEnabled(), true); + assert.equal(generatorChromeHeight(), 16); + const generator = { pos: [10, 20], size: [560, 1035] }; + const pos = nextHorizontalSaveNodePos(generator, []); + assert.equal(pos[0], 10 + 560 + SAVE_NODE_LAYOUT_ORIGIN_GAP_X); + assert.equal(pos[1], 20); // no classic +30 offset under Vue Nodes + LiteGraph.vueNodesMode = false; +} + +{ + assert.equal(generatorMinimumHeight({ _o1igModel: { value: "Nano Banana 2" } }), 1025); + assert.equal( + generatorMinimumHeight({ + _o1igModel: { value: "gpt-image-2" }, + _o1igBatchEnabled: true, + }), + 1300, + ); + assert.ok(generatorPanelMinHeight({ _o1igModel: { value: "Nano Banana 2" } }) >= 292); + assert.equal(measureNodeExtent({ pos: [1, 2], size: [0, 0] }).width, SAVE_NODE_LAYOUT_SIZE[0]); + assert.equal(measureNodeExtent({ pos: [1, 2], size: [410, 500] }).right, 411); +} + +{ + const generator = { + id: 100, + graph, + pos: [20, 30], + size: [410, 340], + outputs: [{ links: [] }], + connect(_originSlot, target) { + const linkId = nextLinkId++; + graph.links.set(linkId, { origin_id: this.id, target_id: target.id }); + this.outputs[0].links.push(linkId); + target.inputs[0].link = linkId; + }, + }; + graph.nodes.set(generator.id, generator); + + const first = createSaveNodeForBatch(generator, "11111111-1111-4111-8111-111111111111"); + const second = createSaveNodeForBatch(generator, "22222222-2222-4222-8222-222222222222"); + assert.equal(first.pos[0], generator.pos[0] + generator.size[0] + SAVE_NODE_LAYOUT_ORIGIN_GAP_X); + assert.equal(first.pos[1], generator.pos[1] + 30); + assert.equal(second.pos[0], first.pos[0] + first.size[0] + SAVE_NODE_LAYOUT_GAP_X); + assert.equal(second.pos[1], first.pos[1]); + assert.ok(second.pos[0] > first.pos[0]); +} + +assert.doesNotMatch(source, /batchIndex % 3/); +assert.match(source, /function nextHorizontalSaveNodePos\(/); +assert.match(source, /getMinHeight: \(\) => generatorPanelMinHeight\(node\)/); +assert.match(source, /Comfy\.VueNodes\.Enabled/); + +console.log("layout placement tests passed"); \ No newline at end of file diff --git a/tests/test_o1key_image_jobs.py b/tests/test_o1key_image_jobs.py index 5e30387..379b210 100644 --- a/tests/test_o1key_image_jobs.py +++ b/tests/test_o1key_image_jobs.py @@ -18,6 +18,20 @@ COMFY_ROOT = CUSTOM_NODES_ROOT.parent sys.path.insert(0, str(COMFY_ROOT)) sys.path.insert(0, str(CUSTOM_NODES_ROOT)) +import types as _types +# Avoid package-wide node registry (CUDA probe) in the portable CPU torch build. +_plugin = _types.ModuleType("comfyui_o1key") +_plugin.__path__ = [str(ROOT)] +sys.modules["comfyui_o1key"] = _plugin +for _child in ("nodes", "utils", "clients"): + _mod = _types.ModuleType(f"comfyui_o1key.{_child}") + _mod.__path__ = [str(ROOT / _child)] + sys.modules[_mod.__name__] = _mod +_model_management = _types.ModuleType("comfy.model_management") +_model_management.processing_interrupted = lambda: False +_model_management.InterruptProcessingException = RuntimeError +sys.modules[_model_management.__name__] = _model_management + from comfyui_o1key.utils import o1key_image_jobs as JOBS # noqa: E402 @@ -70,12 +84,12 @@ class PayloadTests(unittest.TestCase): self.assertEqual(job["generator_node_id"], 1) self.assertEqual(job["save_node_id"], 2) - def test_missing_thinking_level_defaults_to_low(self): + def test_missing_thinking_level_and_resize_defaults(self): payload = _payload() payload.pop("thinking_level") job = JOBS.normalize_job_payload(payload) - self.assertEqual(job["thinking_level"], "低") - self.assertEqual(job["resize_mode"], "不缩放") + self.assertEqual(job["thinking_level"], "高") + self.assertEqual(job["resize_mode"], "智能缩放") self.assertNotIn("color_correction", job) self.assertEqual(job["filename_prefix"], "o1key") self.assertEqual(job["save_format"], "原始") @@ -110,6 +124,62 @@ class PayloadTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "Nano Banana 2"): JOBS.normalize_job_payload(payload) + def test_26_complexity_normalizes_default_and_rejects_invalid_values(self): + for variant in ("sunburst", "flare"): + model = f"gpt-image-2.6-{variant}" + job = JOBS.normalize_job_payload({**_payload(), "model": model}) + self.assertEqual(job["complexity"], "high") + for value, expected in (("low", "low"), ("medium", "medium"), ("high", "high"), + ("低", "low"), ("中", "medium"), ("高", "high")): + job = JOBS.normalize_job_payload({**_payload(), "model": model, "complexity": value}) + self.assertEqual(job["complexity"], expected) + for value in ("invalid", "", [], 1): + with self.subTest(model=model, value=value), self.assertRaisesRegex(ValueError, "复杂度"): + JOBS.normalize_job_payload({**_payload(), "model": model, "complexity": value}) + job = JOBS.normalize_job_payload({**_payload(), "model": "gpt-image-2.5-sunburst", "complexity": "low"}) + self.assertNotIn("complexity", job) + + def test_26_svg_gif_normalize_and_reject_edit(self): + for output_format in ("svg", "gif"): + job = JOBS.normalize_job_payload({ + **_payload(), + "batch_id": str(__import__("uuid").uuid4()), + "model": "gpt-image-2.6-sunburst", + "output_format": output_format, + "frame_count": 12 if output_format == "gif" else 9, + "frame_duration_ms": 205 if output_format == "gif" else 200, + }) + self.assertEqual(job["output_format"], output_format) + if output_format == "gif": + self.assertEqual(job["frame_count"], 12) + self.assertEqual(job["frame_duration_ms"], 200) + else: + self.assertNotIn("frame_count", job) + self.assertNotIn("frame_duration_ms", job) + with self.assertRaisesRegex(ValueError, "仅支持 GPT Image 2.6"): + JOBS.normalize_job_payload({ + **_payload(), + "batch_id": str(__import__("uuid").uuid4()), + "model": "gpt-image-2.5-sunburst", + "output_format": output_format, + }) + with self.assertRaisesRegex(ValueError, "纯文生图"): + JOBS.normalize_job_payload({ + **_payload(), + "batch_id": str(__import__("uuid").uuid4()), + "model": "gpt-image-2.6-flare", + "output_format": output_format, + "references": [{"name": "a.png", "subfolder": "", "type": "input"}], + }) + with self.assertRaisesRegex(ValueError, "帧数"): + JOBS.normalize_job_payload({ + **_payload(), + "batch_id": str(__import__("uuid").uuid4()), + "model": "gpt-image-2.6-flare", + "output_format": "gif", + "frame_count": 1, + }) + def test_unified_limits_and_gpt_parameters(self): payload = _payload() payload.update({ @@ -146,7 +216,8 @@ class PayloadTests(unittest.TestCase): self.assertEqual(default_gpt["resize_mode"], "智能缩放") self.assertEqual(default_gpt["save_format"], "原始") - for model in ("gpt-image-2.5-sunburst", "gpt-image-2.5-flare"): + for model in ("gpt-image-2.5-sunburst", "gpt-image-2.5-flare", + "gpt-image-2.6-sunburst", "gpt-image-2.6-flare"): with self.subTest(model=model): gpt_25 = JOBS.normalize_job_payload({ **_payload(), @@ -353,7 +424,7 @@ class PayloadTests(unittest.TestCase): grouped = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "一组搭配+多模特", + "batch_mode": "整组素材→多个目标", "references": outfits[:9], "model_references": models, }) @@ -364,7 +435,7 @@ class PayloadTests(unittest.TestCase): cartesian = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "全部搭配×全部模特", + "batch_mode": "每张素材×每张目标", "references": outfits, "model_references": models, }) @@ -376,7 +447,7 @@ class PayloadTests(unittest.TestCase): single_references = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "单图素材批量", + "batch_mode": "每张素材单独出图", "references": outfits[:3], "model_references": models[:1], }) @@ -404,7 +475,7 @@ class PayloadTests(unittest.TestCase): single_fifty = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "单图素材批量", + "batch_mode": "每张素材单独出图", "references": fifty_references, }) self.assertEqual(single_fifty["total_task_count"], 50) @@ -412,7 +483,7 @@ class PayloadTests(unittest.TestCase): grouped_fifty_targets = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "一组搭配+多模特", + "batch_mode": "整组素材→多个目标", "references": outfits[:1], "model_references": fifty_models, }) @@ -422,7 +493,7 @@ class PayloadTests(unittest.TestCase): JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "单图素材批量", + "batch_mode": "每张素材单独出图", "references": [ *fifty_references, {"name": "overflow.png", "subfolder": "", "type": "input"}, @@ -433,7 +504,7 @@ class PayloadTests(unittest.TestCase): JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "一组搭配+多模特", + "batch_mode": "整组素材→多个目标", "references": outfits, "model_references": models[:1], }) @@ -641,7 +712,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase): "model": "gpt-image-2", "resolution": "1K", "batch_enabled": True, - "batch_mode": "单图素材批量", + "batch_mode": "每张素材单独出图", "references": references, }) job["reference_paths"] = tuple(item["name"] for item in references) @@ -700,7 +771,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase): "model": "gpt-image-2", "resolution": "1K", "batch_enabled": True, - "batch_mode": "全部搭配×全部模特", + "batch_mode": "每张素材×每张目标", "references": [ {"name": os.path.basename(path), "subfolder": "", "type": "input"} for path in outfit_paths @@ -769,7 +840,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase): job = JOBS.normalize_job_payload({ **_payload(), - "model": "gpt-image-2.5-sunburst", + "model": "gpt-image-2.6-sunburst", + "complexity": "low", "resolution": "4K", "aspect_ratio": "智能", "prompt": "紫色方块\n---\n绿色圆形", @@ -802,7 +874,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase): self.assertGreater(maximum_active, 1) self.assertTrue(all(call["n"] == 1 for call in calls)) self.assertTrue(all(call["quality"] == "xhigh" for call in calls)) - self.assertTrue(all(call["model"] == "gpt-image-2.5-sunburst-sp" for call in calls)) + self.assertTrue(all(call["model"] == "gpt-image-2.6-sunburst-sp" for call in calls)) + self.assertTrue(all(call["complexity"] == "low" for call in calls)) self.assertTrue(all(call["special_price_parallel"] is False for call in calls)) self.assertTrue(all(call["size"] == "2880x2880" for call in calls)) self.assertTrue(all(call["output_format"] == "webp" for call in calls)) @@ -902,7 +975,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase): job = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "单图素材批量", + "batch_mode": "每张素材单独出图", "references": references, }) job["reference_paths"] = tuple(item["name"] for item in references) @@ -969,7 +1042,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase): job = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "全部搭配×全部模特", + "batch_mode": "每张素材×每张目标", "references": [ {"name": os.path.basename(path), "subfolder": "", "type": "input"} for path in outfit_paths @@ -1162,7 +1235,7 @@ class IsolationTests(unittest.TestCase): job = JOBS.normalize_job_payload({ **_payload(), "batch_enabled": True, - "batch_mode": "全部搭配×全部模特", + "batch_mode": "每张素材×每张目标", "references": [{"name": "outfit.png", "subfolder": "", "type": "input"}], "model_references": [{"name": "model.png", "subfolder": "", "type": "input"}], }) diff --git a/tests/test_o1key_image_save.py b/tests/test_o1key_image_save.py index f14d135..5bc722f 100644 --- a/tests/test_o1key_image_save.py +++ b/tests/test_o1key_image_save.py @@ -334,5 +334,72 @@ class O1keyImageSaveTests(unittest.TestCase): self.assertEqual(Path(output_dir, "1.png").read_bytes(), b"keep-existing") + def test_original_gif_preserves_bytes_and_marks_animated(self): + frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue", "green")] + buffer = BytesIO() + frames[0].save( + buffer, + format="GIF", + save_all=True, + append_images=frames[1:], + duration=120, + loop=0, + ) + raw = buffer.getvalue() + for image in frames: + image.close() + with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as output_dir: + source = os.path.join(temp_dir, "provider.gif") + Path(source).write_bytes(raw) + results = save_temp_images( + [source], + "o1key-gif", + "原始", + output_dir, + _folder_paths(output_dir), + naming_rule="自定义前缀", + ) + self.assertEqual(len(results), 1) + self.assertTrue(results[0]["filename"].endswith(".gif")) + self.assertEqual(results[0].get("media"), "gif") + self.assertTrue(results[0].get("animated")) + saved = Path(output_dir, results[0]["filename"]).read_bytes() + self.assertEqual(detect_image_format(saved), "GIF") + self.assertEqual(saved, raw) + + def test_forced_png_from_gif_reencodes_first_frame(self): + frames = [Image.new("RGB", (6, 4), color) for color in ("red", "blue")] + buffer = BytesIO() + frames[0].save( + buffer, + format="GIF", + save_all=True, + append_images=frames[1:], + duration=100, + loop=0, + ) + raw = buffer.getvalue() + for image in frames: + image.close() + with tempfile.TemporaryDirectory() as temp_dir, tempfile.TemporaryDirectory() as output_dir: + source = os.path.join(temp_dir, "provider.gif") + Path(source).write_bytes(raw) + results = save_temp_images( + [source], + "o1key-gif-png", + "png", + output_dir, + _folder_paths(output_dir), + naming_rule="自定义前缀", + ) + self.assertTrue(results[0]["filename"].endswith(".png")) + self.assertNotEqual(results[0].get("media"), "gif") + self.assertEqual( + detect_image_format(Path(output_dir, results[0]["filename"]).read_bytes()), + "PNG", + ) + + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_save_gif.py b/tests/test_save_gif.py new file mode 100644 index 0000000..46296d8 --- /dev/null +++ b/tests/test_save_gif.py @@ -0,0 +1,188 @@ +"""Tests for O1keySaveGIF — output save + custom-key GIF preview + passthrough.""" + +from __future__ import annotations + +import os +import sys +import tempfile +import unittest +from io import BytesIO +from pathlib import Path +from types import ModuleType, SimpleNamespace +from unittest.mock import patch + +import torch +from PIL import Image + + +PLUGIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CUSTOM_NODES_DIR = os.path.dirname(PLUGIN_DIR) +COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR) +for child in ("nodes", "utils", "clients"): + package = ModuleType(f"comfyui_o1key.{child}") + package.__path__ = [os.path.join(PLUGIN_DIR, child)] + sys.modules[package.__name__] = package +plugin_package = ModuleType("comfyui_o1key") +plugin_package.__path__ = [PLUGIN_DIR] +sys.modules[plugin_package.__name__] = plugin_package +model_management = ModuleType("comfy.model_management") +model_management.processing_interrupted = lambda: False +model_management.InterruptProcessingException = RuntimeError +sys.modules[model_management.__name__] = model_management +sys.path.insert(0, COMFY_ROOT) +sys.path.insert(0, CUSTOM_NODES_DIR) + + +def _make_gif_bytes(colors=("red", "blue", "green"), duration=100) -> bytes: + frames = [Image.new("RGB", (6, 4), color) for color in colors] + buf = BytesIO() + frames[0].save( + buf, + format="GIF", + save_all=True, + append_images=frames[1:], + duration=duration, + loop=0, + ) + return buf.getvalue() + + +class SaveGifHelperTests(unittest.TestCase): + def test_read_and_duration_helpers(self): + from comfyui_o1key.utils.gpt_image_media import ( + encode_gif_from_pil_images, + is_gif_bytes, + read_gif_bytes_from_path, + resolve_gif_frame_duration_ms, + ) + + self.assertEqual(resolve_gif_frame_duration_ms(fps=5.0, frame_duration_ms=0), 200) + self.assertEqual(resolve_gif_frame_duration_ms(fps=5.0, frame_duration_ms=120), 120) + data = _make_gif_bytes() + self.assertTrue(is_gif_bytes(data)) + with tempfile.TemporaryDirectory() as temp_dir: + path = os.path.join(temp_dir, "demo.gif") + Path(path).write_bytes(data) + self.assertEqual(read_gif_bytes_from_path(path), data) + self.assertIsNone(read_gif_bytes_from_path(os.path.join(temp_dir, "missing.gif"))) + png = os.path.join(temp_dir, "x.png") + Image.new("RGB", (2, 2), "white").save(png) + self.assertIsNone(read_gif_bytes_from_path(png)) + + frames = [Image.new("RGB", (4, 4), c) for c in ("red", "blue")] + encoded = encode_gif_from_pil_images(frames, duration_ms=80) + self.assertTrue(is_gif_bytes(encoded)) + + +class SaveGifNodeTests(unittest.TestCase): + def test_passthrough_writes_output_and_preview_payload(self): + from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview + + gif_bytes = _make_gif_bytes() + with tempfile.TemporaryDirectory() as source_dir, tempfile.TemporaryDirectory() as output_dir: + source = os.path.join(source_dir, "provider.gif") + Path(source).write_bytes(gif_bytes) + + def get_save_image_path(prefix, root, _w, _h): + return root, prefix, 1, "", prefix + + folder = SimpleNamespace( + get_output_directory=lambda: output_dir, + get_save_image_path=get_save_image_path, + ) + with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder): + result = O1keySaveGIF.execute(文件路径=source, 文件名前缀="ComfyUI") + + target = result.args[0] + ui_obj = result.ui + self.assertTrue(str(target).lower().endswith(".gif")) + self.assertTrue(Path(target).is_file()) + self.assertEqual(Path(target).read_bytes(), gif_bytes) + self.assertTrue(str(target).startswith(output_dir)) + self.assertIsInstance(ui_obj, SavedGifPreview) + data = ui_obj.as_dict() + # Custom key only — core must NOT see ``images`` or it will mount + # $$canvas-image-preview (static frame + "W x H") under our . + self.assertNotIn("images", data) + self.assertNotIn("animated", data) + self.assertIn(SavedGifPreview.UI_KEY, data) + entry = data[SavedGifPreview.UI_KEY][0] + self.assertEqual(entry["type"], "output") + self.assertTrue(str(entry["filename"]).lower().endswith(".gif")) + self.assertEqual(entry["filename"], Path(target).name) + self.assertEqual(entry["subfolder"], "") + + def test_image_metadata_passthrough_avoids_reencode(self): + from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview + from comfyui_o1key.utils.image_utils import pil_to_tensor + from comfyui_o1key.utils.gpt_image_media import expand_gif_frames + + gif_bytes = _make_gif_bytes() + with Image.open(BytesIO(gif_bytes)) as opened: + frames = expand_gif_frames(opened, gif_bytes) + tensor = pil_to_tensor(frames) + + with tempfile.TemporaryDirectory() as output_dir: + def get_save_image_path(prefix, root, _w, _h): + return root, prefix, 7, "", prefix + + folder = SimpleNamespace( + get_output_directory=lambda: output_dir, + get_save_image_path=get_save_image_path, + ) + with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder): + result = O1keySaveGIF.execute(图像=tensor, fps=5.0, 文件名前缀="meta") + + target = result.args[0] + self.assertEqual(Path(target).read_bytes(), gif_bytes) + data = result.ui.as_dict() + self.assertNotIn("images", data) + self.assertNotIn("animated", data) + self.assertTrue( + str(data[SavedGifPreview.UI_KEY][0]["filename"]).lower().endswith(".gif") + ) + + def test_image_batch_fallback_encodes_gif(self): + from comfyui_o1key.nodes.save_gif import O1keySaveGIF, SavedGifPreview + from comfyui_o1key.utils.image_utils import pil_to_tensor + from comfyui_o1key.utils.gpt_image_media import is_gif_bytes + + frames = [Image.new("RGB", (5, 3), c) for c in ("red", "green", "blue")] + tensor = pil_to_tensor(frames) + with tempfile.TemporaryDirectory() as output_dir: + def get_save_image_path(prefix, root, _w, _h): + return root, prefix, 3, "", prefix + + folder = SimpleNamespace( + get_output_directory=lambda: output_dir, + get_save_image_path=get_save_image_path, + ) + with patch("comfyui_o1key.nodes.save_gif.folder_paths", folder): + result = O1keySaveGIF.execute(图像=tensor, fps=10.0, 文件名前缀="anim") + + target = result.args[0] + ui_obj = result.ui + data = Path(target).read_bytes() + self.assertTrue(is_gif_bytes(data)) + payload = ui_obj.as_dict() + self.assertNotIn("images", payload) + self.assertNotIn("animated", payload) + self.assertIn(SavedGifPreview.UI_KEY, payload) + self.assertIsInstance(tensor, torch.Tensor) + + def test_schema_registers_chinese_labels(self): + from comfyui_o1key.nodes.save_gif import O1keySaveGIF + + schema = O1keySaveGIF.define_schema() + schema.validate() + self.assertEqual(schema.node_id, "O1keySaveGIF") + self.assertEqual(schema.display_name, "保存 GIF") + ids = [item.id for item in schema.inputs] + self.assertIn("文件路径", ids) + self.assertIn("图像", ids) + self.assertIn("文件名前缀", ids) + self.assertTrue(schema.is_output_node) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/gpt_image_media.py b/utils/gpt_image_media.py new file mode 100644 index 0000000..4c591e4 --- /dev/null +++ b/utils/gpt_image_media.py @@ -0,0 +1,294 @@ +"""GPT Image 2.6 SVG/GIF result helpers.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +from io import BytesIO +from typing import Iterable, List, Optional, Sequence + +from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError + + +def is_svg_bytes(data: bytes) -> bool: + if not data: + return False + head = data.lstrip()[:256].lower() + return head.startswith(b" bool: + return bool(data) and (data.startswith(b"GIF87a") or data.startswith(b"GIF89a")) + + +def expand_gif_frames(image: Image.Image, original_bytes: Optional[bytes] = None) -> List[Image.Image]: + """Return every GIF frame as a standalone RGBA image; keep container bytes on frame 0.""" + raw = original_bytes if isinstance(original_bytes, bytes) else getattr(image, "_o1key_original_bytes", None) + frames: List[Image.Image] = [] + try: + n_frames = int(getattr(image, "n_frames", 1) or 1) + except Exception: + n_frames = 1 + if n_frames <= 1 and not getattr(image, "is_animated", False): + frame = image.convert("RGBA") + if isinstance(raw, bytes): + setattr(frame, "_o1key_original_bytes", raw) + setattr(frame, "_o1key_original_format", "GIF") + frame.format = "GIF" + frames.append(frame) + return frames + + for index in range(n_frames): + try: + image.seek(index) + except EOFError: + break + frame = image.copy().convert("RGBA") + frame.format = "GIF" + if index == 0 and isinstance(raw, bytes): + setattr(frame, "_o1key_original_bytes", raw) + setattr(frame, "_o1key_original_format", "GIF") + setattr(frame, "_o1key_animation_bytes", raw) + frames.append(frame) + if not frames: + raise RuntimeError("GIF 结果无法解码为帧") + return frames + + +def animation_bytes_from_images(images: Iterable[Image.Image]) -> Optional[bytes]: + for image in images: + raw = getattr(image, "_o1key_animation_bytes", None) + if isinstance(raw, bytes) and is_gif_bytes(raw): + return raw + raw = getattr(image, "_o1key_original_bytes", None) + fmt = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper() + if isinstance(raw, bytes) and (fmt == "GIF" or is_gif_bytes(raw)): + return raw + return None + + +def read_gif_bytes_from_path(path: str) -> Optional[bytes]: + """Return GIF bytes from a filesystem path, or None if missing/not a GIF.""" + text = str(path or "").strip().strip('"').strip("'") + if not text: + return None + if not os.path.isfile(text): + return None + with open(text, "rb") as handle: + data = handle.read() + if not is_gif_bytes(data): + return None + return data + + +def resolve_gif_frame_duration_ms(fps: float = 5.0, frame_duration_ms: int = 0) -> int: + """Prefer explicit ms; otherwise derive from fps. Clamp to a usable GIF delay.""" + try: + explicit = int(frame_duration_ms or 0) + except (TypeError, ValueError): + explicit = 0 + if explicit > 0: + return max(20, explicit) + try: + fps_value = float(fps) + except (TypeError, ValueError): + fps_value = 5.0 + if fps_value <= 0: + fps_value = 5.0 + return max(20, int(round(1000.0 / fps_value))) + + +def encode_gif_from_pil_images( + images: Sequence[Image.Image], + *, + duration_ms: int = 200, + loop: int = 0, +) -> bytes: + """Encode a batch of PIL images into one animated GIF (fallback path).""" + frames = [img.convert("RGBA") for img in images if img is not None] + if not frames: + raise ValueError("没有可用于编码 GIF 的图像帧") + duration = max(20, int(duration_ms or 200)) + buffer = BytesIO() + frames[0].save( + buffer, + format="GIF", + save_all=True, + append_images=frames[1:], + duration=duration, + loop=loop, + disposal=2, + ) + data = buffer.getvalue() + if not is_gif_bytes(data): + raise RuntimeError("GIF 编码失败") + return data + + +def svg_bytes_from_image(image: Image.Image) -> Optional[bytes]: + raw = getattr(image, "_o1key_original_bytes", None) + fmt = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper() + if isinstance(raw, bytes) and (fmt == "SVG" or is_svg_bytes(raw)): + return raw + return None + + +def _svg_placeholder(svg_bytes: bytes, size: tuple[int, int] = (1024, 1024)) -> Image.Image: + image = Image.new("RGBA", size, (245, 247, 250, 255)) + draw = ImageDraw.Draw(image) + draw.rectangle((32, 32, size[0] - 32, size[1] - 32), outline=(80, 110, 180, 255), width=4) + try: + font = ImageFont.load_default() + except Exception: + font = None + text = "SVG 已保存\n(本机未安装矢量栅格化依赖,显示占位预览)" + draw.multiline_text((64, 72), text, fill=(40, 50, 70, 255), font=font, spacing=8) + preview = image + setattr(preview, "_o1key_original_bytes", svg_bytes) + setattr(preview, "_o1key_original_format", "SVG") + preview.format = "SVG" + return preview + + +def _rasterize_cairosvg(svg_bytes: bytes) -> Image.Image: + import cairosvg # type: ignore + + png_bytes = cairosvg.svg2png(bytestring=svg_bytes) + image = Image.open(BytesIO(png_bytes)) + image.load() + return image.convert("RGBA") + + +def _rasterize_with_cli(svg_bytes: bytes, command_builder) -> Image.Image: + with tempfile.TemporaryDirectory(prefix="o1key_svg_") as temp_dir: + src = os.path.join(temp_dir, "input.svg") + dst = os.path.join(temp_dir, "output.png") + with open(src, "wb") as handle: + handle.write(svg_bytes) + command = command_builder(src, dst) + completed = subprocess.run( + command, + capture_output=True, + check=False, + timeout=60, + ) + if completed.returncode != 0 or not os.path.isfile(dst): + stderr = (completed.stderr or b"").decode("utf-8", errors="replace") + raise RuntimeError(stderr or "svg rasterize failed") + with Image.open(dst) as image: + image.load() + return image.convert("RGBA") + + +def _rasterize_magick(svg_bytes: bytes) -> Image.Image: + magick = shutil.which("magick") or shutil.which("convert") + if not magick: + raise RuntimeError("ImageMagick not found") + + def build(src: str, dst: str): + return [magick, src, dst] + + return _rasterize_with_cli(svg_bytes, build) + + +def _rasterize_inkscape(svg_bytes: bytes) -> Image.Image: + inkscape = shutil.which("inkscape") + if not inkscape: + raise RuntimeError("Inkscape not found") + + def build(src: str, dst: str): + return [inkscape, src, "--export-type=png", f"--export-filename={dst}"] + + return _rasterize_with_cli(svg_bytes, build) + + +def rasterize_svg(svg_bytes: bytes) -> Image.Image: + """Rasterize SVG for IMAGE preview; always preserve original SVG bytes on the result.""" + if not isinstance(svg_bytes, (bytes, bytearray)) or not svg_bytes: + raise ValueError("SVG 数据为空") + data = bytes(svg_bytes) + last_error: Exception | None = None + for renderer in (_rasterize_cairosvg, _rasterize_magick, _rasterize_inkscape): + try: + image = renderer(data) + setattr(image, "_o1key_original_bytes", data) + setattr(image, "_o1key_original_format", "SVG") + image.format = "SVG" + return image + except Exception as exc: # pragma: no cover - environment dependent + last_error = exc + continue + preview = _svg_placeholder(data) + if last_error is not None: + setattr(preview, "_o1key_svg_rasterize_error", str(last_error)) + return preview + + +def materialize_result_images( + data: bytes, + *, + requested_format: Optional[str] = None, + content_type: Optional[str] = None, +) -> List[Image.Image]: + """Turn provider bytes into one or more PIL images for Comfy IMAGE tensors.""" + if not isinstance(data, (bytes, bytearray)) or not data: + raise ValueError("结果图像数据为空") + payload = bytes(data) + fmt = str(requested_format or "").strip().lower() + ctype = str(content_type or "").strip().lower() + treat_as_svg = fmt == "svg" or "svg" in ctype or is_svg_bytes(payload) + if treat_as_svg: + return [rasterize_svg(payload)] + + try: + image = Image.open(BytesIO(payload)) + image.load() + except (OSError, UnidentifiedImageError) as exc: + if is_svg_bytes(payload): + return [rasterize_svg(payload)] + raise RuntimeError(f"结果图像无法解码: {exc}") from None + + image_format = str(image.format or "").upper() + if image_format == "JPG": + image_format = "JPEG" + setattr(image, "_o1key_original_bytes", payload) + setattr(image, "_o1key_original_format", image_format or None) + if image_format: + image.format = image_format + + treat_as_gif = fmt == "gif" or image_format == "GIF" or is_gif_bytes(payload) + if treat_as_gif: + return expand_gif_frames(image, payload) + return [image] + + +def write_bytes_atomic(path: str, data: bytes) -> None: + temporary_path = f"{path}.tmp" + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + try: + with open(temporary_path, "wb") as handle: + handle.write(data) + os.replace(temporary_path, path) + finally: + if os.path.exists(temporary_path): + try: + os.remove(temporary_path) + except OSError: + pass + + +__all__ = [ + "animation_bytes_from_images", + "encode_gif_from_pil_images", + "expand_gif_frames", + "is_gif_bytes", + "is_svg_bytes", + "materialize_result_images", + "rasterize_svg", + "read_gif_bytes_from_path", + "resolve_gif_frame_duration_ms", + "svg_bytes_from_image", + "write_bytes_atomic", +] diff --git a/utils/image_utils.py b/utils/image_utils.py index 705210f..b2cceef 100644 --- a/utils/image_utils.py +++ b/utils/image_utils.py @@ -404,14 +404,21 @@ def expand_batch_prompt_tasks(prompt: str, images_per_prompt: int) -> List[str]: return [task_prompt for task_prompt in prompts for _ in range(count)] -IMAGE_BATCH_MODE_GROUP_TO_MODELS = "一组搭配+多模特" -IMAGE_BATCH_MODE_CARTESIAN = "全部搭配×全部模特" -IMAGE_BATCH_MODE_SINGLE_REFERENCES = "单图素材批量" +IMAGE_BATCH_MODE_GROUP_TO_MODELS = "整组素材→多个目标" +IMAGE_BATCH_MODE_CARTESIAN = "每张素材×每张目标" +IMAGE_BATCH_MODE_SINGLE_REFERENCES = "每张素材单独出图" IMAGE_BATCH_MODES = ( IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_CARTESIAN, IMAGE_BATCH_MODE_SINGLE_REFERENCES, ) +# Labels shipped before the rename. They are accepted so old workflows and queued +# jobs keep running, but only the current labels are offered in the combo widget. +IMAGE_BATCH_MODE_ALIASES = { + "一组搭配+多模特": IMAGE_BATCH_MODE_GROUP_TO_MODELS, + "全部搭配×全部模特": IMAGE_BATCH_MODE_CARTESIAN, + "单图素材批量": IMAGE_BATCH_MODE_SINGLE_REFERENCES, +} def expand_image_generation_tasks( @@ -436,6 +443,8 @@ def expand_image_generation_tasks( count = int(images_per_pair) if count < 1: raise ValueError("每个组合的生图数量必须大于 0") + # Retired labels stay accepted so queued and saved workflows keep running. + batch_mode = IMAGE_BATCH_MODE_ALIASES.get(batch_mode, batch_mode) prompts = parse_batch_prompts(prompt) or [prompt.strip()] if not batch_enabled: pairings = [{ @@ -451,7 +460,7 @@ def expand_image_generation_tasks( model_total = max(0, int(model_reference_count)) if batch_mode == IMAGE_BATCH_MODE_SINGLE_REFERENCES: if outfit_total < 1: - raise ValueError("单图批量至少需要上传1张素材图") + raise ValueError("每张素材单独出图至少需要上传1张素材图") pairings = [ { "reference_indices": (outfit_index,), diff --git a/utils/mj_prompt.py b/utils/mj_prompt.py new file mode 100644 index 0000000..d2c9a40 --- /dev/null +++ b/utils/mj_prompt.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +"""Midjourney prompt helpers for o1key MJ image generation. + +Controlled flags are appended in a stable order. Duplicate user-written copies +of the same flags are stripped first so widget values win. +""" + +from __future__ import annotations + +import re +from typing import Optional, Sequence + +MJ_MODEL_ID = "mj-v8.2" + +MJ_ASPECT_RATIO_OPTIONS = [ + "1:1", + "16:9", + "9:16", + "4:5", + "3:2", + "2:3", + "4:3", + "21:9", +] + +MJ_QUALITY_MIN = 1 +MJ_QUALITY_MAX = 4 +MJ_QUALITY_DEFAULT = 2 + +MJ_STYLIZE_MIN = 0 +MJ_STYLIZE_MAX = 1000 +MJ_STYLIZE_DEFAULT = 250 + +MJ_CHAOS_MIN = 0 +MJ_CHAOS_MAX = 100 +MJ_CHAOS_DEFAULT = 0 + +MJ_IW_MIN = 0.0 +MJ_IW_MAX = 3.0 +MJ_IW_DEFAULT = 1.0 + +MJ_WEIRD_MIN = 0 +MJ_WEIRD_MAX = 3000 +MJ_WEIRD_DEFAULT = 0 + +MJ_EXP_MIN = 0 +MJ_EXP_MAX = 100 +MJ_EXP_DEFAULT = 0 + +MJ_SW_MIN = 0 +MJ_SW_MAX = 1000 +MJ_SW_DEFAULT = 100 + +MJ_CONTENT_REF_MAX = 4 +MJ_STYLE_REF_MAX = 4 + +# Strip both short and long Midjourney spellings before we append ours. +_STRIP_PATTERNS = ( + re.compile(r"(?i)(?:^|\s)--ar(?:atio)?\s+\S+"), + re.compile(r"(?i)(?:^|\s)--q(?:uality)?\s+\S+"), + re.compile(r"(?i)(?:^|\s)--hd\b"), + re.compile(r"(?i)(?:^|\s)--iw\s+\S+"), + re.compile(r"(?i)(?:^|\s)--raw\b"), + re.compile(r"(?i)(?:^|\s)--s(?:tylize)?\s+\S+"), + re.compile(r"(?i)(?:^|\s)--c(?:haos)?\s+\S+"), + re.compile(r"(?i)(?:^|\s)--seed\s+\S+"), + re.compile(r"(?i)(?:^|\s)--weird\s+\S+"), + re.compile(r"(?i)(?:^|\s)--tile\b"), + re.compile(r"(?i)(?:^|\s)--exp\s+\S+"), + re.compile(r"(?i)(?:^|\s)--draft\b"), + re.compile(r"(?i)(?:^|\s)--no(?:\s+(?!--)\S+)+"), + re.compile(r"(?i)(?:^|\s)--sref(?:\s+(?!--)\S+)+"), + re.compile(r"(?i)(?:^|\s)--sw\s+\S+"), +) + +_SPACE_RE = re.compile(r"[ \t]{2,}") + + +def strip_controlled_mj_flags(prompt: str) -> str: + """Remove controlled Midjourney flags from free-form prompt text.""" + text = str(prompt or "") + for pattern in _STRIP_PATTERNS: + text = pattern.sub(" ", text) + text = _SPACE_RE.sub(" ", text) + return text.strip() + + +def _format_iw(value: float) -> str: + number = float(value) + if number.is_integer(): + return str(int(number)) + text = f"{number:.3f}".rstrip("0").rstrip(".") + return text or "0" + + +def _normalize_https_urls(urls: Optional[Sequence[str]], *, label: str) -> list[str]: + cleaned: list[str] = [] + for raw in urls or (): + url = str(raw or "").strip() + if not url: + continue + if not url.startswith("https://"): + raise ValueError(f"{label}必须使用临时素材 HTTPS URL") + cleaned.append(url) + return cleaned + + +def _prefix_content_ref_urls(base: str, urls: Sequence[str]) -> str: + """Prepend content-reference URLs that are not already present in the text.""" + extras: list[str] = [] + for url in urls: + if url and url not in base: + extras.append(url) + if not extras: + return base + if not base: + return " ".join(extras) + return " ".join(extras + [base]) + + +def build_mj_prompt( + prompt: str, + *, + aspect_ratio: str = "1:1", + quality: int = MJ_QUALITY_DEFAULT, + hd: bool = False, + image_weight: Optional[float] = None, + raw: bool = False, + stylize: int = MJ_STYLIZE_DEFAULT, + chaos: int = MJ_CHAOS_DEFAULT, + seed: int = -1, + has_reference_image: bool = False, + content_ref_urls: Optional[Sequence[str]] = None, + style_ref_urls: Optional[Sequence[str]] = None, + style_weight: int = MJ_SW_DEFAULT, + weird: int = MJ_WEIRD_DEFAULT, + tile: bool = False, + exp: int = MJ_EXP_DEFAULT, + draft: bool = False, + no_text: str = "", +) -> str: + """Assemble the final Midjourney prompt with controlled trailing flags. + + Stable order: + ``[content_ref_urls...] [base_prompt] [--no ...] --ar --q [--hd] [--iw] + [--sref ...] [--sw] [--raw] --s [--c] [--weird] [--tile] [--exp] + [--draft] [--seed]`` + """ + base = strip_controlled_mj_flags(prompt) + if not base: + raise ValueError("提示词不能为空") + + ratio = str(aspect_ratio or "").strip() + if ratio not in MJ_ASPECT_RATIO_OPTIONS: + raise ValueError(f"画面比例无效:{aspect_ratio}") + + quality_value = int(quality) + if quality_value < MJ_QUALITY_MIN or quality_value > MJ_QUALITY_MAX: + raise ValueError(f"渲染质量须为 {MJ_QUALITY_MIN}–{MJ_QUALITY_MAX}") + + stylize_value = int(stylize) + if stylize_value < MJ_STYLIZE_MIN or stylize_value > MJ_STYLIZE_MAX: + raise ValueError(f"风格化须为 {MJ_STYLIZE_MIN}–{MJ_STYLIZE_MAX}") + + chaos_value = int(chaos) + if chaos_value < MJ_CHAOS_MIN or chaos_value > MJ_CHAOS_MAX: + raise ValueError(f"差异度须为 {MJ_CHAOS_MIN}–{MJ_CHAOS_MAX}") + + weird_value = int(weird) + if weird_value < MJ_WEIRD_MIN or weird_value > MJ_WEIRD_MAX: + raise ValueError(f"怪异度须为 {MJ_WEIRD_MIN}–{MJ_WEIRD_MAX}") + + exp_value = int(exp) + if exp_value < MJ_EXP_MIN or exp_value > MJ_EXP_MAX: + raise ValueError(f"实验值须为 {MJ_EXP_MIN}–{MJ_EXP_MAX}") + + prompt_content_urls = _normalize_https_urls( + content_ref_urls, label="内容参考图" + ) + style_urls = _normalize_https_urls(style_ref_urls, label="风格参考图") + + text_body = _prefix_content_ref_urls(base, prompt_content_urls) + + no_value = str(no_text or "").strip() + parts: list[str] = [text_body] + if no_value: + parts.append(f"--no {no_value}") + + parts.extend([f"--ar {ratio}", f"--q {quality_value}"]) + if hd: + parts.append("--hd") + + if has_reference_image or prompt_content_urls: + if image_weight is None: + iw_value = MJ_IW_DEFAULT + else: + iw_value = float(image_weight) + if iw_value < MJ_IW_MIN or iw_value > MJ_IW_MAX: + raise ValueError(f"参考图权重须为 {MJ_IW_MIN:g}–{MJ_IW_MAX:g}") + parts.append(f"--iw {_format_iw(iw_value)}") + + if style_urls: + parts.append("--sref " + " ".join(style_urls)) + sw_value = int(style_weight) + if sw_value < MJ_SW_MIN or sw_value > MJ_SW_MAX: + raise ValueError(f"风格权重须为 {MJ_SW_MIN}–{MJ_SW_MAX}") + parts.append(f"--sw {sw_value}") + + if raw: + parts.append("--raw") + + parts.append(f"--s {stylize_value}") + + if chaos_value > 0: + parts.append(f"--c {chaos_value}") + + if weird_value > 0: + parts.append(f"--weird {weird_value}") + + if tile: + parts.append("--tile") + + if exp_value > 0: + parts.append(f"--exp {exp_value}") + + if draft: + parts.append("--draft") + + seed_value = int(seed) + if seed_value >= 0: + parts.append(f"--seed {seed_value}") + + return " ".join(parts) + + +__all__ = [ + "MJ_ASPECT_RATIO_OPTIONS", + "MJ_CHAOS_DEFAULT", + "MJ_CHAOS_MAX", + "MJ_CHAOS_MIN", + "MJ_CONTENT_REF_MAX", + "MJ_EXP_DEFAULT", + "MJ_EXP_MAX", + "MJ_EXP_MIN", + "MJ_IW_DEFAULT", + "MJ_IW_MAX", + "MJ_IW_MIN", + "MJ_MODEL_ID", + "MJ_QUALITY_DEFAULT", + "MJ_QUALITY_MAX", + "MJ_QUALITY_MIN", + "MJ_STYLE_REF_MAX", + "MJ_STYLIZE_DEFAULT", + "MJ_STYLIZE_MAX", + "MJ_STYLIZE_MIN", + "MJ_SW_DEFAULT", + "MJ_SW_MAX", + "MJ_SW_MIN", + "MJ_WEIRD_DEFAULT", + "MJ_WEIRD_MAX", + "MJ_WEIRD_MIN", + "build_mj_prompt", + "strip_controlled_mj_flags", +] diff --git a/utils/o1key_image_catalog.py b/utils/o1key_image_catalog.py index 6d558bb..072441b 100644 --- a/utils/o1key_image_catalog.py +++ b/utils/o1key_image_catalog.py @@ -9,16 +9,17 @@ from .nano_banana_models import ( GPT_IMAGE_MODEL_OPTIONS = [ - "gpt-image-2", + "gpt-image-2.6-sunburst", + "gpt-image-2.6-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare", + "gpt-image-2", ] SEEDREAM_MODEL_OPTIONS = ["Seedream 5.0 Pro"] UNIFIED_IMAGE_MODEL_OPTIONS = [ *NANO_BANANA_MODEL_OPTIONS[:3], *GPT_IMAGE_MODEL_OPTIONS, *SEEDREAM_MODEL_OPTIONS, - *NANO_BANANA_MODEL_OPTIONS[3:], ] UNIFIED_IMAGE_ROUTE_OPTIONS = list(NANO_BANANA_ROUTE_OPTIONS) @@ -65,8 +66,30 @@ GPT_IMAGE_EXACT_SIZE_OPTIONS = [ ] GPT_IMAGE_QUALITY_OPTIONS = ["高", "中", "低", "自动"] GPT_IMAGE_25_QUALITY_OPTIONS = [*GPT_IMAGE_QUALITY_OPTIONS, "超高", "最高"] -GPT_IMAGE_OUTPUT_FORMAT_OPTIONS = ["jpeg", "png", "webp"] +GPT_IMAGE_COMPLEXITY_OPTIONS = ["高", "中", "低"] +GPT_IMAGE_COMPLEXITY_API_VALUES = ("low", "medium", "high") +GPT_IMAGE_COMPLEXITY_LABEL_TO_API = { + "高": "high", + "中": "medium", + "低": "low", + "high": "high", + "medium": "medium", + "low": "low", +} +GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS = ["jpeg", "png", "webp"] +GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS = ["svg", "gif"] +GPT_IMAGE_OUTPUT_FORMAT_OPTIONS = list(GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS) +GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS = [ + *GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS, + *GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS, +] GPT_IMAGE_BACKGROUND_OPTIONS = ["auto", "transparent", "opaque"] +GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT = 9 +GPT_IMAGE_GIF_FRAME_COUNT_MIN = 2 +GPT_IMAGE_GIF_FRAME_COUNT_MAX = 64 +GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT = 200 +GPT_IMAGE_GIF_FRAME_DURATION_MIN = 20 +GPT_IMAGE_GIF_FRAME_DURATION_MAX = 2000 GPT_IMAGE_SIZE_MATRIX = { ("1K", "1:1"): "1024x1024", ("1K", "3:2"): "1536x1024", @@ -117,6 +140,80 @@ SEEDREAM_SIZE_MATRIX = { } + +def is_gpt_image_26_model(model: str) -> bool: + name = str(model or "").strip() + if name in GPT_IMAGE_MODEL_OPTIONS: + return name.startswith("gpt-image-2.6-") + for base in GPT_IMAGE_MODEL_OPTIONS: + if name in {base, f"{base}-sp", f"{base}-sd"}: + return base.startswith("gpt-image-2.6-") + return name.startswith("gpt-image-2.6-") + + +def gpt_image_output_formats_for_model(model: str) -> list[str]: + if is_gpt_image_26_model(model): + return list(GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS) + return list(GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS) + + +def resolve_gpt_image_output_format(model: str, output_format: str | None) -> str: + value = str(output_format or "png").strip().lower() + allowed = gpt_image_output_formats_for_model(model) + if value not in allowed: + if value in GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS: + raise ValueError("SVG / GIF 输出仅支持 GPT Image 2.6 系列模型") + raise ValueError("GPT Image 输出格式无效") + return value + + +def resolve_gpt_image_frame_count(output_format: str, frame_count=None) -> int | None: + if str(output_format or "").strip().lower() != "gif": + return None + if frame_count is None or frame_count == "": + return GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT + try: + value = int(frame_count) + except (TypeError, ValueError) as exc: + raise ValueError("GIF 帧数无效") from exc + if value < GPT_IMAGE_GIF_FRAME_COUNT_MIN or value > GPT_IMAGE_GIF_FRAME_COUNT_MAX: + raise ValueError( + f"GIF 帧数仅支持 {GPT_IMAGE_GIF_FRAME_COUNT_MIN}–{GPT_IMAGE_GIF_FRAME_COUNT_MAX}" + ) + return value + + +def resolve_gpt_image_frame_duration_ms(output_format: str, frame_duration_ms=None) -> int | None: + if str(output_format or "").strip().lower() != "gif": + return None + if frame_duration_ms is None or frame_duration_ms == "": + value = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT + else: + try: + value = int(frame_duration_ms) + except (TypeError, ValueError) as exc: + raise ValueError("GIF 帧时长无效") from exc + if value < GPT_IMAGE_GIF_FRAME_DURATION_MIN or value > GPT_IMAGE_GIF_FRAME_DURATION_MAX: + raise ValueError( + f"GIF 帧时长仅支持 {GPT_IMAGE_GIF_FRAME_DURATION_MIN}–{GPT_IMAGE_GIF_FRAME_DURATION_MAX} 毫秒" + ) + return int(round(value / 10.0) * 10) + + +def validate_gpt_image_vector_output( + model: str, + output_format: str, + *, + has_images: bool = False, + has_mask: bool = False, +) -> None: + fmt = resolve_gpt_image_output_format(model, output_format) + if fmt not in GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS: + return + if has_images or has_mask: + raise ValueError("SVG / GIF 仅支持纯文生图,不能带参考图或蒙版") + + def is_gpt_image_model(model: str) -> bool: return model in GPT_IMAGE_MODEL_OPTIONS @@ -124,8 +221,8 @@ def is_gpt_image_model(model: str) -> bool: def resolve_gpt_image_quality(model_name: str, quality: str) -> str: """Resolve a displayed GPT quality for the selected model family.""" if quality in {"超高", "最高"}: - if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith("gpt-image-2.5-"): - raise ValueError("超高和最高质量仅支持 GPT Image 2.5 系列模型") + if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith(("gpt-image-2.5-", "gpt-image-2.6-")): + raise ValueError("超高和最高质量仅支持 GPT Image 2.5 / 2.6 系列模型") return {"超高": "xhigh", "最高": "max"}[quality] try: return {"高": "high", "中": "medium", "低": "low", "自动": "auto"}[quality] @@ -133,6 +230,19 @@ def resolve_gpt_image_quality(model_name: str, quality: str) -> str: raise ValueError("GPT Image 质量参数无效") from None +def resolve_gpt_image_complexity(model_name: str, complexity: str | None) -> str | None: + """Only 2.6 models send complexity; inactive controls retain their value.""" + if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith("gpt-image-2.6-"): + return None + if complexity is None: + return "high" + raw = str(complexity).strip() + value = GPT_IMAGE_COMPLEXITY_LABEL_TO_API.get(raw) or GPT_IMAGE_COMPLEXITY_LABEL_TO_API.get(raw.lower()) + if value not in GPT_IMAGE_COMPLEXITY_API_VALUES: + raise ValueError("GPT Image 复杂度仅支持 低 / 中 / 高") + return value + + def is_seedream_model(model: str) -> bool: return model in SEEDREAM_MODEL_OPTIONS @@ -200,6 +310,10 @@ __all__ = [ "GPT_IMAGE_ASPECT_RATIO_OPTIONS", "GPT_IMAGE_BACKGROUND_OPTIONS", "GPT_IMAGE_COUNTS", + "GPT_IMAGE_COMPLEXITY_OPTIONS", + "GPT_IMAGE_COMPLEXITY_API_VALUES", + "GPT_IMAGE_COMPLEXITY_LABEL_TO_API", + "resolve_gpt_image_complexity", "GPT_IMAGE_EXACT_SIZE_OPTIONS", "GPT_IMAGE_MODEL_OPTIONS", "GPT_IMAGE_25_QUALITY_OPTIONS", @@ -226,4 +340,19 @@ __all__ = [ "resolve_gpt_image_quality", "resolve_seedream_size", "resolve_seedream_layer_size", + "GPT_IMAGE_26_EXTRA_OUTPUT_FORMAT_OPTIONS", + "GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS", + "GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT", + "GPT_IMAGE_GIF_FRAME_COUNT_MAX", + "GPT_IMAGE_GIF_FRAME_COUNT_MIN", + "GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT", + "GPT_IMAGE_GIF_FRAME_DURATION_MAX", + "GPT_IMAGE_GIF_FRAME_DURATION_MIN", + "GPT_IMAGE_RASTER_OUTPUT_FORMAT_OPTIONS", + "gpt_image_output_formats_for_model", + "is_gpt_image_26_model", + "resolve_gpt_image_frame_count", + "resolve_gpt_image_frame_duration_ms", + "resolve_gpt_image_output_format", + "validate_gpt_image_vector_output", ] diff --git a/utils/o1key_image_jobs.py b/utils/o1key_image_jobs.py index 3217ae0..d4a1253 100644 --- a/utils/o1key_image_jobs.py +++ b/utils/o1key_image_jobs.py @@ -21,6 +21,11 @@ from .o1key_image_catalog import ( BANANA_RESOLUTION_OPTIONS, GPT_IMAGE_ASPECT_RATIO_OPTIONS, GPT_IMAGE_BACKGROUND_OPTIONS, + resolve_gpt_image_complexity, + resolve_gpt_image_frame_count, + resolve_gpt_image_frame_duration_ms, + resolve_gpt_image_output_format, + validate_gpt_image_vector_output, GPT_IMAGE_EXACT_SIZE_OPTIONS, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, GPT_IMAGE_COUNTS, @@ -44,11 +49,13 @@ from .o1key_image_catalog import ( ) from .http_error import format_o1key_image_error from .image_utils import ( + IMAGE_BATCH_MODE_ALIASES, IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_SINGLE_REFERENCES, IMAGE_BATCH_MODES, expand_image_generation_tasks, ) +from .gpt_image_media import animation_bytes_from_images, svg_bytes_from_image, write_bytes_atomic from .o1key_image_save import ( DEFAULT_SAVE_NAMING_RULE, detect_image_format, @@ -341,7 +348,7 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]: payload.get("resolution") or UNIFIED_IMAGE_SMART_RESOLUTION ).strip() aspect_ratio = str(payload.get("aspect_ratio") or "智能").strip() - thinking = str(payload.get("thinking_level") or "低").strip() + thinking = str(payload.get("thinking_level") or "高").strip() if model not in MODELS: raise ValueError("模型无效") if model_route not in MODEL_ROUTES: @@ -349,7 +356,7 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]: google_search = model in {"Nano Banana 2.1", "Nano Banana 2"} and payload.get("google_search") is True quality = str(payload.get("quality") or "自动").strip() resize_mode = str( - payload.get("resize_mode") or ("智能缩放" if is_gpt_image_model(model) else "不缩放") + payload.get("resize_mode") or "智能缩放" ).strip() if resize_mode not in {"不缩放", "智能缩放"}: raise ValueError("缩放图片参数无效") @@ -366,13 +373,17 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]: raise ValueError("GPT Image 分辨率无效") if aspect_ratio not in GPT_IMAGE_ASPECT_RATIO_OPTIONS: raise ValueError("GPT Image 宽高比无效") + complexity = resolve_gpt_image_complexity(model, payload.get("complexity")) resolve_gpt_image_quality(model, quality) - if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: - raise ValueError("GPT Image 输出格式无效") + output_format = resolve_gpt_image_output_format(model, output_format) if background not in GPT_IMAGE_BACKGROUND_OPTIONS: raise ValueError("GPT Image 背景参数无效") - if background == "transparent" and output_format == "jpeg": + if background == "transparent" and output_format not in {"png", "webp"}: raise ValueError("GPT Image 透明背景仅支持 PNG 或 WebP 输出格式") + frame_count = resolve_gpt_image_frame_count(output_format, payload.get("frame_count")) + frame_duration_ms = resolve_gpt_image_frame_duration_ms( + output_format, payload.get("frame_duration_ms") + ) elif is_seedream_model(model): output_format = str( payload.get("output_format") or ("png" if layer_decomposition else "jpeg") @@ -437,6 +448,8 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]: batch_mode = str( payload.get("batch_mode") or IMAGE_BATCH_MODE_GROUP_TO_MODELS ).strip() + # Retired labels are still accepted so already-queued jobs keep their pairing. + batch_mode = IMAGE_BATCH_MODE_ALIASES.get(batch_mode, batch_mode) if batch_enabled and batch_mode not in IMAGE_BATCH_MODES: raise ValueError("批量模式无效") if not batch_enabled: @@ -558,8 +571,20 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]: "layer_decomposition": layer_decomposition, } if is_gpt_image_model(model): + validate_gpt_image_vector_output( + model, + output_format, + has_images=bool(safe_references) or bool(safe_model_references), + has_mask=bool(safe_mask), + ) job["output_format"] = output_format job["background"] = background + if complexity is not None: + job["complexity"] = complexity + if frame_count is not None: + job["frame_count"] = frame_count + if frame_duration_ms is not None: + job["frame_duration_ms"] = frame_duration_ms elif is_seedream_model(model): job["output_format"] = output_format elif google_search: @@ -762,8 +787,13 @@ def _provider_result_format(image: Image.Image) -> str: detected = detect_image_format(raw) if isinstance(raw, bytes) else None if detected == "JPEG": return "jpg" - if detected in {"PNG", "WEBP"}: + if detected in {"PNG", "WEBP", "GIF", "SVG"}: return detected.lower() + hinted = str(getattr(image, "_o1key_original_format", "") or getattr(image, "format", "") or "").upper() + if hinted == "JPEG": + return "jpg" + if hinted in {"PNG", "WEBP", "GIF", "SVG"}: + return hinted.lower() return "png" @@ -773,7 +803,7 @@ def _write_provider_result(image: Image.Image, output_path: str) -> None: detected = detect_image_format(raw) if isinstance(raw, bytes) else None temporary_path = f"{output_path}.tmp" try: - if detected in {"PNG", "JPEG", "WEBP"}: + if detected in {"PNG", "JPEG", "WEBP", "GIF", "SVG"}: with open(temporary_path, "wb") as handle: handle.write(raw) else: @@ -1066,6 +1096,7 @@ async def _execute_gpt_image_job( actual_model = resolve_gpt_image_model(job["model"], job["model_route"]) quality = resolve_gpt_image_quality(job["model"], job["quality"]) + complexity = resolve_gpt_image_complexity(job["model"], job.get("complexity")) client = GptImageClient() client.base_url = get_base_url_by_route() client.response_log_enabled = False @@ -1170,6 +1201,11 @@ async def _execute_gpt_image_job( started_at = time.monotonic() heartbeat = asyncio.create_task(_heartbeat()) try: + frame_kwargs = {} + if job.get("frame_count") is not None: + frame_kwargs["frame_count"] = job["frame_count"] + if job.get("frame_duration_ms") is not None: + frame_kwargs["frame_duration_ms"] = job["frame_duration_ms"] images = await client.generate_image_async( prompt=job["task_prompts"][request_index], model=actual_model, @@ -1187,6 +1223,8 @@ async def _execute_gpt_image_job( mask_tensor=mask_tensor, output_format=job["output_format"], background=job["background"], + **({"complexity": complexity} if complexity is not None else {}), + **frame_kwargs, resize_mode=job["resize_mode"], progress_callback=lambda value: _update_request_progress( request_index, @@ -1209,30 +1247,76 @@ async def _execute_gpt_image_job( if not images: raise RuntimeError(f"第 {request_index + 1} 次请求没有返回图片") _update_request_progress(request_index, 0.96) - selected = images[0] - filename = _result_filename( - job, - request_index, - 0, - _provider_result_format(selected), - ) - target = os.path.join(output_path, filename) - await asyncio.to_thread( - _write_provider_result, - selected, - target, - ) - descriptor = { - "filename": filename, - "subfolder": relative_subfolder, - "type": "temp", - "batch_id": job["batch_id"], - "request_index": request_index + 1, - "result_index": 1, - } - _publish_partial_images(progress_callback, [descriptor]) + descriptors: list[dict[str, Any]] = [] + anim = animation_bytes_from_images(images) + svg = svg_bytes_from_image(images[0]) + if anim is not None: + filename = _result_filename(job, request_index, 0, "gif") + target = os.path.join(output_path, filename) + await asyncio.to_thread(write_bytes_atomic, target, anim) + descriptors.append({ + "filename": filename, + "subfolder": relative_subfolder, + "type": "temp", + "batch_id": job["batch_id"], + "request_index": request_index + 1, + "result_index": 1, + "media": "gif", + }) + elif svg is not None: + svg_name = _result_filename(job, request_index, 0, "svg") + svg_target = os.path.join(output_path, svg_name) + await asyncio.to_thread(write_bytes_atomic, svg_target, svg) + # Raster preview for Comfy IMAGE / native preview pipelines. + preview = images[0] + # Ensure preview file is PNG bytes, not SVG container. + from io import BytesIO + buf = BytesIO() + preview.convert("RGBA").save(buf, format="PNG", compress_level=4) + png_bytes = buf.getvalue() + png_name = _result_filename(job, request_index, 1, "png") + png_target = os.path.join(output_path, png_name) + await asyncio.to_thread(write_bytes_atomic, png_target, png_bytes) + descriptors.append({ + "filename": png_name, + "subfolder": relative_subfolder, + "type": "temp", + "batch_id": job["batch_id"], + "request_index": request_index + 1, + "result_index": 1, + "media": "image", + "svg_filename": svg_name, + }) + descriptors.append({ + "filename": svg_name, + "subfolder": relative_subfolder, + "type": "temp", + "batch_id": job["batch_id"], + "request_index": request_index + 1, + "result_index": 2, + "media": "svg", + }) + else: + selected = images[0] + filename = _result_filename( + job, + request_index, + 0, + _provider_result_format(selected), + ) + target = os.path.join(output_path, filename) + await asyncio.to_thread(_write_provider_result, selected, target) + descriptors.append({ + "filename": filename, + "subfolder": relative_subfolder, + "type": "temp", + "batch_id": job["batch_id"], + "request_index": request_index + 1, + "result_index": 1, + }) + _publish_partial_images(progress_callback, descriptors) _update_request_progress(request_index, 1.0) - return [descriptor] + return descriptors finally: for image in images: image.close() diff --git a/utils/o1key_image_save.py b/utils/o1key_image_save.py index 28319b4..7839247 100644 --- a/utils/o1key_image_save.py +++ b/utils/o1key_image_save.py @@ -24,7 +24,8 @@ from PIL.PngImagePlugin import PngInfo SAVE_FORMAT_OPTIONS = ("原始", "png", "jpg", "webp") SAVE_NAMING_RULE_OPTIONS = ("和主图一致", "自然数字", "自定义前缀") DEFAULT_SAVE_NAMING_RULE = "自定义前缀" -_FORMAT_EXTENSIONS = {"PNG": "png", "JPEG": "jpg", "WEBP": "webp"} +_FORMAT_EXTENSIONS = {"PNG": "png", "JPEG": "jpg", "WEBP": "webp", "GIF": "gif"} +_TEMP_RESULT_FORMATS = frozenset(_FORMAT_EXTENSIONS) # GIF kept as original bytes when 原始 _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" _SAVE_LOCK = threading.Lock() _UNSAFE_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]') @@ -107,6 +108,11 @@ def detect_image_format(data: bytes) -> str | None: return "JPEG" if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": return "WEBP" + if data.startswith(b"GIF87a") or data.startswith(b"GIF89a"): + return "GIF" + head = data.lstrip()[:256].lower() if data else b"" + if head.startswith(b" str | None: if value: return str(value) + # Kling 4.0 compatible task envelopes may place the result under + # output.media[].url instead of result_url/task_result.videos[].url. + output = _as_dict(source.get("output")) + media = output.get("media") + if isinstance(media, list): + for item in media: + item = _as_dict(item) + value = item.get("url") or item.get("video_url") + if value: + return str(value) + # 腾讯 Kling(v3-t)渠道:完成时视频地址在 metadata.url metadata = _as_dict(source.get("metadata")) value = metadata.get("url") or metadata.get("video_url") diff --git a/web/js/gifPreview.js b/web/js/gifPreview.js new file mode 100644 index 0000000..c72962a --- /dev/null +++ b/web/js/gifPreview.js @@ -0,0 +1,240 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; + +/** + * 「保存 GIF」emits custom UI key ``o1key_gif`` (NOT ``images``). + * + * ComfyUI core ``unsafeUpdatePreviews`` only hydrates canvas / video + * previews from ``getNodeOutputs(node).images``. Feeding SavedImages made + * core stack ``$$canvas-image-preview`` (static frame + "W x H") under our + * DOM . Stripping ``message.images`` in onExecuted does not clear the + * live ``app.nodeOutputs`` entry, so the canvas widget kept coming back. + * + * Fix: Python emits ``o1key_gif`` only; this extension mounts one . + * gpt image intentionally emits no GIF node preview. + */ + +const NODE_TYPES = new Set(["O1keySaveGIF"]); +const WIDGET_NAME = "o1key_gif_preview_widget"; +const UI_KEY = "o1key_gif"; +const CANVAS_PREVIEW_NAME = "$$canvas-image-preview"; +const EXT_NAME = "comfyui_o1key.gifPreview"; + +function isGifEntry(entry) { + const name = String(entry?.filename || entry?.name || ""); + return /\.gif$/i.test(name); +} + +function buildViewUrl(entry) { + if (!entry) return ""; + const filename = String(entry.filename || entry.name || ""); + if (!filename) return ""; + const params = new URLSearchParams(); + params.set("filename", filename); + const subfolder = String(entry.subfolder || ""); + if (subfolder) params.set("subfolder", subfolder); + params.set("type", String(entry.type || "output")); + return api.apiURL(`/view?${params.toString()}`); +} + +function pickGifEntry(message) { + const custom = Array.isArray(message?.[UI_KEY]) ? message[UI_KEY] : []; + const fromCustom = custom.find(isGifEntry) || custom[0]; + if (fromCustom) return fromCustom; + + // Legacy SavedImages payloads (pre-custom-key) — still show one , + // but clear live nodeOutputs.images so core cannot remount IMAGE_PREVIEW. + const images = Array.isArray(message?.images) ? message.images : []; + return images.find(isGifEntry) || null; +} + +/** + * Remove core ``images`` from the LIVE outputs store for this node. + * History snapshots already copied the payload; mutating the live entry + * only stops ``updatePreviews`` from driving ImagePreviewWidget. + */ +function clearLiveCoreImages(node) { + const store = app.nodeOutputs; + if (!store || node?.id == null) return; + + const idKeys = new Set([String(node.id), node.id]); + for (const key of Object.keys(store)) { + if (!idKeys.has(key) && !idKeys.has(String(key))) { + // Locator ids are usually the plain node id string; also match + // trailing ":id" / "id" forms used by execution-id helpers. + const asStr = String(key); + if (![...idKeys].some((id) => asStr === String(id) || asStr.endsWith(`:${id}`))) { + continue; + } + } + const entry = store[key]; + if (!entry || typeof entry !== "object") continue; + if ("images" in entry) delete entry.images; + if ("animated" in entry) delete entry.animated; + } +} + +function removeCoreCanvasPreview(node) { + node.imgs = undefined; + node.images = undefined; + node.imageIndex = undefined; + node.overIndex = undefined; + node.animatedImages = undefined; + + if (node.videoContainer) { + try { + node.videoContainer.replaceChildren(); + } catch (_err) { + /* ignore */ + } + node.videoContainer = undefined; + } + + if (!Array.isArray(node.widgets)) return; + for (let i = node.widgets.length - 1; i >= 0; i--) { + const widget = node.widgets[i]; + if (!widget) continue; + const name = String(widget.name || ""); + const type = String(widget.type || ""); + const isOurs = name === WIDGET_NAME; + const isCore = + !isOurs && + (name === CANVAS_PREVIEW_NAME || + type === "IMAGE_PREVIEW" || + type === "image" || + type === "imagecompare" || + type === "video" || + /canvas-image-preview/i.test(name)); + if (!isCore) continue; + try { + widget.onRemove?.(); + } catch (_err) { + /* ignore */ + } + node.widgets.splice(i, 1); + } +} + +function ensureGifWidget(node) { + if (node._o1keyGifContainer && node.widgets?.some((w) => w.name === WIDGET_NAME)) { + return node._o1keyGifContainer; + } + + const container = document.createElement("div"); + container.style.cssText = + "width:100%;display:flex;flex-direction:column;align-items:center;" + + "padding:4px;box-sizing:border-box;"; + + const img = document.createElement("img"); + img.alt = "GIF preview"; + img.style.cssText = + "width:100%;display:block;border-radius:4px;background:#111;" + + "object-fit:contain;max-height:480px;"; + + const label = document.createElement("div"); + label.style.cssText = + "font-size:10px;color:#aaa;margin-top:2px;text-align:center;word-break:break-all;"; + + container.appendChild(img); + container.appendChild(label); + + node._o1keyGifContainer = container; + node._o1keyGifImg = img; + node._o1keyGifLabel = label; + + if (!node.widgets?.some((w) => w.name === WIDGET_NAME)) { + const widget = node.addDOMWidget(WIDGET_NAME, "img", container, { + serialize: false, + hideOnZoom: false, + }); + widget.serializeValue = () => undefined; + widget.computeSize = function (width) { + const w = width ?? node.size?.[0] ?? 320; + const naturalW = img.naturalWidth || 0; + const naturalH = img.naturalHeight || 0; + if (naturalW > 0 && naturalH > 0) { + const innerW = Math.max(w - 16, 10); + const h = Math.round((innerW * naturalH) / naturalW); + return [w, Math.min(h, 480) + 28]; + } + return [w, 260]; + }; + } + + img.addEventListener("load", () => { + const w = Math.max(node.size?.[0] || 0, 320); + const naturalW = img.naturalWidth || 1; + const naturalH = img.naturalHeight || 1; + const innerW = Math.max(w - 16, 10); + const h = Math.min(Math.round((innerW * naturalH) / naturalW), 480) + 70; + node.setSize([w, Math.max(node.size?.[1] || 0, h)]); + node.setDirtyCanvas(true, true); + }); + + return container; +} + +function showGifPreview(node, entry) { + const url = buildViewUrl(entry); + if (!url) return; + + clearLiveCoreImages(node); + removeCoreCanvasPreview(node); + ensureGifWidget(node); + + if (node._o1keyGifImg) { + node._o1keyGifImg.src = url; + } + if (node._o1keyGifLabel) { + node._o1keyGifLabel.textContent = String(entry.filename || entry.name || ""); + } + + // Keep heuristics sane, but never leave imgs populated for IMAGE_PREVIEW. + node.previewMediaType = "image"; + removeCoreCanvasPreview(node); + node.setDirtyCanvas(true, true); +} + +app.registerExtension({ + name: EXT_NAME, + + async beforeRegisterNodeDef(nodeType, nodeData) { + if (!NODE_TYPES.has(nodeData?.name)) return; + + const origOnExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + const gif = pickGifEntry(message); + + // Always strip live core image previews for this node type — + // new payloads have no ``images``; legacy ones must be cleared + // from app.nodeOutputs so updatePreviews cannot remount. + clearLiveCoreImages(this); + + if (gif) { + if (origOnExecuted) { + const rest = Object.assign({}, message); + delete rest.images; + delete rest.animated; + origOnExecuted.call(this, rest); + } + showGifPreview(this, gif); + return; + } + + if (origOnExecuted) { + origOnExecuted.apply(this, arguments); + } + }; + }, + + /** + * History / queue restore updates nodeOutputs then may redraw before + * onExecuted; clear any stale ``images`` left from older SavedImages runs. + */ + async nodeCreated(node) { + if (!NODE_TYPES.has(node?.comfyClass || node?.type)) return; + // Light one-shot: if outputs already present without our key, ignore. + // Real preview is applied in onExecuted (also fired on history load). + clearLiveCoreImages(node); + }, +}); diff --git a/web/js/gptImageQuality.js b/web/js/gptImageQuality.js index fba1f7e..2a63685 100644 --- a/web/js/gptImageQuality.js +++ b/web/js/gptImageQuality.js @@ -4,19 +4,66 @@ const NODE_TYPES = new Set(["O1keyGPTImage", "O1keyGPTImageBatch"]); const BASE_QUALITY_OPTIONS = ["高", "中", "低", "自动"]; const GPT_IMAGE_25_QUALITY_OPTIONS = [...BASE_QUALITY_OPTIONS, "超高", "最高"]; const QUALITY_FALLBACK = "自动"; +const RASTER_FORMATS = ["png", "jpeg", "webp"]; +const FORMAT_26 = [...RASTER_FORMATS, "svg", "gif"]; +const BATCH_RASTER = ["原始", "JPEG", "PNG", "WebP"]; +const BATCH_26 = [...BATCH_RASTER, "SVG", "GIF"]; function findWidget(node, name) { return node.widgets?.find((widget) => widget.name === name); } +function setWidgetHidden(widget, hidden) { + if (!widget) return; + if (!("__o1keyOriginalComputeSize" in widget)) { + widget.__o1keyOriginalComputeSize = widget.computeSize; + } + widget.hidden = hidden; + widget.options ??= {}; + widget.options.hidden = hidden; + if (hidden) widget.computeSize = () => [0, -4]; + else if (widget.__o1keyOriginalComputeSize) { + widget.computeSize = widget.__o1keyOriginalComputeSize; + } else delete widget.computeSize; +} + +function hasReferenceOrMask(node) { + if (findWidget(node, "遮罩")?.value) return true; + const widgets = node.widgets || []; + for (const widget of widgets) { + if (/^参考图/.test(widget.name) && widget.value) return true; + } + // Connected inputs on modern nodes are not always mirrored into widget values. + const inputs = node.inputs || []; + for (const input of inputs) { + if (!input || input.link == null) continue; + if (input.name === "遮罩" || /^参考图/.test(input.name) || input.name === "参考图组") { + return true; + } + } + return false; +} + +function normalizeStandaloneFormat(value) { + return String(value || "png").trim().toLowerCase(); +} + +function normalizeBatchFormat(value) { + const raw = String(value || "原始"); + if (["svg", "SVG"].includes(raw)) return "SVG"; + if (["gif", "GIF"].includes(raw)) return "GIF"; + return raw; +} + function updateQualityOptions(node) { const modelWidget = findWidget(node, "模型"); const qualityWidget = findWidget(node, "质量"); if (!modelWidget || !qualityWidget) return; - const supports25Quality = - typeof modelWidget.value === "string" && modelWidget.value.startsWith("gpt-image-2.5-"); - const allowedOptions = supports25Quality ? GPT_IMAGE_25_QUALITY_OPTIONS : BASE_QUALITY_OPTIONS; + const model = String(modelWidget.value || ""); + const supportsExtendedQuality = /^gpt-image-2\.[56]-/.test(model); + const is26 = /^gpt-image-2\.6-/.test(model); + const allowedOptions = supportsExtendedQuality ? GPT_IMAGE_25_QUALITY_OPTIONS : BASE_QUALITY_OPTIONS; qualityWidget.options ??= {}; qualityWidget.options.values = [...allowedOptions]; @@ -25,6 +72,33 @@ function updateQualityOptions(node) { qualityWidget.callback?.(QUALITY_FALLBACK); } + setWidgetHidden(findWidget(node, "复杂度"), !is26); + + const formatWidget = findWidget(node, "输出格式") || findWidget(node, "图片输出格式"); + const isBatch = (node.comfyClass || node.type) === "O1keyGPTImageBatch"; + if (formatWidget) { + const blocked = hasReferenceOrMask(node); + let values = isBatch + ? (is26 ? BATCH_26 : BATCH_RASTER) + : (is26 ? FORMAT_26 : RASTER_FORMATS); + if (is26 && blocked) { + values = values.filter((value) => !/^(svg|gif|SVG|GIF)$/i.test(value)); + } + formatWidget.options ??= {}; + formatWidget.options.values = [...values]; + if (!values.includes(formatWidget.value)) { + formatWidget.value = isBatch ? "PNG" : "png"; + formatWidget.callback?.(formatWidget.value); + } + } + + const formatValue = isBatch + ? normalizeBatchFormat(formatWidget?.value) + : normalizeStandaloneFormat(formatWidget?.value); + const showFrames = is26 && (formatValue === "gif" || formatValue === "GIF"); + setWidgetHidden(findWidget(node, "帧数"), !showFrames); + setWidgetHidden(findWidget(node, "帧时长ms"), !showFrames); + node.setDirtyCanvas?.(true, true); } @@ -35,10 +109,29 @@ function guardNode(node) { if (!modelWidget || !qualityWidget) return; node.__o1keyGptImageQuality = true; - const originalModelCallback = modelWidget.callback; - modelWidget.callback = function () { - const result = originalModelCallback?.apply(this, arguments); - updateQualityOptions(node); + const watch = ["模型", "输出格式", "图片输出格式", "遮罩"]; + for (const name of watch) { + const widget = findWidget(node, name); + if (!widget) continue; + const original = widget.callback; + widget.callback = function () { + const result = original?.apply(this, arguments); + updateQualityOptions(node); + return result; + }; + } + + const originalOnConfigure = node.onConfigure; + node.onConfigure = function () { + const result = originalOnConfigure?.apply(this, arguments); + updateQualityOptions(this); + return result; + }; + + const originalOnConnectionsChange = node.onConnectionsChange; + node.onConnectionsChange = function () { + const result = originalOnConnectionsChange?.apply(this, arguments); + updateQualityOptions(this); return result; }; diff --git a/web/js/migrateWorkflow.js b/web/js/migrateWorkflow.js index 146bb31..029f1cf 100644 --- a/web/js/migrateWorkflow.js +++ b/web/js/migrateWorkflow.js @@ -13,9 +13,11 @@ const GPT_IMAGE_ROUTE_ALIASES = new Map([ ]); const GPT_IMAGE_NODE_TYPES = new Set(["O1keyGPTImage", "O1keyGPTImageBatch"]); const GPT_IMAGE_MODELS = new Set([ - "gpt-image-2", + "gpt-image-2.6-sunburst", + "gpt-image-2.6-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare", + "gpt-image-2", ]); const GPT_IMAGE_ROUTES = new Set(["畅速", "直连", "专线"]); const GPT_IMAGE_RESIZE_MODES = new Set(["不缩放", "智能缩放"]); @@ -23,6 +25,35 @@ const GPT_IMAGE_COLOR_CORRECTION_MODES = new Set(["不纠正", "智能纠正"]); const UNIFIED_COLOR_CORRECTION_MODES = new Set(["不纠正", "智能纠正"]); const GPT_IMAGE_BACKGROUNDS = new Set(["auto", "transparent", "opaque"]); const GPT_IMAGE_MODERATION_MODES = new Set(["自动", "低"]); +const GPT_IMAGE_COMPLEXITY_VALUES = new Set(["low", "medium", "high", "低", "中", "高"]); +const GPT_IMAGE_COMPLEXITY_TO_LABEL = Object.freeze({ + low: "低", + medium: "中", + high: "高", + 低: "低", + 中: "中", + 高: "高", +}); +function normalizeGptImageComplexityLabel(value) { + if (value == null) return "高"; + return GPT_IMAGE_COMPLEXITY_TO_LABEL[value] ?? GPT_IMAGE_COMPLEXITY_TO_LABEL[String(value).toLowerCase()] ?? "高"; +} +function placeGptImageComplexity(wv, complexity) { + // Returns true when widgets_values changed. + if (GPT_IMAGE_COMPLEXITY_VALUES.has(wv[3])) { + const normalized = normalizeGptImageComplexityLabel(wv[3]); + if (wv[3] !== normalized) { + wv[3] = normalized; + return true; + } + return false; + } + const label = normalizeGptImageComplexityLabel(complexity === undefined ? "高" : complexity); + // Old layouts stored complexity on the tail; new schema keeps it after 模型线路. + wv.splice(3, 0, label); + return true; +} +const GPT_IMAGE_CONTROL_AFTER_GENERATE = new Set(["fixed", "increment", "decrement", "randomize"]); const GPT_IMAGE_BATCH_OUTPUT_FORMATS = new Set(["原始", "JPEG", "PNG", "WebP"]); const GPT_IMAGE_BATCH_NAMING_RULES = new Set(["和原始图片名保持一致", "自然数字"]); @@ -33,12 +64,25 @@ function findLastIndex(values, predicate) { return -1; } +function batchGPTImagePathCountIndex(wv) { + // Current schema inserts 复杂度 after 模型线路, shifting "N个路径" from 6 -> 7. + if (/^([1-5])个路径$/.test(String(wv[7] ?? "")) && GPT_IMAGE_COMPLEXITY_VALUES.has(wv[3])) { + return 7; + } + if (/^([1-5])个路径$/.test(String(wv[6] ?? ""))) { + return 6; + } + return -1; +} + function batchGPTImageRandomSelectionIndex(wv) { - const match = /^([1-5])个路径$/.exec(String(wv[6] ?? "")); + const pathCountIndex = batchGPTImagePathCountIndex(wv); + if (pathCountIndex < 0) return -1; + const match = /^([1-5])个路径$/.exec(String(wv[pathCountIndex] ?? "")); if (!match) return -1; const pathCount = Number(match[1]); const pairingWidgetCount = pathCount >= 2 ? 1 : 0; - return 7 + pathCount + pairingWidgetCount; + return pathCountIndex + 1 + pathCount + pairingWidgetCount; } function batchGPTImageConcurrencyIndex(wv) { @@ -113,6 +157,10 @@ function findLegacySeedanceAssetWidgets(wv) { const NANO_BANANA_MODELS = new Set([ "Nano Banana Pro", "Nano Banana 2 Lite", "Nano Banana 2.1", "Nano Banana 2", "Nano Banana", ]); +const RETIRED_UNIFIED_IMAGE_MODELS = new Map([ + ["Nano Banana 2 Lite", "Nano Banana 2"], + ["Nano Banana", "Nano Banana 2"], +]); const NANO_BANANA_ROUTE_ALIASES = new Map([ ["特价", "畅速"], ["官方", "专线"], @@ -143,13 +191,18 @@ function isCurrentGPTImageBatchWidgetLayout(wv) { const resizeIndex = namingIndex + 2; const seedIndex = namingIndex + 3; const randomSelectionIndex = batchGPTImageRandomSelectionIndex(wv); + const hasFrameTail = ( + Number.isInteger(wv[seedIndex + 1]) + && Number.isInteger(wv[seedIndex + 2]) + && seedIndex + 2 === wv.length - 1 + ); return GPT_IMAGE_BATCH_OUTPUT_FORMATS.has(wv[formatIndex]) && GPT_IMAGE_BACKGROUNDS.has(wv[backgroundIndex]) && typeof wv[savePathIndex] === "string" && GPT_IMAGE_RESIZE_MODES.has(wv[resizeIndex]) && Number.isInteger(wv[seedIndex]) && formatIndex === randomSelectionIndex - && seedIndex === wv.length - 1; + && (seedIndex === wv.length - 1 || hasFrameTail); } function isGPTImageBatchWidgetLayoutWithRandomSelection(wv) { @@ -238,6 +291,16 @@ const MIGRATIONS = [ && typeof wv[9] === "string" && /^\s*\[/.test(wv[9]), apply: (wv) => wv.splice(8, 1), }, + { + type: "O1keyImageGenerator", + note: "将统一图片生成节点已下线的 Nano Banana 模型迁移到 Nano Banana 2", + when: (wv) => RETIRED_UNIFIED_IMAGE_MODELS.has(wv[1]), + apply: (wv) => { + const retiredModel = wv[1]; + wv[1] = RETIRED_UNIFIED_IMAGE_MODELS.get(retiredModel); + if (retiredModel === "Nano Banana 2 Lite" && wv[4] === "512") wv[4] = "1K"; + }, + }, { type: "O1keyAutoRedCast", note: "为旧版自动红偏校正补齐末尾 seed 参数", @@ -320,7 +383,7 @@ const MIGRATIONS = [ note: "为统一图片生成节点补齐可选批量出图字段", when: (wv) => wv.length >= 15 && wv.length < 18, apply: (wv) => { - const appendedDefaults = [false, "一组搭配+多模特", "[]"]; + const appendedDefaults = [false, "整组素材→多个目标", "[]"]; while (wv.length < 18) wv.push(appendedDefaults[wv.length - 15]); }, }, @@ -1380,6 +1443,8 @@ function migrateUnifiedSaveSettings(container) { const nodes = Array.isArray(container?.nodes) ? container.nodes : []; const nodesById = new Map(nodes.map((node) => [String(node?.id), node])); const defaults = ["自定义前缀", "o1key", "原始", ""]; + // 保存位置 是这份补齐序列的终点;老存档若还带着已停用的内容审查强度,就要多补一格。 + const saveSettingsTarget = (values) => (GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 22 : 21); let migrated = 0; for (const saveNode of nodes.filter((node) => node?.type === "O1keyImageSave")) { @@ -1395,7 +1460,7 @@ function migrateUnifiedSaveSettings(container) { if (generatorValues.length === 18) { generatorValues.push(legacy[3], legacy[0], legacy[1], legacy[2]); } else { - while (generatorValues.length < 22) { + while (generatorValues.length < saveSettingsTarget(generatorValues)) { generatorValues.push(defaults[generatorValues.length - 18]); } } @@ -1407,34 +1472,73 @@ function migrateUnifiedSaveSettings(container) { const values = generator?.widgets_values; if (!Array.isArray(values) || values.length < 18) continue; const before = values.length; - while (values.length < 22) values.push(defaults[values.length - 18]); + while (values.length < saveSettingsTarget(values)) values.push(defaults[values.length - 18]); if (values.length !== before) migrated++; } return migrated; } -function migrateUnifiedOnlineSearch(container) { +const RETIRED_ONLINE_SEARCH_VALUES = new Set(["关闭", "打开"]); + +// 批量模式 used model-centric labels before the industry-neutral rename. +const RETIRED_BATCH_MODE_LABELS = new Map([ + ["一组搭配+多模特", "整组素材→多个目标"], + ["全部搭配×全部模特", "每张素材×每张目标"], + ["单图素材批量", "每张素材单独出图"], +]); + +function migrateUnifiedBatchModeLabels(container) { const nodes = Array.isArray(container?.nodes) ? container.nodes : []; let migrated = 0; for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) { const values = node?.widgets_values; if (!Array.isArray(values)) continue; - const expectedLength = GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 22 : 21; - if (values.length !== expectedLength) continue; - values.push("关闭"); + // Match by label instead of index so the rewrite survives every array shape. + const index = values.findIndex((value) => RETIRED_BATCH_MODE_LABELS.has(value)); + if (index < 0) continue; + values[index] = RETIRED_BATCH_MODE_LABELS.get(values[index]); migrated++; } return migrated; } +function migrateRetiredOnlineSearch(container) { + const nodes = Array.isArray(container?.nodes) ? container.nodes : []; + let migrated = 0; + for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) { + const values = node?.widgets_values; + if (!Array.isArray(values) || values.length < 23) continue; + // 在线搜索 sat between 保存位置 and 图层拆分; the layer flag and the complexity label + // right behind it identify the slot without trusting a fixed index. + // Index 20 is 保存位置 in the current schema, so only the slots after it can be the + // retired field. The layer flag right behind it pins the position down. + for (let index = 21; index < values.length - 1; index += 1) { + if (!RETIRED_ONLINE_SEARCH_VALUES.has(values[index])) continue; + if (typeof values[index + 1] !== "boolean") continue; + const next = values[index + 2]; + const tailLike = next === undefined + || GPT_IMAGE_COMPLEXITY_VALUES.has(next) + || Number.isInteger(next); + if (!tailLike) continue; + values.splice(index, 1); + migrated++; + break; + } + } + return migrated; +} + function migrateUnifiedLayerDecomposition(container) { const nodes = Array.isArray(container?.nodes) ? container.nodes : []; let migrated = 0; for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) { const values = node?.widgets_values; if (!Array.isArray(values)) continue; - const expectedLength = GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 23 : 22; + const expectedLength = GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 22 : 21; if (values.length !== expectedLength) continue; + // A graph that already carries 图层拆分 ends on a boolean; only the pre-layers shape + // ends on 保存位置, so this keeps the rule idempotent. + if (typeof values.at(-1) === "boolean") continue; values.push(false); migrated++; } @@ -1469,6 +1573,51 @@ app.registerExtension({ migrated += migrateGrokVideoInputNames(node); const wv = node?.widgets_values; if (!Array.isArray(wv)) continue; + // GPT Image: peel append-only tails before legacy end-based rules. + // Current widget order: ..., 模型线路, 复杂度, 分辨率, ... seed, control?, 帧数?, 帧时长ms? + // Older graphs kept 复杂度 on the tail after seed/control; peel it and reinsert at index 3. + let frameDuration; + let frameCount; + let complexity; + let controlAfterGenerate; + if (GPT_IMAGE_NODE_TYPES.has(node.type)) { + const maybeDuration = wv.at(-1); + const maybeCount = wv.at(-2); + const maybeComplexity = wv.at(-3); + if ( + Number.isInteger(maybeDuration) + && Number.isInteger(maybeCount) + && GPT_IMAGE_COMPLEXITY_VALUES.has(maybeComplexity) + ) { + // Old tail: ..., complexity, frame_count, frame_duration_ms + frameDuration = wv.pop(); + frameCount = wv.pop(); + complexity = wv.pop(); + } else if ( + Number.isInteger(maybeDuration) + && Number.isInteger(maybeCount) + ) { + // New tail (complexity already mid-list): ..., control?/seed, frame_count, frame_duration_ms + frameDuration = wv.pop(); + frameCount = wv.pop(); + } else if (["low", "medium", "high"].includes(String(wv.at(-1)).toLowerCase())) { + // Old tails stored English complexity. Chinese 低 overlaps moderation — do not peel it. + complexity = wv.pop(); + } + // Repair graphs already scrambled by the pre-fix migration: + // [..., seed, control, 智能缩放, auto, (complexity...)] → drop bogus resize/bg after control. + if ( + GPT_IMAGE_CONTROL_AFTER_GENERATE.has(wv.at(-3)) + && GPT_IMAGE_RESIZE_MODES.has(wv.at(-2)) + && GPT_IMAGE_BACKGROUNDS.has(wv.at(-1)) + ) { + wv.splice(wv.length - 2, 2); + migrated++; + } + if (GPT_IMAGE_CONTROL_AFTER_GENERATE.has(wv.at(-1))) { + controlAfterGenerate = wv.pop(); + } + } for (const rule of MIGRATIONS) { if (rule.type !== "*" && node.type !== rule.type) continue; try { @@ -1480,23 +1629,37 @@ app.registerExtension({ console.warn(`[o1key] 工作流迁移失败: ${rule.note}`, e); } } + if (controlAfterGenerate !== undefined) wv.push(controlAfterGenerate); + if (GPT_IMAGE_NODE_TYPES.has(node.type)) { + // Keep 复杂度 at index 3 (after 模型线路). Missing => default 高. + if (placeGptImageComplexity(wv, complexity)) migrated++; + } else if (complexity !== undefined) { + wv.push(complexity); + } + if (frameCount !== undefined) wv.push(frameCount); + if (frameDuration !== undefined) wv.push(frameDuration); } for (const container of collectGraphContainers(graphData)) { migrated += migrateBatchNanoRandomInput(container); migrated += migrateUnifiedExternalPromptInput(container); migrated += migrateUnifiedSaveSettings(container); - migrated += migrateUnifiedOnlineSearch(container); + migrated += migrateUnifiedBatchModeLabels(container); migrated += migrateUnifiedLayerDecomposition(container); migrated += migrateUnifiedModeration(container); for (const node of container?.nodes || []) { const values = node?.widgets_values; - if (node?.type === "O1keyImageGenerator" && Array.isArray(values) - && values.length === 24 && values[23] === "" - && ["关闭", "打开"].includes(values[21]) && typeof values[22] === "boolean") { - values.pop(); // Retired non-serialized HTML panel value. - migrated++; - } + if (node?.type !== "O1keyImageGenerator" || !Array.isArray(values)) continue; + // A retired non-serialized HTML panel value can linger on the tail. Every real + // widget ends on a boolean or a number there (保存位置 also holds "" but always + // sits behind 格式), so an empty string on the tail is never a real value. + if (values.length < 22 || values.at(-1) !== "") continue; + const previous = values.at(-2); + if (typeof previous !== "boolean" && !Number.isInteger(previous)) continue; + values.pop(); + migrated++; } + // Runs last: the trailing-value repair above still relies on the old index. + migrated += migrateRetiredOnlineSearch(container); } if (migrated > 0) { console.log(`[o1key] 工作流参数迁移:已修复 ${migrated} 处参数或端口`); diff --git a/web/js/o1keyImageGenerator.js b/web/js/o1keyImageGenerator.js index 7e014e8..0fbfe82 100644 --- a/web/js/o1keyImageGenerator.js +++ b/web/js/o1keyImageGenerator.js @@ -11,10 +11,21 @@ const GENERATOR_DENSE_MIN_HEIGHT = 1110; const GENERATOR_BATCH_MIN_HEIGHT = 1215; const GENERATOR_DENSE_BATCH_MIN_HEIGHT = 1300; const GENERATOR_DEFAULT_SIZE = [560, 1035]; +const PROMPT_DEFAULT_HEIGHT = 106; +const USE_NATIVE_LITEGRAPH_PARAMETERS = true; +const NATIVE_PARAMETER_WIDGETS = new Set([ + "模型", "模型线路", "思考等级", "分辨率", "宽高比", "生图数量", "seed", + "质量", "输出格式", "缩放图片", "背景", "批量出图", "批量模式", "命名规则", + "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms", +]); const PROMPT_PLACEHOLDER = "描述你想生成的图片;多个提示词用独占一行的 --- 分隔;Seedream 图层拆分时可留空…"; const GENERATOR_OUTPUT_COUNT = 4; const GENERATOR_LAYER_OUTPUT_COUNT = 3; const SAVE_NODE_LAYOUT_SIZE = [300, 260]; +const SAVE_NODE_LAYOUT_GAP_X = 50; +const SAVE_NODE_LAYOUT_ORIGIN_GAP_X = 70; +const SAVE_NODE_CHROME_FALLBACK = 140; +const SAVE_NODE_CHROME_VUE_FALLBACK = 96; const SAVE_SLOT_GRID_NODE_INSET = 24; const SAVE_SLOT_GRID_PADDING_BORDER = 14; const SAVE_SLOT_GRID_GAP = 7; @@ -23,19 +34,44 @@ const SAVE_PREVIEW_MAX_HEIGHT = 720; const SAVE_PREVIEW_SIZE_LABEL_HEIGHT = 15; const GENERATOR_CHROME_HEIGHT = 48; const GENERATOR_PANEL_MIN_HEIGHT = GENERATOR_MIN_SIZE[1] - GENERATOR_CHROME_HEIGHT; +const GENERATOR_COMPACT_MIN_HEIGHT = 320; +const DOM_WIDGET_CHROME = 20; +const PANEL_CONTENT_GAP = 8; +const PANEL_CONTENT_PADDING = 18; +const ACTIONS_BASE_HEIGHT = 42; +const ACTIONS_STATUS_HEIGHT = 21; +const SETTLE_FIT_DELAYS = [60, 200, 600]; +// computeSize() is re-derived from the laid-out DOM, so it reports the node height plus a +// small rounding offset. Fitting every offset re-laid the node out forever (1510 <-> 1528); +// a dead zone keeps repeated fits idempotent while still absorbing real row changes. +const GENERATOR_FIT_TOLERANCE = 24; +// A single resize event can never move the corner this far; anything larger is a stale +// gesture (menu click without a matching pointerup) rather than the user dragging. +const GENERATOR_DRAG_OVERSHOOT = 400; +// The pointer must have gone down on the node itself before a resize counts as a drag. +const GENERATOR_DRAG_MARGIN = 12; const REFERENCE_LIGHTBOX_ID = "o1key-image-reference-lightbox"; const CANVAS_IMAGE_PICKER_ID = "o1key-canvas-image-picker"; const MODEL_OPTIONS = [ { value: "Nano Banana 2.1", label: "Nano Banana 2.1", description: "快速,批量" }, { value: "Nano Banana 2", label: "Nano Banana 2", description: "快速,批量" }, { value: "Nano Banana Pro", label: "Nano Banana Pro", description: "高质量资产" }, - { value: "gpt-image-2", label: "GPT Image 2", description: "高质量,编辑" }, - { value: "gpt-image-2.5-sunburst", label: "GPT Image 2.5 Sunburst", description: "最新,高质量" }, + { value: "gpt-image-2.6-sunburst", label: "GPT Image 2.6 Sunburst", description: "精修,细节还原" }, + { value: "gpt-image-2.6-flare", label: "GPT Image 2.6 Flare", description: "快速出图" }, + { value: "gpt-image-2.5-sunburst", label: "GPT Image 2.5 Sunburst", description: "高质量,细节" }, { value: "gpt-image-2.5-flare", label: "GPT Image 2.5 Flare", description: "快速,日常" }, + { value: "gpt-image-2", label: "GPT Image 2", description: "高质量,编辑" }, { value: "Seedream 5.0 Pro", label: "Seedream 5.0 Pro", description: "高质量,参考图,分层" }, - { value: "Nano Banana 2 Lite", label: "Nano Banana 2 Lite", description: "快速,草稿" }, - { value: "Nano Banana", label: "Nano Banana", description: "快速,草稿" }, ]; +const RETIRED_MODEL_ALIASES = Object.freeze({ + "Nano Banana 2 Lite": "Nano Banana 2", + "Nano Banana": "Nano Banana 2", +}); +function normalizeUnifiedModel(value) { + const candidate = String(value ?? "").trim(); + if (MODEL_OPTIONS.some((option) => option.value === candidate)) return candidate; + return RETIRED_MODEL_ALIASES[candidate] || "Nano Banana 2.1"; +} const ROUTES = [ { value: "畅速", label: "特价", description: "便宜" }, { value: "直连", label: "优质", description: "小贵" }, @@ -45,7 +81,6 @@ const THINKING_LEVEL_OPTIONS = [ { value: "低", label: "低", description: "耗时低,智力低" }, { value: "高", label: "高", description: "耗时高,智力高" }, ]; -const ONLINE_SEARCH_OPTIONS = ["关闭", "打开"]; const RESIZE_OPTIONS = [ { value: "不缩放", label: "不缩放", description: "无大图" }, { value: "智能缩放", label: "智能缩放", description: "有大图" }, @@ -55,12 +90,37 @@ const GPT_RESOLUTIONS = ["智能", "1K", "2K", "4K"]; const GPT_RATIOS = ["智能", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16"]; const GPT_QUALITIES = ["高", "中", "低", "自动"]; const GPT_25_QUALITIES = [...GPT_QUALITIES, "超高", "最高"]; + +const GPT_COMPLEXITY_OPTIONS = [ + { value: "高", label: "高", description: "充分规划,耗时更长" }, + { value: "中", label: "中", description: "平衡规划与速度" }, + { value: "低", label: "低", description: "较少规划,速度优先" }, +]; +const GPT_COMPLEXITY_TO_LABEL = Object.freeze({ + high: "高", + medium: "中", + low: "低", + 高: "高", + 中: "中", + 低: "低", +}); +function normalizeGptComplexityLabel(value) { + if (value == null || value === "") return "高"; + return GPT_COMPLEXITY_TO_LABEL[value] + ?? GPT_COMPLEXITY_TO_LABEL[String(value).toLowerCase()] + ?? "高"; +} + const GPT_IMAGE_COUNTS = Array.from({ length: 8 }, (_, index) => String(index + 1)); const GPT_OUTPUT_FORMATS = [ { value: "jpeg", label: "JPEG", description: "不支持透明背景" }, { value: "png", label: "PNG", description: "支持透明背景" }, { value: "webp", label: "WebP", description: "支持透明背景" }, ]; +const GPT_26_EXTRA_OUTPUT_FORMATS = [ + { value: "svg", label: "SVG", description: "矢量,仅纯文生图" }, + { value: "gif", label: "GIF", description: "动图,仅纯文生图" }, +]; const SEEDREAM_RESOLUTIONS = ["智能", "1K", "2K"]; const SEEDREAM_LAYER_RESOLUTIONS = ["智能", "1K", "1.5K", "2K"]; const SEEDREAM_RATIOS = ["智能", "1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "21:9"]; @@ -93,74 +153,117 @@ const GPT_BACKGROUNDS = [ { value: "opaque", label: "不透明", description: "生成实色背景" }, ]; const IMAGE_COUNTS = ["1", "2", "4", "9"]; -const BATCH_MODE_GROUP_TO_MODELS = "一组搭配+多模特"; -const BATCH_MODE_CARTESIAN = "全部搭配×全部模特"; -const BATCH_MODE_SINGLE_REFERENCES = "单图素材批量"; -const BATCH_MODE_OPTIONS = [ - { value: BATCH_MODE_GROUP_TO_MODELS, label: "整组素材 → 多个目标", description: "整组应用" }, - { value: BATCH_MODE_CARTESIAN, label: "全匹配(素材 × 目标)", description: "逐一组合" }, - { value: BATCH_MODE_SINGLE_REFERENCES, label: "单图批量(每张素材独立)", description: "无需目标图" }, +// Industry-neutral wording: 素材 = source assets, 目标 = targets to receive them. +const BATCH_MODE_GROUP_TO_TARGETS = "整组素材→多个目标"; +const BATCH_MODE_ALL_PAIRS = "每张素材×每张目标"; +const BATCH_MODE_SINGLE_REFERENCES = "每张素材单独出图"; +const BATCH_MODE_VALUES = [ + BATCH_MODE_GROUP_TO_TARGETS, + BATCH_MODE_ALL_PAIRS, + BATCH_MODE_SINGLE_REFERENCES, ]; +// Workflows saved before the rename keep working: old labels map to the new ones. +const BATCH_MODE_ALIASES = new Map([ + ["一组搭配+多模特", BATCH_MODE_GROUP_TO_TARGETS], + ["全部搭配×全部模特", BATCH_MODE_ALL_PAIRS], + ["单图素材批量", BATCH_MODE_SINGLE_REFERENCES], +]); +const BATCH_MODE_OPTIONS = [ + { value: BATCH_MODE_GROUP_TO_TARGETS, label: "整组素材→多个目标", description: "整组共用" }, + { value: BATCH_MODE_ALL_PAIRS, label: "每张素材×每张目标", description: "两两组合" }, + { value: BATCH_MODE_SINGLE_REFERENCES, label: "每张素材单独出图", description: "无需目标" }, +]; + +function normalizeBatchMode(value) { + const text = String(value ?? "").trim(); + if (!text) return BATCH_MODE_GROUP_TO_TARGETS; + if (BATCH_MODE_VALUES.includes(text)) return text; + return BATCH_MODE_ALIASES.get(text) || BATCH_MODE_GROUP_TO_TARGETS; +} + +function batchModeOf(node) { + return normalizeBatchMode(node?._o1igBatchMode?.value); +} const ALL_RATIOS = [ "智能", "1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9", ]; const NANO2_ONLY_RATIOS = new Set(["1:4", "1:8", "4:1", "8:1"]); const GPT_IMAGE_MODELS = new Set([ - "gpt-image-2", + "gpt-image-2.6-sunburst", + "gpt-image-2.6-flare", "gpt-image-2.5-sunburst", "gpt-image-2.5-flare", + "gpt-image-2", ]); const isGptImageModel = (model) => GPT_IMAGE_MODELS.has(model); const MODEL_CAPABILITIES = Object.freeze({ - "Nano Banana 2.1": Object.freeze({ thinking: true, search: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }), - "Nano Banana 2": Object.freeze({ thinking: true, search: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }), - "Nano Banana Pro": Object.freeze({ thinking: false, search: false, quality: false, output: false, mask: false, resize: true, saveFormat: true }), - "gpt-image-2": Object.freeze({ thinking: false, search: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), - "gpt-image-2.5-sunburst": Object.freeze({ thinking: false, search: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), - "gpt-image-2.5-flare": Object.freeze({ thinking: false, search: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), - "Seedream 5.0 Pro": Object.freeze({ thinking: false, search: false, quality: false, output: true, mask: false, resize: false, saveFormat: false, layers: true }), - "Nano Banana 2 Lite": Object.freeze({ thinking: false, search: false, quality: false, output: false, mask: false, resize: true, saveFormat: true }), - "Nano Banana": Object.freeze({ thinking: false, search: false, quality: false, output: false, mask: false, resize: true, saveFormat: true }), + "Nano Banana 2.1": Object.freeze({ thinking: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }), + "Nano Banana 2": Object.freeze({ thinking: true, quality: false, output: false, mask: false, resize: true, saveFormat: true }), + "Nano Banana Pro": Object.freeze({ thinking: false, quality: false, output: false, mask: false, resize: true, saveFormat: true }), + "gpt-image-2": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), + "gpt-image-2.5-sunburst": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), + "gpt-image-2.5-flare": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false }), + "gpt-image-2.6-sunburst": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false, complexity: true, frames: true }), + "gpt-image-2.6-flare": Object.freeze({ thinking: false, quality: true, output: true, mask: true, resize: true, saveFormat: false, complexity: true, frames: true }), + "Seedream 5.0 Pro": Object.freeze({ thinking: false, quality: false, output: true, mask: false, resize: false, saveFormat: false, layers: true }), }); -// The retired moderation name only hides a stale server widget until ComfyUI restarts. +// Retired names only hide a stale server widget until ComfyUI restarts; they are never +// serialized, so they must stay out of GENERATOR_SERIALIZED_WIDGETS. +const RETIRED_BACKEND_WIDGETS = new Set(["内容审查强度", "在线搜索"]); const BACKEND_WIDGETS = [ "prompt", "模型", "模型线路", "思考等级", "分辨率", "宽高比", "生图数量", "seed", "参考图清单", "质量", "输出格式", "蒙版清单", "缩放图片", "背景", "内容审查强度", - "批量出图", "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", + "批量出图", "批量模式", "模特图清单", "命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", "复杂度", "帧数", "帧时长ms", ]; const CSS = ` /* Keep the image-generation panel and its interactions; only layout and theme are shared. */ -.o1ig-panel,.o1ig-lightbox,.o1ig-canvas-picker{ +.o1ig-panel,.o1ig-actions,.o1ig-lightbox,.o1ig-canvas-picker{ --o1ig-text:var(--input-text); --o1ig-muted:var(--descrip-text); --o1ig-surface:var(--comfy-input-bg); --o1ig-border:var(--border-color); + --o1ig-invalid:var(--error-text); --o1ig-radius:var(--radius-lg,8px); color:var(--o1ig-text);font-family:var(--font-sans,Inter,system-ui,sans-serif); } -.lg-node-widget .o1ig-panel{ +.lg-node-widget:has(.o1ig-panel){ + height:100%;min-height:0;display:flex;flex-direction:column;align-self:stretch; +} +/* The slot between the widget and the panel must grow too, otherwise the slack the node body + carries is left as an empty strip instead of stretching the prompt area. */ +.lg-node-widget:has(.o1ig-panel)>div:has(.o1ig-panel){flex:1 1 auto;height:100%;} +.lg-node-widget .o1ig-panel,.lg-node-widget .o1ig-actions{ --o1ig-text:var(--component-node-foreground,var(--input-text)); --o1ig-muted:var(--component-node-foreground-secondary,var(--descrip-text)); --o1ig-surface:var(--component-node-widget-background,var(--comfy-input-bg)); --o1ig-border:var(--component-node-border,var(--border-color)); } +.lg-node-widget .o1ig-panel{flex:1 1 auto;min-height:0;} +/* The Vue body already pads the widget column, so the panel must not add a second inset on the + right: its content has to end where the native parameter rows end. */ +.lg-node-widget .o1ig-panel{padding-right:0;} +.lg-node-widget .o1ig-actions{padding-left:0;padding-right:0;} .o1ig-panel{ - width:100%;height:100%;min-height:292px;box-sizing:border-box;padding:10px 12px 12px; + width:100%;height:100%;min-height:0;box-sizing:border-box;padding:10px 12px 8px; font-size:12px;line-height:1.5;display:flex;flex-direction:column;gap:8px;overflow:visible;user-select:none; } -.o1ig-panel button,.o1ig-lightbox button,.o1ig-canvas-picker button{ +.o1ig-actions{ + width:100%;height:100%;box-sizing:border-box;padding:2px 12px 8px; + display:flex;flex-direction:column;gap:7px;justify-content:flex-end;user-select:none; +} +.o1ig-panel button,.o1ig-actions button,.o1ig-lightbox button,.o1ig-canvas-picker button{ border:1px solid var(--o1ig-border);background:var(--o1ig-surface);color:var(--o1ig-text); font:inherit;box-shadow:none; } -.o1ig-panel button:hover,.o1ig-lightbox button:hover,.o1ig-canvas-picker button:hover{ +.o1ig-panel button:hover,.o1ig-actions button:hover,.o1ig-lightbox button:hover,.o1ig-canvas-picker button:hover{ border-color:var(--o1ig-muted);background:var(--o1ig-surface);color:var(--o1ig-text); } -.o1ig-panel button:focus-visible,.o1ig-lightbox button:focus-visible,.o1ig-canvas-picker button:focus-visible{ +.o1ig-panel button:focus-visible,.o1ig-actions button:focus-visible,.o1ig-lightbox button:focus-visible,.o1ig-canvas-picker button:focus-visible{ outline:1px solid currentColor;outline-offset:2px; } -.o1ig-panel button:disabled{cursor:wait;opacity:.6;} +.o1ig-panel button:disabled,.o1ig-actions button:disabled{cursor:wait;opacity:.6;} .o1ig-refs{ display:flex;flex:0 0 109px;box-sizing:border-box;gap:7px;min-height:109px;overflow-x:auto;overflow-y:hidden; padding:1px 1px 4px;border-radius:var(--o1ig-radius);scrollbar-width:thin; @@ -181,9 +284,18 @@ const CSS = ` .o1ig-asset-meta{display:flex;min-width:0;align-items:baseline;gap:7px;} .o1ig-asset-actions{display:flex;flex:0 0 auto;align-items:center;gap:5px;margin-left:auto;} .o1ig-asset-hint{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} +.o1ig-asset-hint.hidden{display:none;} .o1ig-model-assets{display:none;}.o1ig-model-assets.visible{display:flex;} -.o1ig-batch-summary{display:none;min-height:18px;padding:4px 0;color:var(--o1ig-muted);font-size:11px;} -.o1ig-batch-summary.visible{display:block;} +/* Live preview of what the current batch settings will queue. */ +.o1ig-batch-summary{ + display:none;min-height:18px;padding:3px 2px 1px;color:var(--o1ig-muted);font-size:11px; + align-items:baseline;gap:0 8px;flex-wrap:wrap; +} +.o1ig-batch-summary.visible{display:flex;} +.o1ig-batch-summary-detail{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} +.o1ig-batch-summary-total{ + flex:0 0 auto;margin-left:auto;color:var(--o1ig-text);font-weight:600;font-variant-numeric:tabular-nums; +} .o1ig-thumb{ position:relative;flex:0 0 102px;height:102px;box-sizing:border-box;border-radius:var(--o1ig-radius); border:1px solid var(--o1ig-border);background:var(--o1ig-surface);overflow:hidden;transition:transform .12s ease,opacity .12s ease; @@ -228,9 +340,12 @@ const CSS = ` .o1ig-canvas-picker-card strong,.o1ig-canvas-picker-card span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0 8px;} .o1ig-canvas-picker-card strong{padding-top:7px;font-size:11px;font-weight:500;}.o1ig-canvas-picker-card span{padding-top:2px;padding-bottom:8px;color:var(--o1ig-muted);font-size:10px;} .o1ig-canvas-picker-empty{grid-column:1/-1;display:grid;place-items:center;min-height:150px;color:var(--o1ig-muted);text-align:center;font-size:12px;} -.o1ig-prompt-wrap{position:relative;width:100%;height:auto;min-height:142px;flex:1 1 142px;min-width:0;overflow:visible;} -.o1ig-prompt{width:100%;height:100%;min-height:142px;max-height:none;resize:none;box-sizing:border-box;padding:10px 12px 40px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);color:var(--o1ig-text);outline:none;font:inherit;font-size:12px;line-height:1.55;user-select:text;} +.o1ig-prompt-wrap{position:relative;width:100%;flex:1 1 auto;height:auto;min-height:${PROMPT_DEFAULT_HEIGHT}px;min-width:0;display:flex;flex-direction:column;overflow:hidden;} +.o1ig-prompt{width:100%;flex:1 1 auto;min-height:${PROMPT_DEFAULT_HEIGHT}px;height:100%;max-height:none;resize:none;box-sizing:border-box;padding:10px 12px 40px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);color:var(--o1ig-text);outline:none;font:inherit;font-size:12px;line-height:1.55;user-select:text;} .o1ig-prompt::placeholder{color:var(--o1ig-muted);}.o1ig-prompt:focus{border-color:var(--o1ig-muted);} +.o1ig-prompt-wrap.invalid .o1ig-prompt{border-color:var(--o1ig-invalid);} +.o1ig-prompt-wrap.invalid{animation:o1ig-prompt-shake .3s ease-in-out;} +@keyframes o1ig-prompt-shake{0%,100%{transform:translateX(0)}25%{transform:translateX(-3px)}75%{transform:translateX(3px)}} .o1ig-prompt-optimize{position:absolute;right:8px;bottom:8px;min-width:96px;height:28px;padding:0 9px;display:flex;align-items:center;justify-content:center;gap:5px;border-radius:7px;cursor:pointer;font-size:11px!important;line-height:1;white-space:nowrap;} .o1ig-prompt-optimize-icon{display:block;font-size:15px;line-height:1;transform-origin:center;} .o1ig-prompt-optimize.busy .o1ig-prompt-optimize-icon{animation:o1ig-magic-pulse .9s ease-in-out infinite alternate;} @@ -240,16 +355,12 @@ const CSS = ` .o1ig-prompt-optimize-status.busy::before{content:"";flex:0 0 auto;width:6px;height:6px;border-radius:50%;background:currentColor;animation:o1ig-prompt-status-pulse .8s ease-in-out infinite alternate;} @keyframes o1ig-prompt-status-pulse{from{opacity:.35;transform:scale(.8)}to{opacity:1;transform:scale(1.12)}} .o1ig-toolbar{width:100%;min-width:0;display:grid;flex:0 0 auto;grid-template-columns:minmax(0,1fr);gap:6px;position:relative;overflow:visible;} -.o1ig-section-title{grid-column:1/-1;display:flex;align-items:center;gap:9px;min-height:18px;margin-top:2px;color:var(--o1ig-muted);font-size:11px;font-weight:500;} -.o1ig-section-title::after{content:"";height:1px;flex:1;background:var(--o1ig-border);} .o1ig-field-wide{grid-column:1/-1;} .o1ig-control{width:100%;height:28px;min-width:0;box-sizing:border-box;padding:0 9px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);color:var(--o1ig-text);outline:none;font:inherit;font-size:12px;line-height:1.4;font-variant-numeric:tabular-nums;} .o1ig-control:hover,.o1ig-control:focus{border-color:var(--o1ig-muted);} .o1ig-select{position:relative;min-width:0;height:28px;z-index:1;}.o1ig-select.open{z-index:50;} .o1ig-select-trigger{width:100%;height:28px;min-width:0;display:flex;align-items:center;gap:6px;box-sizing:border-box;padding:0 7px 0 9px;border-radius:var(--o1ig-radius);cursor:pointer;text-align:left;font-size:12px!important;line-height:1.4;font-variant-numeric:tabular-nums;} .o1ig-select-value{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.4;} -.o1ig-select-selected-description{flex:0 0 auto;max-width:42%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--o1ig-muted);font-size:10px;line-height:1.35;} -.o1ig-select-selected-description:empty{display:none;} .o1ig-select-caret{width:14px;height:14px;flex:0 0 14px;display:flex;align-items:center;justify-content:center;align-self:center;line-height:0;transform-origin:50% 50%;transition:transform .14s ease;} .o1ig-select-caret svg{display:block;width:12px;height:12px;overflow:visible;}.o1ig-select.open .o1ig-select-caret{transform:rotate(180deg);} .o1ig-select-menu{position:absolute;top:32px;left:0;min-width:100%;width:100%;display:none;box-sizing:border-box;padding:5px;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--comfy-menu-bg);} @@ -259,13 +370,17 @@ const CSS = ` .o1ig-select-option-label{min-width:0;overflow:hidden;text-overflow:ellipsis;} .o1ig-select-option-description{flex:0 0 auto;color:var(--o1ig-muted);font-size:10px;line-height:1.35;} .o1ig-panel .o1ig-select-option.selected{outline:1px solid var(--o1ig-muted);outline-offset:-1px;font-weight:600;} -.o1ig-field{display:grid;grid-template-columns:104px minmax(0,1fr);align-items:center;gap:4px 8px;min-width:0;} -.o1ig-field label{min-width:0;font-size:11px;font-weight:400;line-height:1.4;color:var(--o1ig-muted);text-align:left;white-space:nowrap;} +.o1ig-field-inline-label{display:grid;grid-template-columns:104px minmax(0,1fr);align-items:center;gap:0;min-width:0;min-height:28px;height:28px;overflow:visible;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);} +.o1ig-field-inline-label > .o1ig-inline-label{padding-left:9px;color:var(--o1ig-muted);font-size:11px;line-height:1.4;white-space:nowrap;pointer-events:none;} +.o1ig-field-inline-label > .o1ig-control{height:26px;padding:0 7px;border:0;border-radius:0;background:transparent;} +.o1ig-field-inline-label > .o1ig-control:hover,.o1ig-field-inline-label > .o1ig-control:focus{border-color:transparent;background:transparent;} +.o1ig-field-inline-label > .o1ig-select{height:26px;} +.o1ig-field-inline-label .o1ig-select-trigger{height:26px;padding-left:4px;border:0;border-radius:0;background:transparent;} +.o1ig-field-inline-label .o1ig-select-value{text-align:right;} +.o1ig-field-inline-label > .o1ig-mask-wrap{height:26px;align-items:center;} +.o1ig-field-inline-label > .o1ig-mask-wrap .o1ig-control{height:26px;border:0;border-radius:0;background:transparent;} +.o1ig-field-inline-label:focus-within,.o1ig-field-inline-label:hover{border-color:var(--o1ig-muted);} .o1ig-resize-warning{display:none;grid-column:2;color:var(--o1ig-muted);font-size:10px;line-height:1.4;}.o1ig-resize-warning.visible{display:block;} -.o1ig-seed{width:100%;height:28px;min-width:0;display:grid;grid-template-columns:minmax(0,1fr) 28px;gap:0;box-sizing:border-box;overflow:hidden;border:1px solid var(--o1ig-border);border-radius:var(--o1ig-radius);background:var(--o1ig-surface);} -.o1ig-seed:hover,.o1ig-seed:focus-within{border-color:var(--o1ig-muted);} -.o1ig-seed .o1ig-control{height:26px;border:0;border-radius:0;background:transparent;} -.o1ig-seed button{height:26px;padding:0;border:0;border-left:1px solid var(--o1ig-border);border-radius:0;font-size:14px;cursor:pointer;} .o1ig-mask-wrap{display:grid;grid-template-columns:minmax(0,1fr) 28px;gap:5px;} .o1ig-mask-button{padding:0 9px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left;cursor:pointer;}.o1ig-mask-clear{padding:0;font-size:15px;cursor:pointer;} .o1ig-generate{width:100%;height:32px;flex:0 0 32px;border-radius:var(--o1ig-radius);font-size:12px;cursor:pointer;} @@ -324,26 +439,177 @@ function isGeneratedSeedControl(widget) { return name === "control_after_generate" || name.endsWith(" control_after_generate"); } +function generatorSeed(node) { + // The seed row is the native widget, so it is the single source of truth. + const value = Math.floor(Number(findWidget(node, "seed")?.value)); + return Number.isFinite(value) ? Math.max(0, value) : 0; +} + function hideBackendWidget(widget) { if (!widget) return; - if (!widget.__o1igHidden) widget.computeSize = () => [0, -4]; + if (!widget.__o1igOriginalComputeSizeCaptured) { + widget.__o1igOriginalComputeSizeCaptured = true; + widget.__o1igHadComputeSize = "computeSize" in widget; + widget.__o1igOriginalComputeSize = widget.computeSize; + widget.computeSize = () => [0, -4]; + } widget.__o1igHidden = true; widget.hidden = true; widget.options ??= {}; widget.options.hidden = true; } +function showBackendWidget(widget) { + if (!widget) return; + if (widget.__o1igHidden && widget.__o1igOriginalComputeSizeCaptured) { + if (widget.__o1igHadComputeSize) widget.computeSize = widget.__o1igOriginalComputeSize; + else delete widget.computeSize; + } + widget.__o1igHidden = false; + widget.hidden = false; + widget.options ??= {}; + widget.options.hidden = false; +} + +function setNativeWidgetVisible(node, name, visible) { + if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return; + const widget = findWidget(node, name); + if (visible) showBackendWidget(widget); + else hideBackendWidget(widget); +} + function hideBackendWidgets(node) { for (const name of BACKEND_WIDGETS) { - hideBackendWidget(findWidget(node, name)); - } - for (const widget of node?.widgets || []) { - if (isGeneratedSeedControl(widget)) { + const widget = findWidget(node, name); + if (USE_NATIVE_LITEGRAPH_PARAMETERS && NATIVE_PARAMETER_WIDGETS.has(name)) { + showBackendWidget(widget); + } else { hideBackendWidget(widget); - // LiteGraph restores by widget.serialize; options.serialize only excludes API prompts. - widget.serialize = false; } } + for (const widget of node?.widgets || []) { + if (!isGeneratedSeedControl(widget)) continue; + // The seed row is native, so its 生成后控制 companion stays visible too. + showBackendWidget(widget); + // LiteGraph restores by widget.serialize; options.serialize only excludes API prompts. + // Keep it out of widgets_values so the schema order stays aligned. + widget.serialize = false; + } +} + +const NATIVE_PARAMETER_PANEL_FIELDS = Object.freeze({ + "模型": "_o1igModel", + "模型线路": "_o1igRoute", + "思考等级": "_o1igThinking", + "分辨率": "_o1igResolution", + "宽高比": "_o1igRatio", + "生图数量": "_o1igCount", + "质量": "_o1igQuality", + "输出格式": "_o1igOutputFormat", + "缩放图片": "_o1igResize", + "背景": "_o1igBackground", + "批量模式": "_o1igBatchMode", + "图层拆分": "_o1igLayerDecomposition", + "命名规则": "_o1igNamingRule", + "filename_prefix": "_o1igFilenamePrefix", + "格式": "_o1igSaveFormat", + "保存位置": "_o1igSaveLocation", + "帧数": "_o1igFrameCount", + "帧时长ms": "_o1igFrameDuration", +}); + +function syncNativeParameterToPanel(node, name, value) { + if (!USE_NATIVE_LITEGRAPH_PARAMETERS || node._o1igNativeParameterSyncing) return; + node._o1igNativeParameterSyncing = true; + try { + const controlName = NATIVE_PARAMETER_PANEL_FIELDS[name]; + if (controlName && node[controlName]) { + node[controlName].value = name === "模型" + ? normalizeUnifiedModel(value) + : name === "图层拆分" + ? (value === true || String(value || "").toLowerCase() === "true" || value === "开启" ? "开启" : "关闭") + : value; + } + if (name === "批量出图") { + node._o1igBatchEnabled = value === true + || String(value || "").toLowerCase() === "true" + || value === "开启"; + syncBatchLayout(node); + syncModelOptions(node); + } else if (name === "批量模式") { + syncBatchLayout(node); + } else if (name === "模型" || name === "图层拆分") { + syncModelOptions(node); + } else if (name === "输出格式" || name === "背景" || name === "帧数" || name === "帧时长ms") { + syncGptOutputOptions(node); + if (name === "输出格式" || name === "背景") syncModelOptions(node); + } else if (name === "命名规则" || name === "格式" || name === "保存位置" || name === "filename_prefix") { + syncGeneratorSaveControls(node); + } else if (name === "缩放图片") { + syncResizeWarning(node); + } + syncNativeWidgetOptions(node); + } finally { + node._o1igNativeParameterSyncing = false; + } +} + +const NATIVE_COMBO_PANEL_FIELDS = Object.freeze({ + "模型线路": "_o1igRoute", + "思考等级": "_o1igThinking", + "分辨率": "_o1igResolution", + "宽高比": "_o1igRatio", + "生图数量": "_o1igCount", + "质量": "_o1igQuality", + "输出格式": "_o1igOutputFormat", + "缩放图片": "_o1igResize", + "背景": "_o1igBackground", + "批量模式": "_o1igBatchMode", + "命名规则": "_o1igNamingRule", + "格式": "_o1igSaveFormat", +}); + +function syncNativeWidgetOptions(node) { + if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return; + for (const [name, controlName] of Object.entries(NATIVE_COMBO_PANEL_FIELDS)) { + const widget = findWidget(node, name); + const control = node[controlName]; + if (!widget || !control?._o1igOptions) continue; + widget.options ??= {}; + widget.options.values = control._o1igOptions.map((option) => option.value); + widget.value = control.value; + } +} + +function installNativeParameterBridge(node) { + if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return; + for (const name of NATIVE_PARAMETER_WIDGETS) { + const widget = findWidget(node, name); + if (!widget || widget.__o1igNativeParameterBridge) continue; + const originalCallback = widget.callback; + widget.__o1igNativeParameterBridge = true; + widget.callback = function () { + const result = originalCallback?.apply(this, arguments); + syncNativeParameterToPanel(node, name, this.value); + return result; + }; + } +} + +function movePanelWidgetToFront(node, panelWidget) { + if (!USE_NATIVE_LITEGRAPH_PARAMETERS || !Array.isArray(node.widgets)) return; + const index = node.widgets.indexOf(panelWidget); + if (index < 0) return; + node.widgets.splice(index, 1); + node.widgets.unshift(panelWidget); +} + +function moveWidgetToEnd(node, widget) { + if (!Array.isArray(node?.widgets) || !widget) return; + const index = node.widgets.indexOf(widget); + if (index < 0) return; + node.widgets.splice(index, 1); + node.widgets.push(widget); } function parseReferences(value) { @@ -379,6 +645,8 @@ function syncMaskControl(node) { node._o1igMaskButton.textContent = node._o1igMask?.name || "添加蒙版"; node._o1igMaskButton.title = node._o1igMask?.name || "上传 GPT Image 编辑蒙版"; node._o1igMaskClear.disabled = !node._o1igMask; + + syncGptOutputOptions(node); } function viewPath(item) { @@ -574,7 +842,7 @@ function referenceLightboxEntries(node) { })); if ( node?._o1igBatchEnabled - && node?._o1igBatchMode?.value !== BATCH_MODE_SINGLE_REFERENCES + && batchModeOf(node) !== BATCH_MODE_SINGLE_REFERENCES ) { entries.push(...(node._o1igModelReferences || []).map((item, index) => ({ item, role: "models", index, @@ -899,12 +1167,14 @@ function updateNativeQueueJob(detail, { forceState = "", images = null, error = job.images = savedImages; job.outputs_count = savedImages.length; const preview = savedImages[0]; + const animated = animatedFlagsForSaveResults(savedImages); job.preview_output = { ...preview, nodeId: String(job.save_node_id), - mediaType: "images", + mediaType: animated ? "images" : "images", display_name: preview.filename, }; + if (animated) job.animated = animated; } if (!job.o1key_total_count && savedImages.length) { job.o1key_total_count = savedImages.length; @@ -1020,7 +1290,12 @@ function installNativeTaskQueueBridge() { if (!job) return originals.getJobDetail(jobId); return { ...job, - outputs: job.images?.length ? { [String(job.save_node_id)]: { images: job.images } } : {}, + outputs: job.images?.length ? (() => { + const output = { images: job.images }; + const animated = animatedFlagsForSaveResults(job.images); + if (animated) output.animated = animated; + return { [String(job.save_node_id)]: output }; + })() : {}, update_time: job.execution_end_time || Date.now(), }; }; @@ -1101,7 +1376,6 @@ function setDropdownValue(dropdown, value) { dropdown._o1igValue = nextValue; const selectedOption = selected || dropdown._o1igOptions[0]; dropdown._o1igValueLabel.textContent = selectedOption?.label || ""; - dropdown._o1igValueDescription.textContent = selectedOption?.description || ""; dropdown._o1igTrigger.title = selectedOption?.description ? `${selectedOption.label} · ${selectedOption.description}` : selectedOption?.label || ""; @@ -1159,8 +1433,6 @@ function makeDropdown(options, current, title = "") { trigger.setAttribute("aria-expanded", "false"); const valueLabel = document.createElement("span"); valueLabel.className = "o1ig-select-value"; - const valueDescription = document.createElement("span"); - valueDescription.className = "o1ig-select-selected-description"; const caret = document.createElement("span"); caret.className = "o1ig-select-caret"; caret.setAttribute("aria-hidden", "true"); @@ -1176,7 +1448,7 @@ function makeDropdown(options, current, title = "") { caretPath.setAttribute("stroke-linejoin", "round"); caretIcon.append(caretPath); caret.append(caretIcon); - trigger.append(valueLabel, valueDescription, caret); + trigger.append(valueLabel, caret); const menu = document.createElement("div"); menu.className = "o1ig-select-menu"; @@ -1186,7 +1458,6 @@ function makeDropdown(options, current, title = "") { _o1igMenu: menu, _o1igTrigger: trigger, _o1igValueLabel: valueLabel, - _o1igValueDescription: valueDescription, }); Object.defineProperty(dropdown, "value", { get: () => dropdown._o1igValue, @@ -1239,18 +1510,16 @@ function replaceOptions(select, values, preferred) { function makeAdvancedField(labelText, control) { const field = document.createElement("div"); - field.className = "o1ig-field"; - const label = document.createElement("label"); + field.className = "o1ig-field-inline-label"; + const label = document.createElement("span"); + label.className = "o1ig-inline-label"; label.textContent = labelText; field.append(label, control); return field; } -function makePanelSectionTitle(text) { - const heading = document.createElement("div"); - heading.className = "o1ig-section-title"; - heading.textContent = text; - return heading; +function makeInlineLabelField(labelText, control) { + return makeAdvancedField(labelText, control); } function setFieldVisible(field, visible) { @@ -1259,14 +1528,30 @@ function setFieldVisible(field, visible) { function syncGptOutputOptions(node) { if (!node._o1igOutputFormat || !node._o1igBackground) return; - const formats = node._o1igModel?.value === "Seedream 5.0 Pro" - ? SEEDREAM_OUTPUT_FORMATS - : node._o1igBackground.value === "transparent" - ? GPT_OUTPUT_FORMATS.filter((option) => option.value !== "jpeg") - : GPT_OUTPUT_FORMATS; + const model = node._o1igModel?.value; + let formats; + if (model === "Seedream 5.0 Pro") { + formats = SEEDREAM_OUTPUT_FORMATS; + } else { + const is26 = /^gpt-image-2\.6-/.test(String(model || "")); + const hasRefs = (node._o1igReferences || []).length > 0 + || (node._o1igModelReferences || []).length > 0 + || Boolean(node._o1igMask); + formats = [...GPT_OUTPUT_FORMATS]; + if (is26 && !hasRefs) formats = [...formats, ...GPT_26_EXTRA_OUTPUT_FORMATS]; + if (node._o1igBackground.value === "transparent") { + formats = formats.filter((option) => option.value !== "jpeg" && option.value !== "svg" && option.value !== "gif"); + } + } replaceOptions(node._o1igOutputFormat, formats, node._o1igOutputFormat.value); setWidgetValue(node, "输出格式", node._o1igOutputFormat.value); setWidgetValue(node, "背景", node._o1igBackground.value); + const showFrames = /^gpt-image-2\.6-/.test(String(model || "")) + && node._o1igOutputFormat.value === "gif"; + setFieldVisible(node._o1igFrameCountField, showFrames); + setFieldVisible(node._o1igFrameDurationField, showFrames); + if (node._o1igFrameCount) setWidgetValue(node, "帧数", Number(node._o1igFrameCount.value) || 9); + if (node._o1igFrameDuration) setWidgetValue(node, "帧时长ms", Number(node._o1igFrameDuration.value) || 200); } function generatorSaveSettings(node) { @@ -1298,6 +1583,10 @@ function syncGeneratorSaveControls(node) { || MODEL_CAPABILITIES["Nano Banana 2"]; setFieldVisible(node._o1igFilenamePrefixField, node._o1igNamingRule.value === "自定义前缀"); setFieldVisible(node._o1igSaveFormatField, capabilities.saveFormat); + if (USE_NATIVE_LITEGRAPH_PARAMETERS) { + setNativeWidgetVisible(node, "filename_prefix", node._o1igNamingRule.value === "自定义前缀"); + setNativeWidgetVisible(node, "格式", capabilities.saveFormat); + } const settings = generatorSaveSettings(node); setWidgetValue(node, "命名规则", settings.naming_rule); setWidgetValue(node, "filename_prefix", settings.filename_prefix); @@ -1314,6 +1603,19 @@ function syncResizeWarning(node) { ); } +function statusLineVisible(node) { + return String(node?._o1igStatus?.className || "").includes("visible"); +} + +function syncActionsHeight(node) { + const visible = statusLineVisible(node); + if (visible === node._o1igStatusVisible) return; + node._o1igStatusVisible = visible; + if (!node._o1igActionsWidget) return; + // The panel is flexible, so the status row is taken from / returned to the prompt area. + node.setDirtyCanvas?.(true, true); +} + function setStatus(node, text = "", kind = "") { if (!node._o1igGenerate || !node._o1igStatus) return; clearTimeout(node._o1igStatusTimer); @@ -1323,6 +1625,7 @@ function setStatus(node, text = "", kind = "") { node._o1igGenerate.textContent = "开始生成"; node._o1igGenerate.classList?.remove?.("cancel"); node._o1igPanel?.classList.toggle("busy", kind === "busy"); + syncActionsHeight(node); if (kind === "ok" && text) { node._o1igStatusTimer = setTimeout(() => { if (!node._o1igRunning) setStatus(node, "", ""); @@ -1344,26 +1647,226 @@ function setPromptOptimizeStatus(node, text = "", kind = "") { } } +function flagEmptyPrompt(node) { + // No wording on purpose: pointing at the field is enough, a status line under the button + // just pushed the layout around and read as noise. + const wrap = node?._o1igPrompt?.parentElement; + node?._o1igPrompt?.focus?.(); + if (!wrap?.classList) return; + wrap.classList.remove("invalid"); + void wrap.offsetWidth; // Restart the shake on every click. + wrap.classList.add("invalid"); + clearTimeout(node._o1igPromptInvalidTimer); + node._o1igPromptInvalidTimer = setTimeout(() => { + wrap.classList?.remove("invalid"); + }, 600); +} + +function applyGeneratorSize(node, width, height) { + if (!(height > 0)) return; + const currentWidth = Number(node.size?.[0]) || 0; + const currentHeight = Number(node.size?.[1]) || 0; + if (Math.abs(currentWidth - width) < 0.5 && Math.abs(currentHeight - height) < 0.5) return; + node._o1igAutoSizing = true; + try { + node.setSize?.([width, height]); + // Remember the last programmatic height: it is the baseline of the next user drag. + node._o1igSizedHeight = height; + } finally { + node._o1igAutoSizing = false; + } +} + +// A setSize() fired while the pointer is up comes from the engine (node creation, workflow +// restore, or the Vue layout re-measuring when rows are added/removed). Only a resize with a +// pressed pointer is a real drag by the user. +let canvasPointerDown = false; +let canvasPointerY = 0; +let canvasPointerStartY = 0; +let canvasPointerStartX = 0; +function trackCanvasPointer(event) { + canvasPointerDown = event.type !== "pointerup" && event.type !== "pointercancel"; + const x = Number(event.clientX); + const y = Number(event.clientY); + if (Number.isFinite(y)) canvasPointerY = y; + if (event.type === "pointerdown") { + canvasPointerStartX = Number.isFinite(x) ? x : 0; + canvasPointerStartY = Number.isFinite(y) ? y : 0; + } +} +for (const type of ["pointerdown", "pointerup", "pointercancel", "pointermove"]) { + document?.addEventListener?.(type, trackCanvasPointer, { capture: true, passive: true }); +} +window?.addEventListener?.("blur", () => { + canvasPointerDown = false; +}); + +function resetCanvasPointerGesture() { + // Any graph (re)load voids a gesture that never got its pointerup, which otherwise let a + // stale press turn later re-layouts into "drags" and made the node grow on its own. + canvasPointerDown = false; + canvasPointerStartX = 0; + canvasPointerStartY = 0; +} + +function generatorNodeRoot(node) { + // Vue nodes are real DOM boxes, so the browser itself can say whether a press landed on the + // node. The canvas transform is not usable there: the DOM box and ds.offset disagree, which + // made the geometry test reject perfectly good drags. Classic canvas nodes have no such root. + const panel = node?._o1igPanel; + const root = panel?.closest?.("[data-node-id]"); + return root && root.contains?.(panel) ? root : null; +} + +function pointerStartsInsideNode(node, clientX, clientY) { + // Menus and dialogs live outside the node box, so a press there can never resize it. + const x = Number(clientX); + const y = Number(clientY); + if (!Number.isFinite(x) || !Number.isFinite(y)) return false; + if (!(x > 0) || !(y > 0)) return false; + const root = generatorNodeRoot(node); + const hit = root ? document?.elementFromPoint?.(x, y) : null; + if (root && hit) return root === hit || root.contains(hit); + const ds = node?.graph?.canvas?.ds; + if (!ds) return false; + const scale = Number(ds.scale) || 1; + const localX = (x - (Number(ds.offset?.[0]) || 0)) / scale; + const localY = (y - (Number(ds.offset?.[1]) || 0)) / scale; + const width = Number(node?.size?.[0]) || 0; + const height = Number(node?.size?.[1]) || 0; + return localX >= node.pos[0] - GENERATOR_DRAG_MARGIN + && localX <= node.pos[0] + width + GENERATOR_DRAG_MARGIN + && localY >= node.pos[1] - GENERATOR_DRAG_MARGIN + && localY <= node.pos[1] + height + GENERATOR_DRAG_MARGIN; +} + +function generatorExtraHeight(node) { + // Height the user dragged beyond the content. Keeping it as a delta (instead of a + // "manual resize" flag) means the node still shrinks back when rows disappear. + const raw = Number(node?.properties?.o1keyPanelExtraHeight); + return Number.isFinite(raw) ? Math.max(0, Math.round(raw)) : 0; +} + +function setGeneratorExtraHeight(node, extra) { + if (!node) return; + node.properties ??= {}; + const value = Math.max(0, Math.round(Number(extra) || 0)); + if (generatorExtraHeight(node) === value) return; + node.properties.o1keyPanelExtraHeight = value; +} + +function nextGeneratorExtra(anchor, pointerY, heightDelta, scale) { + // Decides whether a resize event may move the dragged-out height. Returns null when it must + // be left alone. + // A width drag (or any engine re-layout) changes the node height while the pointer keeps + // still: the Vue body resizes itself whenever the panel grows, so folding that height into + // the extra height fed the node straight back into a runaway loop. + if (!(anchor?.pointerY > 0)) return anchor.extra + heightDelta; + const pointerDelta = (Number(pointerY) - anchor.pointerY) / (Number(scale) || 1); + if (Math.abs(pointerDelta) <= 1) return null; + // A stale gesture (press swallowed by a menu, then the pointer moved far away) would + // otherwise fold the whole mouse travel into the extra height and inflate the node. + if (Math.abs(pointerDelta) > GENERATOR_DRAG_OVERSHOOT) return null; + return anchor.extra + pointerDelta; +} + +function nodeDomScale(node) { + // CSS pixels inside a node are canvas pixels times the canvas zoom. Read the zoom from the + // canvas: deriving it from the panel box mixes in DOM rounding and drifts while dragging. + const scale = Number(node?.graph?.canvas?.ds?.scale); + if (Number.isFinite(scale) && scale > 0) return scale; + const panel = node?._o1igPanel; + const layout = Number(panel?.offsetHeight); + const painted = Number(panel?.getBoundingClientRect?.().height); + if (!(layout > 0) || !(painted > 0)) return 1; + const ratio = painted / layout; + return Number.isFinite(ratio) && ratio > 0 ? ratio : 1; +} + +function generatorPanelDomHeight(node) { + // Height the panel element itself has to cover: its content plus the dragged-out height. + // The DOM widget chrome (LiteGraph's margin around every DOM widget) lives outside the + // element, so it is not part of this number. + const content = measurePanelContentHeight(node); + if (content > 0) return content + generatorExtraHeight(node); + return Math.max( + GENERATOR_COMPACT_MIN_HEIGHT, + generatorPanelMinHeight(node) - domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel), + ); +} + +function syncPanelExtraDomHeight(node) { + const panel = node?._o1igPanel; + if (!panel?.style) return; + const extra = generatorExtraHeight(node); + // Only the Vue node body needs this: its grid rows follow min-content, so whatever the node + // has beyond the other rows must land on the panel or the grid splits it between its two + // auto rows (empty strips above the first parameter row and above the button). + if (!(extra > 0) || !isVueNodesEnabled()) { + if (panel.style.minHeight) panel.style.minHeight = ""; + return; + } + // Never read this back from the laid-out row: the row is scaled by the canvas zoom and + // re-derived from this very value, which made the target drift while dragging. + const target = Math.ceil(generatorPanelDomHeight(node)); + if (!(target > 0)) return; + const current = Number.parseFloat(panel.style.minHeight) || 0; + if (Math.abs(current - target) <= 1) return; + panel.style.minHeight = `${target}px`; +} + function fitNode(node) { - if (!node._o1igPanelWidget) return; + if (!node?._o1igPanelWidget) return; + // A fresh fit re-bases the drag anchor used by onResize. + node._o1igDragAnchor = null; + // Workflows saved before the delta bookkeeping carry this flag; it no longer means anything. + if (node.properties?.o1keyPanelAutoHeight !== undefined) delete node.properties.o1keyPanelAutoHeight; + // Any setSize() during creation / workflow restore is engine driven, not a user resize. + node._o1igSettled = false; const enforce = () => { const width = Math.max(Number(node.size?.[0]) || 0, GENERATOR_MIN_SIZE[0]); - const denseLayout = isGptImageModel(node._o1igModel?.value); - const minimumHeight = node._o1igBatchEnabled - ? denseLayout ? GENERATOR_DENSE_BATCH_MIN_HEIGHT : GENERATOR_BATCH_MIN_HEIGHT - : denseLayout ? GENERATOR_DENSE_MIN_HEIGHT : GENERATOR_MIN_SIZE[1]; - const height = Math.max(Number(node.size?.[1]) || 0, minimumHeight); - node.setSize?.([width, height]); + // Keep classic computeLayoutSize (getMinHeight) and Vue layout in sync. + node._o1igPanelWidget.options ??= {}; + node._o1igPanelWidget.options.getMinHeight = () => generatorPanelMinHeight(node); + // The panel must stay flexible (no computeSize) so it absorbs the node's free space + // instead of leaving an empty strip under the last parameter row. + if (node._o1igPanelWidget.computeSize) delete node._o1igPanelWidget.computeSize; + if (node._o1igActionsWidget) { + node._o1igActionsWidget.options ??= {}; + node._o1igActionsWidget.options.getMinHeight = () => actionsWidgetHeight(node); + node._o1igActionsWidget.options.getMaxHeight = () => actionsWidgetHeight(node); + } + syncPanelExtraDomHeight(node); + const contentHeight = generatorContentHeight(node, width); + // generatorPanelMinHeight() already carries the dragged-out height, so computeSize is + // the whole story: no leftover slack can appear above the action bar. + // Keep the engine's height when it already matches within the measurement noise, + // otherwise the node oscillates by that noise on every fit. + const currentHeight = Number(node.size?.[1]) || 0; + const height = Math.abs(currentHeight - contentHeight) <= GENERATOR_FIT_TOLERANCE + ? currentHeight + : contentHeight; + applyGeneratorSize(node, width, height); node.setDirtyCanvas?.(true, true); }; enforce(); + // DOM widgets are measured once they are attached to the canvas, so re-fit a few times. requestAnimationFrame(enforce); + for (const delay of SETTLE_FIT_DELAYS) { + setTimeout(() => { + if (node._o1igPanel) enforce(); + }, delay); + } + setTimeout(() => { + node._o1igSettled = true; + }, SETTLE_FIT_DELAYS[SETTLE_FIT_DELAYS.length - 1] + 120); } function applyGeneratorDefaultSize(node) { if (node._o1igDefaultSizeApplied) return; node._o1igDefaultSizeApplied = true; - node.setSize?.([...GENERATOR_DEFAULT_SIZE]); + // Width only: fitNode() then folds the height down to the stacked content. + applyGeneratorSize(node, GENERATOR_DEFAULT_SIZE[0], GENERATOR_DEFAULT_SIZE[1]); node.setDirtyCanvas?.(true, true); } @@ -1406,7 +1909,7 @@ function referenceRole(node, role = "references") { items: node._o1igModelReferences || [], pending: node._o1igModelPending || [], container: node._o1igModelRefs, - add: node._o1igModelAdd, + input: node._o1igModelInput, canvasPicker: node._o1igModelCanvasPick, widget: "模特图清单", label: "目标图", @@ -1417,7 +1920,7 @@ function referenceRole(node, role = "references") { items: node._o1igReferences || [], pending: node._o1igPending || [], container: node._o1igRefs, - add: node._o1igAdd, + input: node._o1igReferenceInput, canvasPicker: node._o1igCanvasPick, widget: "参考图清单", label: node._o1igBatchEnabled ? "素材图" : "参考图", @@ -1425,6 +1928,27 @@ function referenceRole(node, role = "references") { }; } +const IMAGE_FILE_ACCEPT = "image/png,image/jpeg,image/webp,image/gif,image/bmp"; + +function createReferenceFileInput(node, role = "references") { + const input = document.createElement("input"); + input.type = "file"; + input.accept = IMAGE_FILE_ACCEPT; + input.multiple = true; + input.hidden = true; + input.addEventListener("change", async () => { + await acceptFiles(node, input.files, role); + input.value = ""; + }); + return input; +} + +function requestReferenceUpload(node, role = "references") { + const state = referenceRole(node, role); + if (!state.input || hasPendingReferenceUploads(node)) return; + state.input.click(); +} + function hasPendingReferenceUploads(node) { return Boolean( node?._o1igPending?.length @@ -1438,7 +1962,7 @@ function referenceLimit(node, role = "references") { if (node?._o1igLayerDecomposition?.value === "开启") return role === "references" ? 1 : 0; if (!node?._o1igBatchEnabled) return MAX_REQUEST_REFERENCES; if (role === "models") return MAX_REFERENCES; - return node._o1igBatchMode?.value === BATCH_MODE_GROUP_TO_MODELS + return batchModeOf(node) === BATCH_MODE_GROUP_TO_TARGETS ? MAX_REQUEST_REFERENCES - 1 : MAX_REFERENCES; } @@ -1452,13 +1976,13 @@ function referenceBadgeDetails(node, role, listIndex) { title: `图${ordinal}${primary}(按当前顺序)`, }; } - if (node._o1igBatchMode?.value === BATCH_MODE_SINGLE_REFERENCES) { + if (batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES) { return { label: "图1", title: `素材图${ordinal} · 作为单张参考图独立生成`, }; } - const cartesian = node._o1igBatchMode?.value === BATCH_MODE_CARTESIAN; + const cartesian = batchModeOf(node) === BATCH_MODE_ALL_PAIRS; if (role === "models") { const referenceCount = node._o1igReferences?.length || 0; const requestIndex = referenceCount ? (cartesian ? 2 : referenceCount + 1) : 1; @@ -1643,7 +2167,7 @@ async function replaceReference(node, role, original, file) { function renderReferenceRole(node, role = "references") { const state = referenceRole(node, role); - if (!state.container || !state.add) return; + if (!state.container) return; node._o1igReferenceHandles ??= {}; node._o1igReferenceHandles[role] = []; state.container.replaceChildren(); @@ -1758,7 +2282,7 @@ function renderReferenceRole(node, role = "references") { const label = document.createElement("span"); label.textContent = `添加${state.label}`; upload.append(icon, label); - upload.addEventListener("click", () => state.add.click?.()); + upload.addEventListener("click", () => requestReferenceUpload(node, role)); bindImageFileDropTarget(node, upload, role); state.container.append(upload); } @@ -1768,6 +2292,7 @@ function renderReferences(node) { renderReferenceRole(node, "references"); renderReferenceRole(node, "models"); updateBatchSummary(node); + syncGptOutputOptions(node); } async function acceptFiles(node, files, role = "references") { @@ -1845,7 +2370,6 @@ function clearImageFileDropHighlight(node, target, role = "references") { target?.classList?.remove("drag"); const state = referenceRole(node, role); state.container?.classList?.remove("drag"); - state.add?.classList?.remove("drag"); } function bindImageFileDropTarget(node, target, role = "references") { @@ -2122,7 +2646,7 @@ function ensureSaveNode(node) { removeLegacyAutoSaveNodes(node); saveNode.pos = legacyPosition ? [legacyPosition[0], legacyPosition[1]] - : [node.pos[0] + node.size[0] + 70, node.pos[1] + 30]; + : nextHorizontalSaveNodePos(node, findAllConnectedSaveNodes(node)); saveNode.properties ??= {}; saveNode.properties.o1keyAutoCreated = true; graph.add(saveNode); @@ -2136,6 +2660,171 @@ function ensureSaveNode(node) { } } +function isVueNodesEnabled() { + try { + if (window.LiteGraph?.vueNodesMode === true) return true; + return Boolean(app?.ui?.settings?.getSettingValue?.("Comfy.VueNodes.Enabled")); + } catch { + return false; + } +} + +function nodeTitleChromeHeight() { + const title = Number(window.LiteGraph?.NODE_TITLE_HEIGHT); + if (Number.isFinite(title) && title >= 0) { + // Vue Nodes often keep the title outside the body box (title height 0). + if (isVueNodesEnabled()) return title > 0 ? title : 0; + return title > 0 ? title : 30; + } + return isVueNodesEnabled() ? 0 : 30; +} + +function generatorChromeHeight() { + // Classic LiteGraph folds title + widget padding into node.size. + // Vue Nodes body size is closer to content; keep a small inset only. + return isVueNodesEnabled() + ? 16 + : nodeTitleChromeHeight() + 18; +} + +function generatorMinimumHeight(node) { + const denseLayout = isGptImageModel(node?._o1igModel?.value); + if (node?._o1igBatchEnabled) { + return denseLayout ? GENERATOR_DENSE_BATCH_MIN_HEIGHT : GENERATOR_BATCH_MIN_HEIGHT; + } + return denseLayout ? GENERATOR_DENSE_MIN_HEIGHT : GENERATOR_MIN_SIZE[1]; +} + +function domWidgetChrome(widget, element) { + // LiteGraph reserves a margin around every DOM widget (10px top + bottom by default). + // Keep the value self-calibrating so a frontend theme change cannot leave a gap. + const computed = Number(widget?.computedHeight); + const laidOut = Number(element?.offsetHeight); + if (computed > 0 && laidOut > 0 && computed > laidOut) { + const chrome = computed - laidOut; + if (chrome >= 8 && chrome <= 40) return chrome; + } + return DOM_WIDGET_CHROME; +} + +function measurePanelContentHeight(node) { + const panel = node?._o1igPanel; + const children = panel?.children; + if (!children?.length) return 0; + let total = 0; + let count = 0; + for (const child of children) { + // Heights come from layout (offsetHeight) so they stay correct on a zoomed canvas. + // Flexible children report their current grown height, so fall back to the CSS basis. + const basis = Number(child?.dataset?.o1igHeight) || 0; + const height = basis > 0 ? basis : Number(child?.offsetHeight) || 0; + if (height <= 0) continue; + total += height; + count += 1; + } + if (count < 2) return 0; // Panel not laid out yet. + return Math.ceil(total + (count - 1) * PANEL_CONTENT_GAP + PANEL_CONTENT_PADDING); +} + +function generatorPanelMinHeight(node) { + // The dragged-out height belongs to the prompt area: the Vue node grid sizes rows from the + // panel's min-content height, so folding it in here (instead of leaving it to the node body) + // is what makes the textarea grow while the parameter rows stay flush against the button. + const extra = generatorExtraHeight(node); + if (USE_NATIVE_LITEGRAPH_PARAMETERS) { + const measured = measurePanelContentHeight(node); + if (measured > 0) return measured + extra + domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel); + return (node?._o1igBatchEnabled ? 500 : 360) + extra; + } + const fallback = Math.max(292, generatorMinimumHeight(node) - generatorChromeHeight()); + const measured = measurePanelContentHeight(node); + return measured > 0 ? measured + extra + domWidgetChrome(node?._o1igPanelWidget, node?._o1igPanel) : fallback + extra; +} + +function actionsContentHeight(node) { + return ACTIONS_BASE_HEIGHT + (statusLineVisible(node) ? ACTIONS_STATUS_HEIGHT : 0); +} + +function actionsWidgetHeight(node) { + return actionsContentHeight(node) + domWidgetChrome(node?._o1igActionsWidget, node?._o1igActions); +} + +function generatorContentHeight(node, width) { + // LiteGraph owns widget stacking: let it sum every widget (panel, native params, action bar). + const computed = Number(node?.computeSize?.([width])?.[1]) || 0; + const fallback = generatorMinimumHeight(node); + return Math.max(GENERATOR_COMPACT_MIN_HEIGHT, computed || fallback); +} + +function measureNodeExtent(node, fallbackSize = SAVE_NODE_LAYOUT_SIZE) { + const rawWidth = Number(node?.size?.[0]) || 0; + const rawHeight = Number(node?.size?.[1]) || 0; + const width = rawWidth > 0 ? rawWidth : Number(fallbackSize?.[0]) || 0; + const height = rawHeight > 0 ? rawHeight : Number(fallbackSize?.[1]) || 0; + const x = Number(node?.pos?.[0]) || 0; + const y = Number(node?.pos?.[1]) || 0; + return { + x, + y, + width, + height, + right: x + width, + bottom: y + height, + }; +} + +function nextHorizontalSaveNodePos(generator, existingNodes = [], outputIndex = 0) { + const generatorExtent = measureNodeExtent(generator, [ + Math.max(Number(generator?.size?.[0]) || 0, GENERATOR_MIN_SIZE[0]), + Math.max(Number(generator?.size?.[1]) || 0, GENERATOR_MIN_SIZE[1]), + ]); + const originGap = SAVE_NODE_LAYOUT_ORIGIN_GAP_X; + const gapX = SAVE_NODE_LAYOUT_GAP_X; + // Keep classic optical offset under LiteGraph; Vue body already aligns with the title bar. + const defaultY = generatorExtent.y + (isVueNodesEnabled() ? 0 : 30); + void outputIndex; + + const peers = (Array.isArray(existingNodes) ? existingNodes : []).filter(Boolean); + if (!peers.length) { + return [generatorExtent.right + originGap, defaultY]; + } + + let rightmost = null; + for (const peer of peers) { + const extent = measureNodeExtent(peer); + if (!rightmost || extent.right > rightmost.right + 0.5) rightmost = extent; + else if (rightmost && Math.abs(extent.right - rightmost.right) <= 0.5 && extent.y < rightmost.y) { + rightmost = extent; + } + } + + let x = rightmost.right + gapX; + const y = Number.isFinite(rightmost.y) ? rightmost.y : defaultY; + // Push further right until the reserved layout box no longer overlaps peers. + for (let guard = 0; guard < 64; guard += 1) { + let hit = null; + for (const peer of peers) { + const extent = measureNodeExtent(peer); + const overlapsX = x < extent.right + 1 && (x + SAVE_NODE_LAYOUT_SIZE[0]) > extent.x - 1; + const overlapsY = y < extent.bottom + 1 && (y + SAVE_NODE_LAYOUT_SIZE[1]) > extent.y - 1; + if (overlapsX && overlapsY) { + hit = extent; + break; + } + } + if (!hit) break; + x = hit.right + gapX; + } + return [x, y]; +} + +function estimateSaveNodeChromeHeight(node) { + // Prefer a style-aware constant. Deriving chrome from current node.height + // while resizing creates a feedback loop that prevents shrinking. + void node; + return isVueNodesEnabled() ? SAVE_NODE_CHROME_VUE_FALLBACK : SAVE_NODE_CHROME_FALLBACK; +} + function createSaveNodeForBatch(node, batchId = createBatchId(), outputIndex = 0) { const graph = node.graph || app.graph; const LiteGraph = window.LiteGraph; @@ -2149,15 +2838,10 @@ function createSaveNodeForBatch(node, batchId = createBatchId(), outputIndex = 0 const savedIndex = Number(connectedNode.properties?.o1keyBatchIndex) || index + 1; return Math.max(maximum, savedIndex); }, 0); - const column = batchIndex % 3; - const row = Math.floor(batchIndex / 3); graph.beforeChange?.(); try { - saveNode.pos = [ - node.pos[0] + node.size[0] + 70 + column * (SAVE_NODE_LAYOUT_SIZE[0] + 40), - node.pos[1] + 30 + row * (SAVE_NODE_LAYOUT_SIZE[1] + 50), - ]; + saveNode.pos = nextHorizontalSaveNodePos(node, connectedSaveNodes, outputIndex); saveNode.properties ??= {}; saveNode.properties.o1keyAutoCreated = true; saveNode.properties.o1keyBatchIndex = batchIndex + 1; @@ -2614,7 +3298,19 @@ function normalizeLayerMetadata(value) { return normalized; } +function isGifSaveResult(item) { + const name = String(item?.filename || item?.name || ""); + return /\.gif$/i.test(name) || item?.media === "gif" || item?.animated === true; +} + +function animatedFlagsForSaveResults(images) { + const list = normalizeSaveResults(images); + if (!list.some(isGifSaveResult)) return null; + return list.map(isGifSaveResult); +} + function normalizeSaveResults(images) { + if (!Array.isArray(images)) return []; return images.map((item) => { const filename = String(item?.filename || item?.name || ""); @@ -2626,6 +3322,8 @@ function normalizeSaveResults(images) { }; if (item?.external_saved === true) normalized.external_saved = true; if (item?.batch_id) normalized.batch_id = String(item.batch_id); + if (item?.media) normalized.media = String(item.media); + if (item?.animated === true) normalized.animated = true; const requestIndex = Math.max(0, Math.floor(Number(item?.request_index) || 0)); const resultIndex = Math.max(0, Math.floor(Number(item?.result_index) || 0)); if (requestIndex) normalized.request_index = requestIndex; @@ -2689,12 +3387,13 @@ function expandPanelGenerationTasks({ prompt, imageCount = 1, batchEnabled = false, - batchMode = BATCH_MODE_GROUP_TO_MODELS, + batchMode = BATCH_MODE_GROUP_TO_TARGETS, references = [], modelReferences = [], } = {}) { const prompts = expandPanelPromptTasks(prompt, 1); const count = Math.max(1, Math.floor(Number(imageCount) || 1)); + batchMode = normalizeBatchMode(batchMode); let pairings = [{ references: [...references], outfitIndex: null, modelIndex: null }]; if (batchEnabled) { if (batchMode === BATCH_MODE_SINGLE_REFERENCES) { @@ -2705,7 +3404,7 @@ function expandPanelGenerationTasks({ })); } else { if (!references.length || !modelReferences.length) return []; - pairings = batchMode === BATCH_MODE_CARTESIAN + pairings = batchMode === BATCH_MODE_ALL_PAIRS ? references.flatMap((outfit, outfitIndex) => modelReferences.map((model, modelIndex) => ({ references: [outfit, model], outfitIndex, @@ -2728,7 +3427,7 @@ function panelGenerationTasks(node, prompt, imageCount) { prompt, imageCount, batchEnabled: Boolean(node?._o1igBatchEnabled), - batchMode: node?._o1igBatchMode?.value || BATCH_MODE_GROUP_TO_MODELS, + batchMode: batchModeOf(node), references: node?._o1igReferences || [], modelReferences: node?._o1igModelReferences || [], }); @@ -2745,11 +3444,11 @@ function updateBatchReferenceHint(node) { } hint.textContent = !enabled ? `${referenceCount} 张 · 最多 ${MAX_REQUEST_REFERENCES} 张` - : node._o1igBatchMode?.value === BATCH_MODE_SINGLE_REFERENCES - ? `${referenceCount} 张 · 每张独立生成` - : node._o1igBatchMode?.value === BATCH_MODE_CARTESIAN - ? `${referenceCount} 张 · 匹配时每张独立` - : `${referenceCount} 张 · 整组参与`; + : batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES + ? `${referenceCount} 张 · 各自独立` + : batchModeOf(node) === BATCH_MODE_ALL_PAIRS + ? `${referenceCount} 张 · 两两匹配` + : `${referenceCount} 张 · 整组共用`; if (node?._o1igModel?.value === "Seedream 5.0 Pro") { const layerDecomposition = node?._o1igLayerDecomposition?.value === "开启"; hint.title = layerDecomposition @@ -2759,44 +3458,61 @@ function updateBatchReferenceHint(node) { hint.title = ""; } if (node._o1igModelHint) { - node._o1igModelHint.textContent = `${modelCount} 张 · 每张目标图单独参与组合`; + node._o1igModelHint.textContent = `${modelCount} 张 · 每张单独参与组合`; } + // In batch mode the pairing preview below the tracks already carries the counts, + // so the header hints are dropped to keep the lane titles clean. + hint.classList?.toggle("hidden", enabled); + node._o1igModelHint?.classList?.toggle("hidden", enabled); +} + +// Pairing preview shared by the panel row and the queue check: one source of truth. +function batchGenerationPreview(node) { + if (!node?._o1igBatchEnabled) return null; + const sources = node._o1igReferences?.length || 0; + const targets = node._o1igModelReferences?.length || 0; + const perPair = Math.max(1, Math.floor(Number(node._o1igCount?.value) || 1)); + const promptCount = Math.max(1, expandPanelPromptTasks(node._o1igPrompt?.value || "", 1).length); + const mode = batchModeOf(node); + const singleReferences = mode === BATCH_MODE_SINGLE_REFERENCES; + const allPairs = mode === BATCH_MODE_ALL_PAIRS; + const pairCount = singleReferences ? sources : allPairs ? sources * targets : targets; + if (singleReferences ? !sources : (!sources || !targets)) return null; + const parts = []; + if (singleReferences) { + parts.push(`${sources} 张素材·各自独立`); + } else if (allPairs) { + parts.push(`${sources} 张素材 × ${targets} 个目标 = ${pairCount} 组`); + } else { + parts.push(`整组 ${sources} 张素材 × ${targets} 个目标 = ${pairCount} 组`); + } + parts.push(`每组 ${perPair} 张`); + if (promptCount > 1) parts.push(`${promptCount} 条提示词`); + return { + detail: parts.join(" · "), + totalCount: pairCount * perPair * promptCount, + total: `共 ${pairCount * perPair * promptCount} 张`, + }; } function updateBatchSummary(node) { const summary = node?._o1igBatchSummary; if (!summary) return; - const enabled = Boolean(node._o1igBatchEnabled); updateBatchReferenceHint(node); - if (!enabled) { + const preview = batchGenerationPreview(node); + const detail = node._o1igBatchSummaryDetail; + const total = node._o1igBatchSummaryTotal; + if (!preview) { + // Clear the spans instead of the container: writing to `summary.textContent` + // would detach them, and the preview could never render again. summary.classList.remove("visible"); - summary.textContent = ""; - return; - } - const outfits = node._o1igReferences?.length || 0; - const models = node._o1igModelReferences?.length || 0; - const perPair = Math.max(1, Math.floor(Number(node._o1igCount?.value) || 1)); - const promptCount = Math.max(1, expandPanelPromptTasks(node._o1igPrompt?.value || "", 1).length); - const singleReferences = node._o1igBatchMode?.value === BATCH_MODE_SINGLE_REFERENCES; - const pairCount = singleReferences - ? outfits - : node._o1igBatchMode?.value === BATCH_MODE_CARTESIAN - ? outfits * models - : models; - if (singleReferences ? !outfits : (!outfits || !models)) { - summary.classList.remove("visible"); - summary.textContent = ""; + if (detail) detail.textContent = ""; + if (total) total.textContent = ""; return; } summary.classList.add("visible"); - const total = pairCount * perPair * promptCount; - const pairingText = singleReferences - ? `${outfits} 张素材(每张独立)` - : node._o1igBatchMode?.value === BATCH_MODE_CARTESIAN - ? `${outfits} 个素材 × ${models} 个目标 = ${pairCount} 个组合` - : `1 组素材 × ${models} 个目标 = ${pairCount} 个组合`; - const promptText = promptCount > 1 ? ` × ${promptCount} 条提示词` : ""; - summary.textContent = `${pairingText} × 每组 ${perPair} 张${promptText},共 ${total} 张`; + if (detail) detail.textContent = preview.detail; + if (total) total.textContent = preview.total; } function normalizeSaveSlots(slots) { @@ -3017,8 +3733,8 @@ function syncSaveSlotsWidget(node) { } grid.append(card); } - const desiredHeight = widgetHeight + 140; - if (Array.isArray(node.size) && Number(node.size[1]) < desiredHeight) { + const desiredHeight = widgetHeight + estimateSaveNodeChromeHeight(node); + if (Array.isArray(node.size) && Math.abs(Number(node.size[1]) - desiredHeight) > 1) { node.setSize?.([node.size[0], desiredHeight]); } node.setDirtyCanvas?.(true, true); @@ -3436,6 +4152,8 @@ async function promoteTempResults(batchId, saveNode, images) { function dispatchSaveResults(saveNode, batchId, images) { const output = { images }; + const animated = animatedFlagsForSaveResults(images); + if (animated) output.animated = animated; saveNode._o1igsDispatchBatchId = batchId; if (typeof api.dispatchCustomEvent === "function") { api.dispatchCustomEvent("executed", { @@ -3744,7 +4462,6 @@ async function regenerateFromSaveNode(node, imageIndex = 0) { const nextSeed = Math.floor(Math.random() * 0x7fffffff); setWidgetValue(source, "seed", nextSeed); - if (source._o1igSeed) source._o1igSeed.value = String(nextSeed); await queueGeneration(source, 1); } @@ -3760,7 +4477,6 @@ async function retryFailedSaveSlot(node, slotIndex) { } const nextSeed = Math.floor(Math.random() * 0x7fffffff); setWidgetValue(source, "seed", nextSeed); - if (source._o1igSeed) source._o1igSeed.value = String(nextSeed); await queueGeneration(source, 1, { targetSaveNode: node, retrySlotIndex: slot.index, @@ -3773,25 +4489,18 @@ function syncBatchLayout(node) { if (!node?._o1igBatchToggle) return; const enabled = Boolean(node._o1igBatchEnabled); const singleReferences = enabled - && node._o1igBatchMode?.value === BATCH_MODE_SINGLE_REFERENCES; + && batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES; node._o1igBatchToggle.classList.toggle("enabled", enabled); node._o1igBatchToggle.setAttribute("aria-pressed", enabled ? "true" : "false"); node._o1igBatchModeWrap?.classList.toggle("visible", enabled); node._o1igModelAssets?.classList.toggle("visible", enabled && !singleReferences); - if (node._o1igAddLabel) { - node._o1igAddLabel.textContent = "上传"; - } if (node._o1igCountLabel) { node._o1igCountLabel.textContent = singleReferences ? "每图生成数" : enabled ? "每组生图数" : "生图数量"; } const capabilities = MODEL_CAPABILITIES[node._o1igModel?.value] || MODEL_CAPABILITIES["Nano Banana 2"]; setFieldVisible(node._o1igMaskField, Boolean(capabilities.mask && !enabled)); setWidgetValue(node, "批量出图", enabled); - setWidgetValue( - node, - "批量模式", - node._o1igBatchMode?.value || BATCH_MODE_GROUP_TO_MODELS, - ); + setWidgetValue(node, "批量模式", batchModeOf(node)); setWidgetValue(node, "模特图清单", JSON.stringify(node._o1igModelReferences || [])); renderReferences(node); updateBatchSummary(node); @@ -3799,7 +4508,8 @@ function syncBatchLayout(node) { } function syncModelOptions(node) { - const model = node._o1igModel.value; + const model = normalizeUnifiedModel(node._o1igModel.value); + node._o1igModel.value = model; const capabilities = MODEL_CAPABILITIES[model] || MODEL_CAPABILITIES["Nano Banana 2"]; const isGptImage = isGptImageModel(model); if (isGptImage && node._o1igApplyGptDefaults) { @@ -3814,28 +4524,23 @@ function syncModelOptions(node) { const layerDecomposition = isSeedream && node._o1igLayerDecomposition?.value === "开启"; const isNano2 = model === "Nano Banana 2.1" || model === "Nano Banana 2"; - const isNano2Lite = model === "Nano Banana 2 Lite"; const resolutions = isSeedream ? layerDecomposition ? SEEDREAM_LAYER_RESOLUTIONS : SEEDREAM_RESOLUTIONS : isGptImage ? GPT_RESOLUTIONS - : model === "Nano Banana" - ? ["智能", "1K"] - : isNano2Lite - ? ALL_RESOLUTIONS - : ["智能", "1K", "2K", "4K"]; + : ["智能", "1K", "2K", "4K"]; const ratios = isSeedream ? SEEDREAM_RATIOS : isGptImage ? GPT_RATIOS - : isNano2 || isNano2Lite + : isNano2 ? ALL_RATIOS : ALL_RATIOS.filter((ratio) => !NANO2_ONLY_RATIOS.has(ratio)); replaceOptions(node._o1igResolution, resolutions, findWidget(node, "分辨率")?.value || "智能"); replaceOptions(node._o1igRatio, ratios, findWidget(node, "宽高比")?.value || "智能"); replaceOptions(node._o1igCount, imageCountOptions(model, node._o1igCount.value), node._o1igCount.value); if (isGptImage) { - const qualities = model.startsWith("gpt-image-2.5-") ? GPT_25_QUALITIES : GPT_QUALITIES; + const qualities = /^gpt-image-2\.[56]-/.test(model) ? GPT_25_QUALITIES : GPT_QUALITIES; replaceOptions( node._o1igQuality, qualities, @@ -3853,12 +4558,33 @@ function syncModelOptions(node) { setFieldVisible(node._o1igCountField, !layerDecomposition); } setFieldVisible(node._o1igThinkingField, capabilities.thinking); - setFieldVisible(node._o1igOnlineSearchField, capabilities.search); setFieldVisible(node._o1igQualityField, capabilities.quality); + setFieldVisible(node._o1igComplexityField, capabilities.complexity === true); setFieldVisible(node._o1igOutputFormatField, capabilities.output && !layerDecomposition); setFieldVisible(node._o1igBackgroundField, isGptImage); setFieldVisible(node._o1igResizeField, capabilities.resize); setFieldVisible(node._o1igMaskField, capabilities.mask && !node._o1igBatchEnabled); + if (USE_NATIVE_LITEGRAPH_PARAMETERS) { + setNativeWidgetVisible(node, "思考等级", capabilities.thinking); + setNativeWidgetVisible(node, "质量", capabilities.quality); + setNativeWidgetVisible(node, "复杂度", capabilities.complexity === true); + setNativeWidgetVisible(node, "输出格式", capabilities.output && !layerDecomposition); + setNativeWidgetVisible(node, "背景", isGptImage); + setNativeWidgetVisible(node, "缩放图片", capabilities.resize); + setNativeWidgetVisible(node, "图层拆分", isSeedream); + setNativeWidgetVisible(node, "格式", capabilities.saveFormat); + setNativeWidgetVisible(node, "批量模式", Boolean(node._o1igBatchEnabled)); + setNativeWidgetVisible( + node, + "帧数", + capabilities.frames === true && node._o1igOutputFormat?.value === "gif", + ); + setNativeWidgetVisible( + node, + "帧时长ms", + capabilities.frames === true && node._o1igOutputFormat?.value === "gif", + ); + } syncGptOutputOptions(node); syncGeneratorSaveControls(node); syncResizeWarning(node); @@ -3866,7 +4592,6 @@ function syncModelOptions(node) { setWidgetValue(node, "分辨率", node._o1igResolution.value); setWidgetValue(node, "宽高比", node._o1igRatio.value); setWidgetValue(node, "质量", node._o1igQuality.value); - setWidgetValue(node, "在线搜索", node._o1igOnlineSearch.value); setWidgetValue(node, "缩放图片", node._o1igResize.value); setWidgetValue( node, @@ -3876,8 +4601,11 @@ function syncModelOptions(node) { setWidgetValue(node, "输出格式", node._o1igOutputFormat.value); setWidgetValue(node, "图层拆分", layerDecomposition); if (node._o1igOutputsReady) syncGeneratorOutputVisibility(node); - if (node._o1igBatchBar) node._o1igBatchBar.style.display = layerDecomposition ? "none" : ""; + if (node._o1igBatchBar) { + node._o1igBatchBar.style.display = USE_NATIVE_LITEGRAPH_PARAMETERS || layerDecomposition ? "none" : ""; + } syncBatchLayout(node); + syncNativeWidgetOptions(node); } async function optimizePrompt(node) { @@ -3950,8 +4678,7 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { const prompt = String(options?.promptOverride ?? node._o1igPrompt.value).trim(); const saveSettings = generatorSaveSettings(node); if (!prompt && !layerDecomposition) { - setStatus(node, "请输入提示词", "error"); - node._o1igPrompt.focus(); + flagEmptyPrompt(node); return; } if (node._o1igOptimizing) { @@ -3967,9 +4694,9 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { return; } if (node._o1igBatchEnabled && !retrySlotIndex) { - const singleReferences = node._o1igBatchMode.value === BATCH_MODE_SINGLE_REFERENCES; + const singleReferences = batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES; if (singleReferences && !node._o1igReferences.length) { - setStatus(node, "单图批量至少需要上传1张素材图", "error"); + setStatus(node, "每张素材单独出图至少需要上传1张素材图", "error"); return; } if (!singleReferences && !node._o1igReferences.length) { @@ -3981,7 +4708,7 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { return; } if ( - node._o1igBatchMode.value === BATCH_MODE_GROUP_TO_MODELS + batchModeOf(node) === BATCH_MODE_GROUP_TO_TARGETS && node._o1igReferences.length >= MAX_REQUEST_REFERENCES ) { setStatus(node, "整组素材模式最多上传9张素材图(另加1张目标图)", "error"); @@ -4003,15 +4730,16 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { setWidgetValue(node, "分辨率", node._o1igResolution.value); setWidgetValue(node, "宽高比", node._o1igRatio.value); if (!retrySlotIndex) setWidgetValue(node, "生图数量", normalizeImageCount(node._o1igCount.value, node._o1igModel.value)); - setWidgetValue(node, "seed", Math.max(0, Math.floor(Number(node._o1igSeed.value) || 0))); + // The native seed widget already holds the value the queue will read. setWidgetValue(node, "参考图清单", JSON.stringify(node._o1igReferences)); setWidgetValue(node, "质量", node._o1igQuality.value); setWidgetValue(node, "输出格式", node._o1igOutputFormat.value); setWidgetValue(node, "蒙版清单", JSON.stringify(node._o1igMask || {})); setWidgetValue(node, "缩放图片", node._o1igResize.value); setWidgetValue(node, "背景", node._o1igBackground.value); + setWidgetValue(node, "复杂度", normalizeGptComplexityLabel(node._o1igComplexity?.value)); setWidgetValue(node, "批量出图", Boolean(node._o1igBatchEnabled)); - setWidgetValue(node, "批量模式", node._o1igBatchMode.value); + setWidgetValue(node, "批量模式", batchModeOf(node)); setWidgetValue(node, "模特图清单", JSON.stringify(node._o1igModelReferences)); setWidgetValue(node, "命名规则", saveSettings.naming_rule); setWidgetValue(node, "filename_prefix", saveSettings.filename_prefix); @@ -4088,7 +4816,7 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { resolution: node._o1igResolution.value, aspect_ratio: node._o1igRatio.value, image_count: retryTask ? 1 : Number(requestedImageCount), - seed: Math.max(0, Math.floor(Number(node._o1igSeed.value) || 0)), + seed: generatorSeed(node), quality: node._o1igQuality.value, resize_mode: node._o1igResize.value, filename_prefix: saveSettings.filename_prefix, @@ -4108,8 +4836,8 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { } : null, batch_enabled: retryTask ? false : Boolean(node._o1igBatchEnabled), - batch_mode: node._o1igBatchMode.value, - model_references: retryTask || node._o1igBatchMode.value === BATCH_MODE_SINGLE_REFERENCES + batch_mode: batchModeOf(node), + model_references: retryTask || batchModeOf(node) === BATCH_MODE_SINGLE_REFERENCES ? [] : node._o1igModelReferences.map((item) => ({ name: String(item.name), @@ -4120,14 +4848,16 @@ async function queueGeneration(node, imageCountOverride = null, options = {}) { if (isGptImageModel(node._o1igModel.value)) { jobPayload.output_format = node._o1igOutputFormat.value; jobPayload.background = node._o1igBackground.value; + if (MODEL_CAPABILITIES[node._o1igModel.value]?.complexity) { + jobPayload.complexity = normalizeGptComplexityLabel(node._o1igComplexity.value); + } + if (node._o1igOutputFormat.value === "gif") { + jobPayload.frame_count = Number(node._o1igFrameCount?.value) || 9; + jobPayload.frame_duration_ms = Number(node._o1igFrameDuration?.value) || 200; + } } else if (node._o1igModel.value === "Seedream 5.0 Pro") { jobPayload.output_format = node._o1igOutputFormat.value; if (layerDecomposition) jobPayload.layer_decomposition = true; - } else if ( - ["Nano Banana 2.1", "Nano Banana 2"].includes(node._o1igModel.value) - && node._o1igOnlineSearch.value === "打开" - ) { - jobPayload.google_search = true; } const response = await api.fetchApi("/o1key/image/jobs", { method: "POST", @@ -4211,29 +4941,9 @@ function buildPanel(node) { refs.className = "o1ig-refs"; refs.addEventListener("wheel", (event) => event.stopPropagation()); bindImageFileDropTarget(node, refs); - const add = document.createElement("button"); - add.type = "button"; - add.className = "o1ig-add"; - add.title = "添加参考图"; - const addIcon = document.createElement("b"); - addIcon.textContent = "+"; - const addLabel = document.createElement("span"); - addLabel.textContent = "参考图"; - add.append(addIcon, addLabel); - const fileInput = document.createElement("input"); - fileInput.type = "file"; - fileInput.accept = "image/png,image/jpeg,image/webp,image/gif,image/bmp"; - fileInput.multiple = true; - fileInput.hidden = true; - add.append(fileInput); - add.addEventListener("click", (event) => { - if (event.target !== fileInput) fileInput.click(); - }); - fileInput.addEventListener("change", async () => { - await acceptFiles(node, fileInput.files); - fileInput.value = ""; - }); - bindImageFileDropTarget(node, add); + // The trailing "+ 添加…" card is the only upload entry point; the header keeps + // just 画布取图, so the picker input lives beside the track instead of inside a button. + const fileInput = createReferenceFileInput(node, "references"); const canvasPick = document.createElement("button"); canvasPick.type = "button"; canvasPick.className = "o1ig-add o1ig-canvas-pick"; @@ -4251,19 +4961,19 @@ function buildPanel(node) { referenceTitle.textContent = "素材图"; const referenceHint = document.createElement("span"); referenceHint.className = "o1ig-asset-hint"; - referenceHint.textContent = "整组参与"; + referenceHint.textContent = ""; const referenceMeta = document.createElement("div"); referenceMeta.className = "o1ig-asset-meta"; referenceMeta.append(referenceTitle, referenceHint); const referenceActions = document.createElement("div"); referenceActions.className = "o1ig-asset-actions"; - referenceActions.append(add, canvasPick); + referenceActions.append(canvasPick); referenceHeader.append(referenceMeta, referenceActions); const referenceAssets = document.createElement("div"); referenceAssets.className = "o1ig-assets"; const replaceInput = document.createElement("input"); replaceInput.type = "file"; - replaceInput.accept = fileInput.accept; + replaceInput.accept = IMAGE_FILE_ACCEPT; replaceInput.hidden = true; replaceInput.addEventListener("change", async () => { const target = node._o1igReplaceTarget; @@ -4272,34 +4982,13 @@ function buildPanel(node) { replaceInput.value = ""; if (target && file) await replaceReference(node, target.role, target.original, file); }); - referenceAssets.append(referenceHeader, refs, replaceInput); + referenceAssets.append(referenceHeader, refs, replaceInput, fileInput); const modelRefs = document.createElement("div"); modelRefs.className = "o1ig-refs"; modelRefs.addEventListener("wheel", (event) => event.stopPropagation()); bindImageFileDropTarget(node, modelRefs, "models"); - const modelAdd = document.createElement("button"); - modelAdd.type = "button"; - modelAdd.className = "o1ig-add"; - modelAdd.title = "添加目标图"; - const modelAddIcon = document.createElement("b"); - modelAddIcon.textContent = "+"; - const modelAddLabel = document.createElement("span"); - modelAddLabel.textContent = "上传"; - const modelFileInput = document.createElement("input"); - modelFileInput.type = "file"; - modelFileInput.accept = "image/png,image/jpeg,image/webp,image/gif,image/bmp"; - modelFileInput.multiple = true; - modelFileInput.hidden = true; - modelAdd.append(modelAddIcon, modelAddLabel, modelFileInput); - modelAdd.addEventListener("click", (event) => { - if (event.target !== modelFileInput) modelFileInput.click(); - }); - modelFileInput.addEventListener("change", async () => { - await acceptFiles(node, modelFileInput.files, "models"); - modelFileInput.value = ""; - }); - bindImageFileDropTarget(node, modelAdd, "models"); + const modelFileInput = createReferenceFileInput(node, "models"); const modelCanvasPick = document.createElement("button"); modelCanvasPick.type = "button"; modelCanvasPick.className = "o1ig-add o1ig-canvas-pick"; @@ -4316,17 +5005,17 @@ function buildPanel(node) { modelTitle.textContent = "目标图"; const modelHint = document.createElement("span"); modelHint.className = "o1ig-asset-hint"; - modelHint.textContent = "每张目标图单独参与组合"; + modelHint.textContent = ""; const modelMeta = document.createElement("div"); modelMeta.className = "o1ig-asset-meta"; modelMeta.append(modelTitle, modelHint); const modelActions = document.createElement("div"); modelActions.className = "o1ig-asset-actions"; - modelActions.append(modelAdd, modelCanvasPick); + modelActions.append(modelCanvasPick); modelHeader.append(modelMeta, modelActions); const modelAssets = document.createElement("div"); modelAssets.className = "o1ig-assets o1ig-model-assets"; - modelAssets.append(modelHeader, modelRefs); + modelAssets.append(modelHeader, modelRefs, modelFileInput); const batchToggle = document.createElement("button"); batchToggle.type = "button"; @@ -4338,7 +5027,7 @@ function buildPanel(node) { batchToggle.append(batchToggleLabel, batchSwitch); const batchMode = makeSelect( BATCH_MODE_OPTIONS, - findWidget(node, "批量模式")?.value || BATCH_MODE_GROUP_TO_MODELS, + normalizeBatchMode(findWidget(node, "批量模式")?.value), "批量模式", ); const batchModeWrap = document.createElement("div"); @@ -4349,6 +5038,12 @@ function buildPanel(node) { batchBar.append(batchToggle, batchModeWrap); const batchSummary = document.createElement("div"); batchSummary.className = "o1ig-batch-summary"; + batchSummary.title = "预计出图张数 = 组合数 × 每组张数 × 提示词条数,实际以队列结果为准"; + const batchSummaryDetail = document.createElement("span"); + batchSummaryDetail.className = "o1ig-batch-summary-detail"; + const batchSummaryTotal = document.createElement("span"); + batchSummaryTotal.className = "o1ig-batch-summary-total"; + batchSummary.append(batchSummaryDetail, batchSummaryTotal); const prompt = document.createElement("textarea"); prompt.className = "o1ig-prompt"; @@ -4373,11 +5068,17 @@ function buildPanel(node) { promptOptimizeStatus.setAttribute("aria-live", "polite"); const promptWrap = document.createElement("div"); promptWrap.className = "o1ig-prompt-wrap"; + // Flexible child: report its CSS basis when the panel is measured for the node height. + promptWrap.dataset.o1igHeight = String(PROMPT_DEFAULT_HEIGHT); promptWrap.append(prompt, promptOptimizeStatus, promptOptimize); const toolbar = document.createElement("div"); toolbar.className = "o1ig-toolbar"; - const model = makeSelect(MODEL_OPTIONS, findWidget(node, "模型")?.value || "Nano Banana 2.1", "模型"); + const model = makeSelect( + MODEL_OPTIONS, + normalizeUnifiedModel(findWidget(node, "模型")?.value || "Nano Banana 2.1"), + "模型", + ); const resolution = makeSelect(ALL_RESOLUTIONS, findWidget(node, "分辨率")?.value || "智能", "分辨率"); const ratio = makeSelect(ALL_RATIOS, findWidget(node, "宽高比")?.value || "智能", "宽高比"); const ratioField = makeAdvancedField("宽高比", ratio); @@ -4385,14 +5086,8 @@ function buildPanel(node) { const countField = makeAdvancedField("生图数量", count); const countLabel = countField.children?.[0] || null; const route = makeSelect(ROUTES, findWidget(node, "模型线路")?.value || "畅速"); - const thinking = makeSelect(THINKING_LEVEL_OPTIONS, findWidget(node, "思考等级")?.value || "低"); + const thinking = makeSelect(THINKING_LEVEL_OPTIONS, findWidget(node, "思考等级")?.value || "高"); const thinkingField = makeAdvancedField("思考等级", thinking); - const onlineSearch = makeSelect( - ONLINE_SEARCH_OPTIONS, - findWidget(node, "在线搜索")?.value || "关闭", - "在线搜索", - ); - const onlineSearchField = makeAdvancedField("在线搜索", onlineSearch); const layerDecomposition = makeSelect( ["关闭", "开启"], findWidget(node, "图层拆分")?.value === true ? "开启" : "关闭", @@ -4400,11 +5095,33 @@ function buildPanel(node) { ); const layerDecompositionField = makeAdvancedField("图层拆分", layerDecomposition); const quality = makeSelect( - model.value.startsWith("gpt-image-2.5-") ? GPT_25_QUALITIES : GPT_QUALITIES, + /^gpt-image-2\.[56]-/.test(model.value) ? GPT_25_QUALITIES : GPT_QUALITIES, findWidget(node, "质量")?.value || "自动", "质量", ); const qualityField = makeAdvancedField("质量", quality); + const complexity = makeSelect( + GPT_COMPLEXITY_OPTIONS, + normalizeGptComplexityLabel(findWidget(node, "复杂度")?.value), + "复杂度", + ); + const complexityField = makeAdvancedField("复杂度", complexity); + const frameCount = document.createElement("input"); + frameCount.className = "o1ig-control"; + frameCount.type = "number"; + frameCount.min = "2"; + frameCount.max = "64"; + frameCount.step = "1"; + frameCount.value = String(findWidget(node, "帧数")?.value ?? 9); + const frameCountField = makeAdvancedField("GIF帧数", frameCount); + const frameDuration = document.createElement("input"); + frameDuration.className = "o1ig-control"; + frameDuration.type = "number"; + frameDuration.min = "20"; + frameDuration.max = "2000"; + frameDuration.step = "10"; + frameDuration.value = String(findWidget(node, "帧时长ms")?.value ?? 200); + const frameDurationField = makeAdvancedField("GIF帧时长ms", frameDuration); const background = makeSelect( GPT_BACKGROUNDS, findWidget(node, "背景")?.value || "auto", @@ -4419,7 +5136,7 @@ function buildPanel(node) { const outputFormatField = makeAdvancedField("输出格式", outputFormat); const resize = makeSelect( RESIZE_OPTIONS, - findWidget(node, "缩放图片")?.value || "不缩放", + findWidget(node, "缩放图片")?.value || "智能缩放", "缩放图片", ); const resizeWarning = document.createElement("div"); @@ -4471,41 +5188,32 @@ function buildPanel(node) { maskWrap.className = "o1ig-mask-wrap"; maskWrap.append(maskButton, maskClear, maskFileInput); const maskField = makeAdvancedField("蒙版", maskWrap); - const seed = document.createElement("input"); - seed.className = "o1ig-control"; - seed.type = "number"; - seed.min = "0"; - seed.value = String(findWidget(node, "seed")?.value || 0); - const dice = document.createElement("button"); - dice.type = "button"; - dice.className = "o1ig-control"; - dice.textContent = "↻"; - dice.title = "随机种子"; - const seedWrap = document.createElement("div"); - seedWrap.className = "o1ig-seed"; - seedWrap.append(seed, dice); toolbar.append( - makePanelSectionTitle("生成参数"), - makeAdvancedField("模型", model), + makeInlineLabelField("模型", model), makeAdvancedField("模型线路", route), makeAdvancedField("分辨率", resolution), ratioField, countField, thinkingField, - onlineSearchField, layerDecompositionField, qualityField, + complexityField, + frameCountField, + frameDurationField, backgroundField, outputFormatField, resizeField, - makeAdvancedField("种子", seedWrap), maskField, - makePanelSectionTitle("保存设置"), namingRuleField, saveFormatField, filenamePrefixField, saveLocationField, ); + if (USE_NATIVE_LITEGRAPH_PARAMETERS) { + toolbar.style.display = "none"; + batchBar.style.display = "none"; + toolbar.removeChild?.(maskField); + } const generate = document.createElement("button"); generate.type = "button"; @@ -4513,38 +5221,62 @@ function buildPanel(node) { generate.textContent = "开始生成"; const status = document.createElement("div"); status.className = "o1ig-status"; + const actions = document.createElement("div"); + actions.className = "o1ig-actions"; + actions.addEventListener("pointerdown", (event) => { + if (openDropdown && !openDropdown.contains(event.target)) closeDropdown(); + event.stopPropagation(); + }); + actions.append(status, generate); panel.append( batchBar, referenceAssets, modelAssets, batchSummary, - makePanelSectionTitle("画面描述"), promptWrap, + ...(USE_NATIVE_LITEGRAPH_PARAMETERS ? [maskField] : []), toolbar, - status, - generate, ); - const panelWidget = node.addDOMWidget("o1key_image_generator_panel", "div", panel, { + const panelWidget = node.addDOMWidget(PANEL_WIDGET_NAME, "div", panel, { serialize: false, hideOnZoom: false, - getMinHeight: () => GENERATOR_PANEL_MIN_HEIGHT, + getMinHeight: () => generatorPanelMinHeight(node), }); + movePanelWidgetToFront(node, panelWidget); + // The action bar owns the last row of the node: it sits under every native parameter row. + const actionsWidget = node.addDOMWidget(ACTIONS_WIDGET_NAME, "div", actions, { + serialize: false, + hideOnZoom: false, + getMinHeight: () => actionsWidgetHeight(node), + getMaxHeight: () => actionsWidgetHeight(node), + }); + node._o1igActions = actions; + node._o1igActionsWidget = actionsWidget; + moveWidgetToEnd(node, actionsWidget); + // LiteGraph restores widgets_values by position, so the DOM widgets must stay out of that + // list; otherwise every backend value after them shifts by one slot. + for (const widget of [panelWidget, actionsWidget]) { + widget.serialize = false; + widget.options ??= {}; + widget.options.serialize = false; + } Object.assign(node, { _o1igPanel: panel, _o1igPanelWidget: panelWidget, + _o1igActions: actions, + _o1igActionsWidget: actionsWidget, _o1igToolbar: toolbar, _o1igRefs: refs, _o1igReplaceInput: replaceInput, - _o1igAdd: add, + _o1igReferenceInput: fileInput, _o1igCanvasPick: canvasPick, - _o1igAddLabel: addLabel, _o1igReferenceHeader: referenceHeader, _o1igReferenceTitle: referenceTitle, _o1igReferenceHint: referenceHint, _o1igModelRefs: modelRefs, - _o1igModelAdd: modelAdd, + _o1igModelInput: modelFileInput, _o1igModelCanvasPick: modelCanvasPick, _o1igModelAssets: modelAssets, _o1igModelHint: modelHint, @@ -4552,6 +5284,8 @@ function buildPanel(node) { _o1igBatchMode: batchMode, _o1igBatchModeWrap: batchModeWrap, _o1igBatchSummary: batchSummary, + _o1igBatchSummaryDetail: batchSummaryDetail, + _o1igBatchSummaryTotal: batchSummaryTotal, _o1igBatchBar: batchBar, _o1igModel: model, _o1igResolution: resolution, @@ -4563,12 +5297,16 @@ function buildPanel(node) { _o1igRoute: route, _o1igThinking: thinking, _o1igThinkingField: thinkingField, - _o1igOnlineSearch: onlineSearch, - _o1igOnlineSearchField: onlineSearchField, _o1igLayerDecomposition: layerDecomposition, _o1igLayerDecompositionField: layerDecompositionField, _o1igQuality: quality, _o1igQualityField: qualityField, + _o1igComplexity: complexity, + _o1igComplexityField: complexityField, + _o1igFrameCount: frameCount, + _o1igFrameCountField: frameCountField, + _o1igFrameDuration: frameDuration, + _o1igFrameDurationField: frameDurationField, _o1igBackground: background, _o1igBackgroundField: backgroundField, _o1igOutputFormat: outputFormat, @@ -4587,13 +5325,13 @@ function buildPanel(node) { _o1igMaskButton: maskButton, _o1igMaskClear: maskClear, _o1igMaskField: maskField, - _o1igSeed: seed, _o1igPrompt: prompt, _o1igPromptOptimize: promptOptimize, _o1igPromptOptimizeStatus: promptOptimizeStatus, _o1igGenerate: generate, _o1igStatus: status, }); + installNativeParameterBridge(node); model.addEventListener("change", () => syncModelOptions(node)); layerDecomposition.addEventListener("change", () => syncModelOptions(node)); @@ -4613,12 +5351,24 @@ function buildPanel(node) { }); route.addEventListener("change", () => setWidgetValue(node, "模型线路", route.value)); thinking.addEventListener("change", () => setWidgetValue(node, "思考等级", thinking.value)); - onlineSearch.addEventListener("change", () => setWidgetValue(node, "在线搜索", onlineSearch.value)); quality.addEventListener("change", () => setWidgetValue(node, "质量", quality.value)); + complexity.addEventListener("change", () => { + complexity.value = normalizeGptComplexityLabel(complexity.value); + setWidgetValue(node, "复杂度", complexity.value); + }); + frameCount.addEventListener("change", () => { + setWidgetValue(node, "帧数", Number(frameCount.value) || 9); + syncGptOutputOptions(node); + }); + frameDuration.addEventListener("change", () => { + setWidgetValue(node, "帧时长ms", Number(frameDuration.value) || 200); + syncGptOutputOptions(node); + }); background.addEventListener("change", () => syncGptOutputOptions(node)); outputFormat.addEventListener("change", () => { node._o1igOutputTouched = true; setWidgetValue(node, "输出格式", outputFormat.value); + syncGptOutputOptions(node); }); resize.addEventListener("change", () => { node._o1igResizeTouched = true; @@ -4664,11 +5414,6 @@ function buildPanel(node) { setWidgetValue(node, "蒙版清单", "{}"); syncMaskControl(node); }); - seed.addEventListener("change", () => setWidgetValue(node, "seed", Math.max(0, Math.floor(Number(seed.value) || 0)))); - dice.addEventListener("click", () => { - seed.value = String(Math.floor(Math.random() * 0x7fffffff)); - setWidgetValue(node, "seed", Number(seed.value)); - }); prompt.addEventListener("input", () => { setWidgetValue(node, "prompt", prompt.value); updateBatchSummary(node); @@ -4682,7 +5427,11 @@ function buildPanel(node) { syncModelOptions(node); syncResizeWarning(node); syncBatchLayout(node); + syncNativeWidgetOptions(node); fitNode(node); + // Node creation runs before LiteGraph restores widgets_values, so the visual reorder + // waits for the next frame to keep the positional restore aligned with the schema. + requestAnimationFrame(() => applyNativeParameterOrder(node)); requestAnimationFrame(() => { node._o1igOutputsReady = true; syncGeneratorOutputVisibility(node); @@ -4708,8 +5457,10 @@ function installNativeMinimumSize(nodeType, minimum) { const originalComputeSize = nodeType.prototype.computeSize; nodeType.prototype.computeSize = function (size) { const computed = originalComputeSize?.call(this, size) || size || [0, 0]; + // Width stays clamped for the field layout; height follows the stacked widgets so the + // node can shrink to its content instead of keeping a fixed blank strip at the bottom. computed[0] = Math.max(Number(computed[0]) || 0, minimum[0]); - computed[1] = Math.max(Number(computed[1]) || 0, minimum[1]); + computed[1] = Math.max(Number(computed[1]) || 0, GENERATOR_COMPACT_MIN_HEIGHT); return computed; }; } @@ -4724,22 +5475,25 @@ function restorePanelFromWidgets(node) { node._o1igBatchEnabled = rawBatchEnabled === true || String(rawBatchEnabled || "").toLowerCase() === "true" || rawBatchEnabled === "开启"; - node._o1igBatchMode.value = findWidget(node, "批量模式")?.value || BATCH_MODE_GROUP_TO_MODELS; - node._o1igModel.value = findWidget(node, "模型")?.value || "Nano Banana 2.1"; + node._o1igBatchMode.value = normalizeBatchMode( + findWidget(node, "批量模式")?.value || BATCH_MODE_GROUP_TO_TARGETS, + ); + node._o1igModel.value = normalizeUnifiedModel(findWidget(node, "模型")?.value || "Nano Banana 2.1"); node._o1igRoute.value = findWidget(node, "模型线路")?.value || "畅速"; - node._o1igThinking.value = findWidget(node, "思考等级")?.value || "低"; - node._o1igOnlineSearch.value = findWidget(node, "在线搜索")?.value || "关闭"; + node._o1igThinking.value = findWidget(node, "思考等级")?.value || "高"; node._o1igQuality.value = findWidget(node, "质量")?.value || "自动"; + node._o1igComplexity.value = normalizeGptComplexityLabel(findWidget(node, "复杂度")?.value); + if (node._o1igFrameCount) node._o1igFrameCount.value = String(findWidget(node, "帧数")?.value ?? 9); + if (node._o1igFrameDuration) node._o1igFrameDuration.value = String(findWidget(node, "帧时长ms")?.value ?? 200); node._o1igOutputFormat.value = findWidget(node, "输出格式")?.value || "jpeg"; node._o1igBackground.value = findWidget(node, "背景")?.value || "auto"; - node._o1igResize.value = findWidget(node, "缩放图片")?.value || "不缩放"; + node._o1igResize.value = findWidget(node, "缩放图片")?.value || "智能缩放"; node._o1igNamingRule.value = findWidget(node, "命名规则")?.value || "自定义前缀"; node._o1igFilenamePrefix.value = findWidget(node, "filename_prefix")?.value || "o1key"; node._o1igSaveFormat.value = findWidget(node, "格式")?.value || "原始"; node._o1igSaveLocation.value = findWidget(node, "保存位置")?.value || ""; node._o1igPrompt.value = findWidget(node, "prompt")?.value || ""; node._o1igCount.value = normalizeImageCount(findWidget(node, "生图数量")?.value, node._o1igModel.value); - node._o1igSeed.value = String(findWidget(node, "seed")?.value || 0); syncModelOptions(node); syncResizeWarning(node); syncBatchLayout(node); @@ -4747,11 +5501,58 @@ function restorePanelFromWidgets(node) { syncMaskControl(node); } +const GENERATOR_SERIALIZED_WIDGETS = BACKEND_WIDGETS.filter(name => !RETIRED_BACKEND_WIDGETS.has(name)); + function serializeGeneratorWidgets(node, data) { - // options.serialize:false excludes prompts, not workflow values. Keep only schema widgets. - data.widgets_values = (node.widgets || []) - .filter(widget => BACKEND_WIDGETS.includes(widget.name) && widget.name !== "内容审查强度") - .map(widget => widget.value); + // widgets_values is positional, so it is always written in schema order. The on-canvas + // order can differ (批量出图 sits above 模型) without touching saved workflows. + const values = []; + for (const name of GENERATOR_SERIALIZED_WIDGETS) { + const widget = findWidget(node, name); + if (widget) values.push(widget.value); + } + data.widgets_values = values; +} + +const PANEL_WIDGET_NAME = "o1key_image_generator_panel"; +const ACTIONS_WIDGET_NAME = "o1key_image_generator_actions"; + +const GENERATOR_LEADING_WIDGETS = ["批量出图", "批量模式"]; +const GENERATOR_DISPLAY_WIDGETS = (() => { + const leading = GENERATOR_LEADING_WIDGETS.filter(name => GENERATOR_SERIALIZED_WIDGETS.includes(name)); + const rest = GENERATOR_SERIALIZED_WIDGETS.filter(name => !leading.includes(name)); + const modelIndex = rest.indexOf("模型"); + if (modelIndex < 0) return [...GENERATOR_SERIALIZED_WIDGETS]; + const display = [...rest]; + display.splice(modelIndex, 0, ...leading); + return display; +})(); + +function orderNativeWidgets(node, order) { + const widgets = node?.widgets; + if (!Array.isArray(widgets) || !order?.length) return; + const rank = new Map(order.map((name, index) => [name, index])); + const keyed = widgets.map((widget, index) => ({ + widget, + index, + key: widget?.name === PANEL_WIDGET_NAME + ? -1 + : widget?.name === ACTIONS_WIDGET_NAME + ? Number.MAX_SAFE_INTEGER + : rank.has(widget?.name) ? rank.get(widget.name) : 500000 + index, + })); + keyed.sort((a, b) => (a.key - b.key) || (a.index - b.index)); + const ordered = keyed.map(item => item.widget); + if (ordered.every((widget, index) => widgets[index] === widget)) return; + widgets.splice(0, widgets.length, ...ordered); + node.setDirtyCanvas?.(true, true); +} + +function applyNativeParameterOrder(node) { + // Display-only: LiteGraph and the Vue nodes render widgets in node.widgets order, so the + // batch rows are pulled up in front of 模型. Saved data keeps the schema order above. + if (!USE_NATIVE_LITEGRAPH_PARAMETERS) return; + orderNativeWidgets(node, GENERATOR_DISPLAY_WIDGETS); } app.registerExtension({ @@ -4851,9 +5652,22 @@ app.registerExtension({ buildPanel(this); }; + const originalConfigureMethod = nodeType.prototype.configure; + nodeType.prototype.configure = function (data) { + // widgets_values is positional, so it is restored against the schema order and only + // then re-ordered for display. Keeps paste / workflow loads aligned no matter when + // applyNativeParameterOrder() already ran. + orderNativeWidgets(this, GENERATOR_SERIALIZED_WIDGETS); + const result = originalConfigureMethod?.apply(this, arguments); + applyNativeParameterOrder(this); + return result; + }; + const originalConfigure = nodeType.prototype.onConfigure; nodeType.prototype.onConfigure = function (data) { this._o1igApplyGptDefaults = false; + // A workflow (re)load is not a gesture: drop a press that never got its pointerup. + resetCanvasPointerGesture(); const result = originalConfigure?.apply(this, arguments); buildPanel(this); restorePanelFromWidgets(this); @@ -4861,6 +5675,64 @@ app.registerExtension({ return result; }; + const originalResize = nodeType.prototype.onResize; + nodeType.prototype.onResize = function (size) { + originalResize?.apply(this, arguments); + // Engine-driven resizes (creation, workflow restore, Vue re-layout after rows + // appear/disappear) must not be treated as a manual resize, otherwise the node + // keeps the taller body and leaves an empty strip when 批量出图 is turned off. + if (this._o1igAutoSizing) return; // Our own setSize(): keep the drag anchor. + if (!this._o1igSettled || !canvasPointerDown) { + this._o1igDragAnchor = null; + return; + } + // Only a press that started on this node can be resizing it. A press on a menu row + // (重启/设置) never restores its pointerup, so without this check the next engine + // re-layout behaves like a drag and the node grows by the mouse travel. + if (!pointerStartsInsideNode(this, canvasPointerStartX, canvasPointerStartY)) { + this._o1igDragAnchor = null; + return; + } + const height = Number(size?.[1]) || 0; + if (!(height > 0)) return; + // While the pointer is down the Vue body is still on the previous layout, so + // computeSize lags behind; follow the pointer delta from the drag start instead. + if (!this._o1igDragAnchor) { + // Anchor on the last programmatic height, not on this event's size: the first + // resize already carries part of the drag. + const baseline = Number(this._o1igSizedHeight); + this._o1igDragAnchor = { + height: Number.isFinite(baseline) && baseline > 0 ? baseline : height, + extra: generatorExtraHeight(this), + pointerY: canvasPointerStartY, + }; + } + const anchor = this._o1igDragAnchor; + const heightDelta = height - anchor.height; + const nextExtra = nextGeneratorExtra(anchor, canvasPointerY, heightDelta, nodeDomScale(this)); + if (nextExtra === null) { + // A width drag keeps LiteGraph's height; just re-fit once it settles. + this.scheduleGeneratorRefit(); + return; + } + setGeneratorExtraHeight(this, nextExtra); + // Live feedback while dragging: the panel grows and the textarea follows. + syncPanelExtraDomHeight(this); + this.scheduleGeneratorRefit(); + }; + + nodeType.prototype.scheduleGeneratorRefit = function () { + clearTimeout(this._o1igResizeFitTimer); + this._o1igResizeFitTimer = setTimeout(() => { + // Never fight the pointer: re-flow once the drag is over. + if (canvasPointerDown) { + this._o1igResizeFitTimer = setTimeout(() => fitNode(this), 200); + return; + } + fitNode(this); + }, 140); + }; + const originalExecutionStart = nodeType.prototype.onExecutionStart; nodeType.prototype.onExecutionStart = function () { originalExecutionStart?.apply(this, arguments);