Add MJ image node, GIF save, and Kling/image generator updates

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.
This commit is contained in:
Jony
2026-11-09 09:11:12 +08:00
parent ff1cf830fa
commit a181cc1768
40 changed files with 6711 additions and 675 deletions
+16 -10
View File
@@ -148,9 +148,11 @@ pip install -r requirements.txt --upgrade
参考图上传完成后,复制、粘贴节点或保存后重新加载工作流,会保留参考图顺序、批量目标图、蒙版和参数。图片清单引用当前 ComfyUI 的本地文件;复制后可独立调整清单。 参考图上传完成后,复制、粘贴节点或保存后重新加载工作流,会保留参考图顺序、批量目标图、蒙版和参数。图片清单引用当前 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`。 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 个参考位。 - 「整组素材→多个目标」会把当前所有素材图作为一组,并依次与每张目标图组成一次请求。例如 3 张素材图、10 张目标图、每组生图数为 1 时,共生成 10 张;该模式每组最多 9 张素材图,为当前目标图保留第 10 个参考位。
- 「全匹配(素材 × 目标)」会把每张素材图分别与每张目标图组合。例如 10 张素材图和 10 张目标图会展开为 100 个请求。每个请求只携带当前素材图和当前目标图,不会把 20 张图片一起发送给模型。 - 「每张素材×每张目标」会把每张素材图分别与每张目标图组合。例如 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` 关闭,多图使用左右按钮或方向键切换。缩略图悬停时不显示额外文字标签。批量界面不显示额外的“描述示例”板块。 上传后,每张缩略图左下角显示它在实际模型请求中的图号,例如「图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 的「蒙版」参数。 每张参考图、素材图和目标图的右下角都有「替换」按钮:选择一张本地图片后,新图会留在原位置,其他图片和顺序不变;验证或上传失败时保留旧图。左上角的编辑按钮继续用于裁剪和标记。点击后可按「自由 / 原图 / 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 只在服务端读取,不会传给浏览器或写入工作流。 提示词框右下角提供“魔法棒图标 + 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 保存,但不会附带工作流。 本地「格式」只在 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 或图像连线。 旧工作流加载时,会把保存节点原有的「文件名前缀 / 格式 / 保存位置 / 命名规则」迁移到相连的「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`。 `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 时使用开始、结束时间自由裁剪。 「视频裁剪」只需点击节点内的「上传视频」选择文件,也可连接上游 `VIDEO`;上传后的内部文件路径会随工作流保存,但不显示为用户参数。视频加载后可直接预览并拖动时间轴。固定时长大于 0 时,绿色选区会保持该长度并可整体拖动;固定时长为 0 时使用开始、结束时间自由裁剪。
+6 -1
View File
@@ -72,7 +72,7 @@ if not getattr(asyncio, "_o1key_new_event_loop_patched", False):
asyncio._o1key_new_event_loop_patched = True 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 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 O1keySavePSD
from .nodes import O1keyRemoveBackground from .nodes import O1keyRemoveBackground
from .nodes import O1keyGridSplitter from .nodes import O1keyGridSplitter
@@ -85,6 +85,7 @@ from .nodes import O1keyAutoRedCast
from .nodes import O1keyImageGenerator, O1keyImageSave from .nodes import O1keyImageGenerator, O1keyImageSave
from .nodes import O1keyVideoGenerator, O1keyVideoResult from .nodes import O1keyVideoGenerator, O1keyVideoResult
from .nodes import O1keyOmniFlashVideo from .nodes import O1keyOmniFlashVideo
from .nodes import O1keyMJImage
# 报错弹框友好文案(不修改原节点代码,仅在外层统一处理) # 报错弹框友好文案(不修改原节点代码,仅在外层统一处理)
_MSG_TIMEOUT = "API 请求超时,请稍后重试或检查网络。" _MSG_TIMEOUT = "API 请求超时,请稍后重试或检查网络。"
@@ -148,6 +149,7 @@ NODE_CLASS_MAPPINGS = {
"K3Video": K3Video, "K3Video": K3Video,
"K3MotionControl": K3MotionControl, "K3MotionControl": K3MotionControl,
"SaveImageFormat": SaveImageFormat, "SaveImageFormat": SaveImageFormat,
"O1keySaveGIF": O1keySaveGIF,
"O1keySavePSD": O1keySavePSD, "O1keySavePSD": O1keySavePSD,
"O1keyRemoveBackground": O1keyRemoveBackground, "O1keyRemoveBackground": O1keyRemoveBackground,
"O1keyGridSplitter": O1keyGridSplitter, "O1keyGridSplitter": O1keyGridSplitter,
@@ -162,12 +164,14 @@ NODE_CLASS_MAPPINGS = {
"O1keyVideoGenerator": O1keyVideoGenerator, "O1keyVideoGenerator": O1keyVideoGenerator,
"O1keyVideoResult": O1keyVideoResult, "O1keyVideoResult": O1keyVideoResult,
"O1keyOmniFlashVideo": O1keyOmniFlashVideo, "O1keyOmniFlashVideo": O1keyOmniFlashVideo,
"O1keyMJImage": O1keyMJImage,
} }
NODE_DISPLAY_NAME_MAPPINGS = { NODE_DISPLAY_NAME_MAPPINGS = {
"O1keyVideoGenerator": "o1key 视频生成", "O1keyVideoGenerator": "o1key 视频生成",
"O1keyVideoResult": "o1key 视频结果", "O1keyVideoResult": "o1key 视频结果",
"O1keyOmniFlashVideo": "Omni Flash 视频生成", "O1keyOmniFlashVideo": "Omni Flash 视频生成",
"O1keyMJImage": "o1key MJ图片生成",
"NanoBanana": "Nano Banana", "NanoBanana": "Nano Banana",
"BatchNanoBananaPro": "Nano Banana 批量跑图", "BatchNanoBananaPro": "Nano Banana 批量跑图",
"GoogleGemini": "Google Gemini", "GoogleGemini": "Google Gemini",
@@ -195,6 +199,7 @@ NODE_DISPLAY_NAME_MAPPINGS = {
"K3Video": "K 视频生成", "K3Video": "K 视频生成",
"K3MotionControl": "K 动作模仿", "K3MotionControl": "K 动作模仿",
"SaveImageFormat": "保存图像(格式转换)", "SaveImageFormat": "保存图像(格式转换)",
"O1keySaveGIF": "保存 GIF",
"O1keySavePSD": "保存 PSD(分层)", "O1keySavePSD": "保存 PSD(分层)",
"O1keyRemoveBackground": "去背景(rembg)", "O1keyRemoveBackground": "去背景(rembg)",
"O1keyGridSplitter": "合并图智能切割", "O1keyGridSplitter": "合并图智能切割",
+112 -32
View File
@@ -42,9 +42,14 @@ from ..utils.http2_client import (
from ..utils.o1key_image_catalog import ( from ..utils.o1key_image_catalog import (
GPT_IMAGE_BACKGROUND_OPTIONS, GPT_IMAGE_BACKGROUND_OPTIONS,
GPT_IMAGE_MODEL_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, UNIFIED_IMAGE_ROUTE_OPTIONS,
) )
from ..utils.gpt_image_media import materialize_result_images
try: try:
from comfy.model_management import processing_interrupted, InterruptProcessingException from comfy.model_management import processing_interrupted, InterruptProcessingException
@@ -63,15 +68,21 @@ _ENDPOINT_ASYNC_TASK = "/async/v1/tasks/{task_id}"
# ── 主模型与模型线路映射(界面值 → API 模型名)────────────────────────────── # ── 主模型与模型线路映射(界面值 → API 模型名)──────────────────────────────
GPT_IMAGE_ROUTE_OPTIONS = UNIFIED_IMAGE_ROUTE_OPTIONS GPT_IMAGE_ROUTE_OPTIONS = UNIFIED_IMAGE_ROUTE_OPTIONS
GPT_IMAGE_MODEL_MATRIX = { GPT_IMAGE_MODEL_MATRIX = {
("gpt-image-2", "畅速"): "gpt-image-2-c-sp", ("gpt-image-2.6-sunburst", "畅速"): "gpt-image-2.6-sunburst-sp",
("gpt-image-2", "直连"): "gpt-image-2-c-sd", ("gpt-image-2.6-sunburst", "直连"): "gpt-image-2.6-sunburst-sd",
("gpt-image-2", "专线"): "gpt-image-2", ("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-sp",
("gpt-image-2.5-sunburst", "直连"): "gpt-image-2.5-sunburst-sd", ("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-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-sp",
("gpt-image-2.5-flare", "直连"): "gpt-image-2.5-flare-sd", ("gpt-image-2.5-flare", "直连"): "gpt-image-2.5-flare-sd",
("gpt-image-2.5-flare", "专线"): "gpt-image-2.5-flare", ("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 = { _MODEL_NAME_MAP = {
"畅速": "gpt-image-2-c-sp", "畅速": "gpt-image-2-c-sp",
@@ -246,13 +257,15 @@ class GptImageClient:
session: aiohttp.ClientSession, session: aiohttp.ClientSession,
url: str, url: str,
label: str, label: str,
) -> tuple[Image.Image, int, float]: requested_format: Optional[str] = None,
"""Download and fully decode an image, retrying interrupted GET reads.""" ) -> tuple[list[Image.Image], int, float]:
"""Download and fully decode result bytes, retrying interrupted GET reads."""
download_started = time.perf_counter() download_started = time.perf_counter()
for attempt in range(_RESPONSE_READ_MAX_RETRIES + 1): for attempt in range(_RESPONSE_READ_MAX_RETRIES + 1):
try: try:
async with session.get(url, allow_redirects=True) as resp: async with session.get(url, allow_redirects=True) as resp:
image_bytes, diagnostics = await read_response_body_with_diagnostics(resp) image_bytes, diagnostics = await read_response_body_with_diagnostics(resp)
content_type = str(resp.headers.get("Content-Type") or "")
if resp.status != 200: if resp.status != 200:
print( print(
f"[o1key GPT Image] 结果下载传输追踪" f"[o1key GPT Image] 结果下载传输追踪"
@@ -263,10 +276,12 @@ class GptImageClient:
raise _RetryableResultHTTPError(message) raise _RetryableResultHTTPError(message)
raise RuntimeError(message) raise RuntimeError(message)
image = Image.open(BytesIO(image_bytes)) images = materialize_result_images(
image.load() image_bytes,
_attach_original_image_info(image, image_bytes) requested_format=requested_format,
return image, len(image_bytes), time.perf_counter() - download_started content_type=content_type,
)
return images, len(image_bytes), time.perf_counter() - download_started
except ( except (
aiohttp.ClientError, aiohttp.ClientError,
asyncio.TimeoutError, asyncio.TimeoutError,
@@ -807,19 +822,26 @@ class GptImageClient:
raise RuntimeError(f"{label} base64 解码失败: {e}") from None raise RuntimeError(f"{label} base64 解码失败: {e}") from None
@staticmethod @staticmethod
def _decode_inline_result_image(b64: str, label: str) -> tuple[Image.Image, int]: def _decode_inline_result_image(
"""Strictly decode and fully load a completed task's inline 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: try:
if not isinstance(b64, str) or not b64: if not isinstance(b64, str) or not b64:
raise ValueError("empty base64 payload") raise ValueError("empty base64 payload")
image_bytes = base64.b64decode(b64, validate=True) image_bytes = base64.b64decode(b64, validate=True)
if not image_bytes: if not image_bytes:
raise ValueError("decoded image is empty") raise ValueError("decoded image is empty")
image = Image.open(BytesIO(image_bytes)) images = materialize_result_images(
image.load() image_bytes,
_attach_original_image_info(image, image_bytes) requested_format=requested_format,
return image, len(image_bytes) )
except (binascii.Error, ValueError, OSError, UnidentifiedImageError) as exc: 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 raise _IncompleteInlineImageError(f"{label}不完整或无法解码: {exc}") from None
async def _append_images_from_payload( async def _append_images_from_payload(
@@ -1064,21 +1086,37 @@ class GptImageClient:
background: str = "auto", background: str = "auto",
moderation: Optional[str] = None, moderation: Optional[str] = None,
resize_mode: Optional[str] = None, resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> dict: ) -> dict:
if int(n) != 1: if int(n) != 1:
raise ValueError("GPT Image 单次请求的 n 必须为 1;多图请使用外层并发") raise ValueError("GPT Image 单次请求的 n 必须为 1;多图请使用外层并发")
output_format = str(output_format or "png").strip().lower()
background = str(background or "auto").strip().lower() background = str(background or "auto").strip().lower()
moderation = str(moderation).strip().lower() if moderation is not None else None 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: if background not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效") raise ValueError("GPT Image 背景参数无效")
if moderation not in {None, "low"}: if moderation not in {None, "low"}:
raise ValueError("GPT Image 内容审查强度无效") 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) 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]] = [] assets: List[Dict[str, Any]] = []
image_keys: List[str] = [] image_keys: List[str] = []
mask_key = None mask_key = None
@@ -1133,6 +1171,12 @@ class GptImageClient:
body["mask"] = { body["mask"] = {
"image_url": self._png_bytes_to_data_url(asset_bytes[mask_key]) "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": if moderation == "low":
body["moderation"] = "low" body["moderation"] = "low"
return body return body
@@ -1273,6 +1317,7 @@ class GptImageClient:
result_url_callback: Optional[Callable[[str], None]] = None, result_url_callback: Optional[Callable[[str], None]] = None,
log_downloads: bool = True, log_downloads: bool = True,
log_prefix: str = "[o1key GPT Image]", log_prefix: str = "[o1key GPT Image]",
requested_format: Optional[str] = None,
) -> List[Image.Image]: ) -> List[Image.Image]:
data = task.get("data", {}) data = task.get("data", {})
image_items = data.get("images") if isinstance(data, dict) else None image_items = data.get("images") if isinstance(data, dict) else None
@@ -1297,42 +1342,47 @@ class GptImageClient:
f"第 {idx} 张内联 data URL 缺少有效 Base64 头" f"第 {idx} 张内联 data URL 缺少有效 Base64 头"
) )
started = time.perf_counter() started = time.perf_counter()
img, byte_count = self._decode_inline_result_image( decoded, byte_count = self._decode_inline_result_image(
b64_data, b64_data,
f"第 {idx} 张内联 data URL 图片", f"第 {idx} 张内联 data URL 图片",
requested_format=requested_format,
) )
images.append(img) images.extend(decoded)
if log_downloads: if log_downloads:
first = decoded[0]
print( print(
f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 data URL,无网络下载 | " 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" f"解码={time.perf_counter() - started:.2f}s"
) )
elif url and isinstance(url, str) and url.startswith("http"): elif url and isinstance(url, str) and url.startswith("http"):
if log_downloads: if log_downloads:
print(f"{log_prefix} 下载图像 {idx}/{len(image_items)} 开始") print(f"{log_prefix} 下载图像 {idx}/{len(image_items)} 开始")
img, byte_count, elapsed = await self._download_image_with_response_retry( downloaded, byte_count, elapsed = await self._download_image_with_response_retry(
session, url, f"第 {idx} 张图片" session, url, f"第 {idx} 张图片", requested_format=requested_format,
) )
images.append(img) images.extend(downloaded)
result_urls.append(url) result_urls.append(url)
if log_downloads: if log_downloads:
first = downloaded[0]
print( print(
f"{log_prefix} 下载图像 {idx}/{len(image_items)} 完成 | " 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)}" f"{elapsed:.2f}s | {self._format_transfer_rate(byte_count, elapsed)}"
) )
elif b64: elif b64:
started = time.perf_counter() started = time.perf_counter()
img, byte_count = self._decode_inline_result_image( decoded, byte_count = self._decode_inline_result_image(
b64, b64,
f"第 {idx} 张内联 Base64 图片", f"第 {idx} 张内联 Base64 图片",
requested_format=requested_format,
) )
images.append(img) images.extend(decoded)
if log_downloads: if log_downloads:
first = decoded[0]
print( print(
f"{log_prefix} 结果图像 {idx}/{len(image_items)} 内联 base64,无网络下载 | " 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" f"解码={time.perf_counter() - started:.2f}s"
) )
else: else:
@@ -1366,6 +1416,7 @@ class GptImageClient:
result_url_callback: Optional[Callable[[str], None]] = None, result_url_callback: Optional[Callable[[str], None]] = None,
log_downloads: bool = True, log_downloads: bool = True,
log_prefix: str = "[o1key GPT Image]", log_prefix: str = "[o1key GPT Image]",
requested_format: Optional[str] = None,
) -> tuple[dict, List[Image.Image]]: ) -> tuple[dict, List[Image.Image]]:
"""Re-fetch a completed task when its inline image is incomplete.""" """Re-fetch a completed task when its inline image is incomplete."""
current_task = task current_task = task
@@ -1377,6 +1428,7 @@ class GptImageClient:
result_url_callback=result_url_callback, result_url_callback=result_url_callback,
log_downloads=log_downloads, log_downloads=log_downloads,
log_prefix=log_prefix, log_prefix=log_prefix,
requested_format=requested_format,
) )
return current_task, images return current_task, images
except _IncompleteInlineImageError as exc: except _IncompleteInlineImageError as exc:
@@ -1422,6 +1474,9 @@ class GptImageClient:
log_request_start: bool = True, log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None, resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]: ) -> List[Image.Image]:
body = self._build_async_generate_body( body = self._build_async_generate_body(
prompt=prompt, prompt=prompt,
@@ -1435,6 +1490,9 @@ class GptImageClient:
background=background, background=background,
moderation=moderation, moderation=moderation,
resize_mode=resize_mode, 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 "文生图") mode = "图像编辑" if mask_tensor is not None else ("图生图" if image_tensor else "文生图")
@@ -1470,6 +1528,7 @@ class GptImageClient:
result_url_callback=_on_result_url, result_url_callback=_on_result_url,
log_downloads=log_downloads, log_downloads=log_downloads,
log_prefix=log_prefix, log_prefix=log_prefix,
requested_format=output_format,
) )
if task_completed_callback: if task_completed_callback:
task_completed_callback(task_id, len(images), time.time() - task_started, upstream_urls) task_completed_callback(task_id, len(images), time.time() - task_started, upstream_urls)
@@ -1496,6 +1555,9 @@ class GptImageClient:
log_request_start: bool = True, log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None, resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]: ) -> List[Image.Image]:
"""多图生成:并发提交 n 个单图任务,每个请求固定传 n=1。""" """多图生成:并发提交 n 个单图任务,每个请求固定传 n=1。"""
request_count = max(1, int(n)) request_count = max(1, int(n))
@@ -1540,6 +1602,9 @@ class GptImageClient:
log_request_start=log_request_start, log_request_start=log_request_start,
task_completed_callback=task_completed_callback, task_completed_callback=task_completed_callback,
resize_mode=resize_mode, resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
) )
) )
for task_index in range(request_count) for task_index in range(request_count)
@@ -1870,6 +1935,9 @@ class GptImageClient:
log_request_start: bool = True, log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None, resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]: ) -> List[Image.Image]:
"""异步公共入口;多图始终拆成并发的 n=1 单图请求。""" """异步公共入口;多图始终拆成并发的 n=1 单图请求。"""
requested_n = max(1, int(n)) requested_n = max(1, int(n))
@@ -1894,6 +1962,9 @@ class GptImageClient:
log_request_start=log_request_start, log_request_start=log_request_start,
task_completed_callback=task_completed_callback, task_completed_callback=task_completed_callback,
resize_mode=resize_mode, resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
) )
return await self._generate_image_task_async( return await self._generate_image_task_async(
prompt=prompt, prompt=prompt,
@@ -1915,6 +1986,9 @@ class GptImageClient:
log_request_start=log_request_start, log_request_start=log_request_start,
task_completed_callback=task_completed_callback, task_completed_callback=task_completed_callback,
resize_mode=resize_mode, resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
) )
def generate_image_async_sync( def generate_image_async_sync(
@@ -1939,6 +2013,9 @@ class GptImageClient:
log_request_start: bool = True, log_request_start: bool = True,
task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None, task_completed_callback: Optional[Callable[[str, int, float, List[str]], None]] = None,
resize_mode: Optional[str] = None, resize_mode: Optional[str] = None,
complexity: Optional[str] = None,
frame_count=None,
frame_duration_ms=None,
) -> List[Image.Image]: ) -> List[Image.Image]:
""" """
新版异步任务入口,供节点调用。 新版异步任务入口,供节点调用。
@@ -1965,6 +2042,9 @@ class GptImageClient:
log_request_start=log_request_start, log_request_start=log_request_start,
task_completed_callback=task_completed_callback, task_completed_callback=task_completed_callback,
resize_mode=resize_mode, resize_mode=resize_mode,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
) )
def _run(): def _run():
+144
View File
@@ -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)]
+361
View File
@@ -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",
]
+18 -3
View File
@@ -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 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). `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 ### Shared utilities
`utils/` contains cross-provider infrastructure: `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 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. 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. 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. 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. - 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 preserve the selected background and output format; transparent backgrounds are limited to PNG and WebP.
- Unified GPT Image requests omit the retired moderation parameter. - 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 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. - 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 `专线`. - Route-label changes never alter the serialized values `畅速`, `直连`, and `专线`.
@@ -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.
@@ -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.
+2
View File
@@ -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) - [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) - [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) - [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)
+10 -5
View File
@@ -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. - 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 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. 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. 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. 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. 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. 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. 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 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`. 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`.
+217 -1
View File
@@ -25,6 +25,10 @@ import aiohttp
from comfy_api.latest import io 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.config import get_api_key_or_raise, get_base_url_by_route
from ..utils.image_utils import tensor_to_pil from ..utils.image_utils import tensor_to_pil
from ..utils.r2_uploader import upload_image 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_MAX_FPS = 60.0
_REFERENCE_VIDEO_MIN_RATIO = 1 / 2.5 _REFERENCE_VIDEO_MIN_RATIO = 1 / 2.5
_REFERENCE_VIDEO_MAX_RATIO = 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: def _collect_shots(分镜模式: dict, 时长: int) -> list:
"""从 DynamicCombo 的 dict 收集分镜参数并校验。 """从 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(): def _build_model_input():
"""构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。 """构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。
@@ -637,8 +702,11 @@ def _build_model_input():
io.DynamicCombo.Option("v3-omni", _v3_omni_subs()), io.DynamicCombo.Option("v3-omni", _v3_omni_subs()),
io.DynamicCombo.Option("v2-6", _v26_subs()), io.DynamicCombo.Option("v2-6", _v26_subs()),
io.DynamicCombo.Option("v3", _v3_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 仅控制节点是否重新运行,结果本身不可复现。"), tooltip="seed 仅控制节点是否重新运行,结果本身不可复现。"),
# 负向提示词置于最下方(全局生效,两种模式都可用) # 负向提示词置于最下方(全局生效,两种模式都可用)
io.String.Input("负向提示词", multiline=True, default=""), 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="视频")], outputs=[io.Video.Output(display_name="视频")],
accept_all_inputs=True, accept_all_inputs=True,
@@ -730,6 +820,49 @@ class K3Video(io.ComfyNode):
"Content-Type": "application/json", "Content-Type": "application/json",
} }
shots = _collect_shots(分镜模式, 时长) 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,故隐藏。 # 正向提示词仅在「禁用」(单段)时存在;选故事板后腾讯忽略主 Prompt,故隐藏。
提示词 = (分镜模式.get("正向提示词") or "") if not shots else "" 提示词 = (分镜模式.get("正向提示词") or "") if not shots else ""
@@ -1028,6 +1161,89 @@ class K3Video(io.ComfyNode):
) )
# ── 标准 image2video 端点(v3 / v2-6)──────────────────────── # ── 标准 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 @classmethod
async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None): async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None):
"""标准图生视频接口:POST /kling/v1/videos/image2video """标准图生视频接口:POST /kling/v1/videos/image2video
+3 -1
View File
@@ -28,6 +28,7 @@ from .grok_video import O1keyGrokVideo, O1keyGrokVideoEdit
from .K3_video import K3Video from .K3_video import K3Video
from .K3_motion_control import K3MotionControl from .K3_motion_control import K3MotionControl
from .save_image_format import SaveImageFormat from .save_image_format import SaveImageFormat
from .save_gif import O1keySaveGIF
from .save_psd import O1keySavePSD from .save_psd import O1keySavePSD
from .remove_bg import O1keyRemoveBackground from .remove_bg import O1keyRemoveBackground
from .grid_splitter import O1keyGridSplitter from .grid_splitter import O1keyGridSplitter
@@ -40,5 +41,6 @@ from .seedance_autopass_batch import SeedanceAutoPassBatch
from .o1key_image_generator import O1keyImageGenerator, O1keyImageSave from .o1key_image_generator import O1keyImageGenerator, O1keyImageSave
from .o1key_video_generator import O1keyVideoGenerator, O1keyVideoResult from .o1key_video_generator import O1keyVideoGenerator, O1keyVideoResult
from .omni_flash_video import O1keyOmniFlashVideo 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']
+113 -14
View File
@@ -1,6 +1,6 @@
""" """
o1key GPT Image 节点 o1key GPT Image 节点
支持 GPT Image 2 / 2.5 系列的文生图、图生图和带蒙版图像编辑 支持 GPT Image 2 / 2.5 / 2.6 系列的文生图、图生图和带蒙版图像编辑
""" """
import os 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.config import get_base_url_by_route
from ..utils.o1key_image_catalog import ( from ..utils.o1key_image_catalog import (
GPT_IMAGE_BACKGROUND_OPTIONS, 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_EXACT_SIZE_OPTIONS,
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
GPT_IMAGE_25_QUALITY_OPTIONS, GPT_IMAGE_25_QUALITY_OPTIONS,
resolve_gpt_image_quality, resolve_gpt_image_quality,
resolve_gpt_image_size, 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 ( from ..utils.file_utils import (
ImageInfo, ImageInfo,
generate_timestamp_filename, generate_timestamp_filename,
@@ -142,13 +159,17 @@ class O1keyGPTImage(io.ComfyNode):
io.Combo.Input( io.Combo.Input(
"模型", "模型",
options=GPT_IMAGE_MODEL_OPTIONS, options=GPT_IMAGE_MODEL_OPTIONS,
default="gpt-image-2.5-sunburst", default="gpt-image-2.6-sunburst",
), ),
io.Combo.Input( io.Combo.Input(
"模型线路", "模型线路",
options=GPT_IMAGE_ROUTE_OPTIONS, options=GPT_IMAGE_ROUTE_OPTIONS,
default="畅速", default="畅速",
), ),
io.Combo.Input(
"复杂度", options=GPT_IMAGE_COMPLEXITY_OPTIONS, default="高",
tooltip="仅 GPT Image 2.6 生效:低 / 中 / 高;越高规划越充分、耗时越长。",
),
io.Combo.Input( io.Combo.Input(
"分辨率", "分辨率",
options=GPT_IMAGE_EXACT_SIZE_OPTIONS, options=GPT_IMAGE_EXACT_SIZE_OPTIONS,
@@ -168,13 +189,13 @@ class O1keyGPTImage(io.ComfyNode):
"质量", "质量",
options=GPT_IMAGE_25_QUALITY_OPTIONS, options=GPT_IMAGE_25_QUALITY_OPTIONS,
default="自动", 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( io.Combo.Input(
"输出格式", "输出格式",
options=["png", "jpeg", "webp"], options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
default="png", default="png",
tooltip="Generated image output format", tooltip="2.6 另支持 svg / gif;svg/gif 仅纯文生图可用。",
), ),
io.Combo.Input( io.Combo.Input(
"背景", "背景",
@@ -204,8 +225,29 @@ class O1keyGPTImage(io.ComfyNode):
control_after_generate=io.ControlAfterGenerate.randomize, control_after_generate=io.ControlAfterGenerate.randomize,
tooltip="Random seed (0 = not specified)", 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端口。 # 兼容 Autogrow 改造前保存的参考图1~参考图9端口。
accept_all_inputs=True, accept_all_inputs=True,
) )
@@ -214,7 +256,7 @@ class O1keyGPTImage(io.ComfyNode):
def execute( def execute(
cls, cls,
prompt: str, prompt: str,
模型: str = "gpt-image-2.5-sunburst", 模型: str = "gpt-image-2.6-sunburst",
模型线路: str = "畅速", 模型线路: str = "畅速",
分辨率: str = "智能", 分辨率: str = "智能",
质量: str = "自动", 质量: str = "自动",
@@ -224,6 +266,9 @@ class O1keyGPTImage(io.ComfyNode):
遮罩=None, 遮罩=None,
缩放图片: str = "智能缩放", 缩放图片: str = "智能缩放",
背景: str = "auto", 背景: str = "auto",
复杂度: str = "高",
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
**kwargs, **kwargs,
) -> io.NodeOutput: ) -> io.NodeOutput:
result = cls.generate( result = cls.generate(
@@ -238,15 +283,21 @@ class O1keyGPTImage(io.ComfyNode):
遮罩=遮罩, 遮罩=遮罩,
缩放图片=缩放图片, 缩放图片=缩放图片,
背景=背景, 背景=背景,
复杂度=复杂度,
帧数=帧数,
帧时长ms=帧时长ms,
**kwargs, **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 @classmethod
def generate( def generate(
cls, cls,
prompt: str, prompt: str,
模型: str = "gpt-image-2.5-sunburst", 模型: str = "gpt-image-2.6-sunburst",
模型线路: str = "畅速", 模型线路: str = "畅速",
分辨率: str = "智能", 分辨率: str = "智能",
质量: str = "自动", 质量: str = "自动",
@@ -256,6 +307,9 @@ class O1keyGPTImage(io.ComfyNode):
遮罩=None, 遮罩=None,
缩放图片: str = "智能缩放", 缩放图片: str = "智能缩放",
背景: str = "auto", 背景: str = "auto",
复杂度: str = "高",
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
**kwargs, **kwargs,
): ):
""" """
@@ -285,12 +339,19 @@ class O1keyGPTImage(io.ComfyNode):
raise ValueError("提供了遮罩但未提供图片,请同时提供图片和遮罩") raise ValueError("提供了遮罩但未提供图片,请同时提供图片和遮罩")
if 缩放图片 not in {"不缩放", "智能缩放"}: if 缩放图片 not in {"不缩放", "智能缩放"}:
raise ValueError("缩放图片参数无效") raise ValueError("缩放图片参数无效")
if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS:
raise ValueError("GPT Image 输出格式无效")
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效") 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 输出格式") 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 参数值 ────────────────────────────────── # ── 2. 解析分辨率显示值 → API 参数值 ──────────────────────────────────
size = _resolve_async_size(分辨率) size = _resolve_async_size(分辨率)
@@ -300,6 +361,7 @@ class O1keyGPTImage(io.ComfyNode):
# ── 2c. 解析质量显示值 → API 参数值 ─────────────────────────────────── # ── 2c. 解析质量显示值 → API 参数值 ───────────────────────────────────
quality = resolve_gpt_image_quality(模型, 质量) quality = resolve_gpt_image_quality(模型, 质量)
complexity = resolve_gpt_image_complexity(模型, 复杂度)
# ── 3. 创建客户端 ───────────────────────────────────────────────────── # ── 3. 创建客户端 ─────────────────────────────────────────────────────
try: try:
@@ -348,6 +410,9 @@ class O1keyGPTImage(io.ComfyNode):
mask_tensor=遮罩, mask_tensor=遮罩,
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 {}),
progress_callback=_make_node_progress_callback(progress_bar, idx, total), progress_callback=_make_node_progress_callback(progress_bar, idx, total),
special_price_parallel=True, special_price_parallel=True,
task_submitted_callback=_submitted, task_submitted_callback=_submitted,
@@ -381,6 +446,9 @@ class O1keyGPTImage(io.ComfyNode):
mask_tensor=遮罩, mask_tensor=遮罩,
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 {}),
progress_callback=_make_node_progress_callback(progress_bar, 1, 1), progress_callback=_make_node_progress_callback(progress_bar, 1, 1),
special_price_parallel=True, special_price_parallel=True,
task_submitted_callback=_submitted, task_submitted_callback=_submitted,
@@ -402,6 +470,37 @@ class O1keyGPTImage(io.ComfyNode):
raise RuntimeError("所有提示词均生成失败,无可用图像输出") raise RuntimeError("所有提示词均生成失败,无可用图像输出")
# ── 7. PIL → tensor ─────────────────────────────────────────────── # ── 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) output_tensor = GptImageClient._pil_list_to_tensor(all_pil_images)
# ── 8. 完成日志 ─────────────────────────────────────────────────── # ── 8. 完成日志 ───────────────────────────────────────────────────
@@ -412,7 +511,7 @@ class O1keyGPTImage(io.ComfyNode):
f"{output_tensor.shape[2]}×{output_tensor.shape[1]}" f"{output_tensor.shape[2]}×{output_tensor.shape[1]}"
) )
return (output_tensor,) return (output_tensor, file_path, preview)
finally: finally:
cls._print_balance(client) cls._print_balance(client)
+88 -14
View File
@@ -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.image_utils import parse_batch_prompts, pil_to_tensor, tensor_to_pil
from ..utils.o1key_image_catalog import ( from ..utils.o1key_image_catalog import (
GPT_IMAGE_BACKGROUND_OPTIONS, 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, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
) )
from ..utils.gpt_image_media import animation_bytes_from_images, svg_bytes_from_image, write_bytes_atomic
try: try:
from comfy.model_management import InterruptProcessingException from comfy.model_management import InterruptProcessingException
@@ -134,14 +148,18 @@ class O1keyGPTImageBatch(io.ComfyNode):
tooltip="可用独占一行的 --- 分隔多条提示词。"), tooltip="可用独占一行的 --- 分隔多条提示词。"),
io.Combo.Input( io.Combo.Input(
"模型", options=GPT_IMAGE_MODEL_OPTIONS, "模型", 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_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.Combo.Input("分辨率", options=_RESOLUTION_OPTIONS, default="智能"),
io.Int.Input("生图数量", default=1, min=1, max=8, step=1), io.Int.Input("生图数量", default=1, min=1, max=8, step=1),
io.Combo.Input( io.Combo.Input(
"质量", options=GPT_IMAGE_25_QUALITY_OPTIONS, default="自动", "质量", 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( io.DynamicCombo.Input(
"图片路径数量", "图片路径数量",
@@ -151,7 +169,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
io.Mask.Input("遮罩", optional=True, io.Mask.Input("遮罩", optional=True,
tooltip="应用到每个任务的第一张参考图。"), tooltip="应用到每个任务的第一张参考图。"),
references, references,
io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP"], io.Combo.Input("图片输出格式", options=["原始", "JPEG", "PNG", "WebP", "SVG", "GIF"],
default="原始"), default="原始"),
io.Combo.Input( io.Combo.Input(
"背景", "背景",
@@ -173,6 +191,24 @@ class O1keyGPTImageBatch(io.ComfyNode):
"seed", default=0, min=0, max=2**31 - 1, step=1, "seed", default=0, min=0, max=2**31 - 1, step=1,
control_after_generate=io.ControlAfterGenerate.randomize, 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="输出图像")], outputs=[io.Image.Output(display_name="输出图像")],
accept_all_inputs=True, accept_all_inputs=True,
@@ -238,13 +274,33 @@ class O1keyGPTImageBatch(io.ComfyNode):
naming_rule: str, task_index: int, base_filename: Optional[str], naming_rule: str, task_index: int, base_filename: Optional[str],
) -> List[str]: ) -> List[str]:
saved = [] 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): for image_index, image in enumerate(images, 1):
if image_format == "原始": if image_format == "原始":
fmt = str(getattr(image, "format", None) or "PNG").upper() fmt = str(getattr(image, "format", None) or "PNG").upper()
fmt = "JPEG" if fmt in ("JPG", "JPEG") else "WEBP" if fmt == "WEBP" else "PNG" fmt = "JPEG" if fmt in ("JPG", "JPEG") else "WEBP" if fmt == "WEBP" else "PNG"
else: else:
fmt = image_format.upper() 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 == "自然数字": if naming_rule == "自然数字":
stem = str(task_index + 1) stem = str(task_index + 1)
if image_index > 1: if image_index > 1:
@@ -284,7 +340,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
cls, client, pair, task_prompt, task_index, total_tasks, cls, client, pair, task_prompt, task_index, total_tasks,
model, quality, size, image_count, seed, mask, output_format, model, quality, size, image_count, seed, mask, output_format,
background, resize_mode, 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: ) -> dict:
try: try:
task_started = time.time() task_started = time.time()
@@ -294,6 +351,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
image_tensor=[pil_to_tensor([item.image]) for item in pair], image_tensor=[pil_to_tensor([item.image]) for item in pair],
mask_tensor=mask, output_format=output_format, mask_tensor=mask, output_format=output_format,
background=background, background=background,
**({"complexity": complexity} if complexity is not None else {}),
progress_callback=progress_callback, progress_callback=progress_callback,
special_price_parallel=True, special_price_parallel=True,
log_downloads=True, log_downloads=True,
@@ -328,7 +386,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
async def _process_async( async def _process_async(
cls, client, task_defs, model, quality, size, image_count, seed, cls, client, task_defs, model, quality, size, image_count, seed,
mask, output_format, background, resize_mode, 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]: ) -> List[dict]:
total = len(task_defs) total = len(task_defs)
progress_values = [0] * total progress_values = [0] * total
@@ -338,7 +397,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
client, pair, prompt, index, total, model, quality, size, client, pair, prompt, index, total, model, quality, size,
image_count, seed, mask, output_format, background, image_count, seed, mask, output_format, background,
resize_mode, folder, naming_rule, 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 for index, pair, prompt in task_defs
] ]
@@ -357,10 +417,11 @@ class O1keyGPTImageBatch(io.ComfyNode):
@classmethod @classmethod
def execute( def execute(
cls, prompt, 模型="gpt-image-2.5-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1, cls, prompt, 模型="gpt-image-2.6-sunburst", 模型线路="畅速", 分辨率="智能", 生图数量=1,
质量="自动", 图片路径数量=None, 遮罩=None, seed=0, 质量="自动", 图片路径数量=None, 遮罩=None, seed=0,
图片输出格式="原始", 图片保存命名规则="和原始图片名保持一致", 图片输出格式="原始", 图片保存命名规则="和原始图片名保持一致",
图片保存路径="", 缩放图片="智能缩放", 背景="auto", **kwargs, 图片保存路径="", 缩放图片="智能缩放", 背景="auto", 复杂度="高",
帧数=GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT, 帧时长ms=GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT, **kwargs,
) -> io.NodeOutput: ) -> io.NodeOutput:
if not prompt or not str(prompt).strip(): if not prompt or not str(prompt).strip():
raise ValueError("提示词不能为空") raise ValueError("提示词不能为空")
@@ -369,6 +430,7 @@ class O1keyGPTImageBatch(io.ComfyNode):
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效") raise ValueError("GPT Image 背景参数无效")
complexity = resolve_gpt_image_complexity(模型, 复杂度)
actual_model = resolve_gpt_image_model(模型, 模型线路) actual_model = resolve_gpt_image_model(模型, 模型线路)
# 兼容旧节点通过命名参数调用时使用的字段名。 # 兼容旧节点通过命名参数调用时使用的字段名。
@@ -419,11 +481,22 @@ class O1keyGPTImageBatch(io.ComfyNode):
folder = cls._output_folder(图片保存路径) folder = cls._output_folder(图片保存路径)
quality = resolve_gpt_image_quality(模型, 质量) quality = resolve_gpt_image_quality(模型, 质量)
output_format = {"原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp"}.get(图片输出格式, "png") output_format = {
if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: "原始": "png", "JPEG": "jpeg", "PNG": "png", "WebP": "webp",
raise ValueError("GPT Image 输出格式无效") "SVG": "svg", "GIF": "gif",
if 背景 == "transparent" and output_format == "jpeg": "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 输出格式") 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 = GptImageClient()
client.base_url = get_base_url_by_route() client.base_url = get_base_url_by_route()
client.response_log_enabled = False client.response_log_enabled = False
@@ -443,7 +516,8 @@ class O1keyGPTImageBatch(io.ComfyNode):
client, task_defs, actual_model, quality, _resolve_size(分辨率), client, task_defs, actual_model, quality, _resolve_size(分辨率),
生图数量, seed, 遮罩, output_format, 背景, 生图数量, seed, 遮罩, output_format, 背景,
缩放图片, folder, 缩放图片, folder,
图片保存命名规则, pbar, 图片保存命名规则, pbar, complexity,
frame_count, frame_duration_ms,
) )
return loop.run_until_complete(client._run_with_interrupt(coro)) return loop.run_until_complete(client._run_with_interrupt(coro))
finally: finally:
+402
View File
@@ -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"]
+99 -32
View File
@@ -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.config import get_api_key_or_raise, get_base_url_by_route
from ..utils.http2_client import create_http_client from ..utils.http2_client import create_http_client
from ..utils.image_utils import ( from ..utils.image_utils import (
IMAGE_BATCH_MODE_ALIASES,
IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_GROUP_TO_MODELS,
IMAGE_BATCH_MODE_SINGLE_REFERENCES, IMAGE_BATCH_MODE_SINGLE_REFERENCES,
IMAGE_BATCH_MODES, IMAGE_BATCH_MODES,
@@ -36,6 +37,19 @@ from ..utils.o1key_image_catalog import (
BANANA_RESOLUTION_OPTIONS, BANANA_RESOLUTION_OPTIONS,
GPT_IMAGE_ASPECT_RATIO_OPTIONS, GPT_IMAGE_ASPECT_RATIO_OPTIONS,
GPT_IMAGE_BACKGROUND_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_COUNTS,
GPT_IMAGE_EXACT_SIZE_OPTIONS, GPT_IMAGE_EXACT_SIZE_OPTIONS,
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
@@ -258,6 +272,9 @@ async def _generate_gpt_images(
resize_mode: str, resize_mode: str,
output_format: str, output_format: str,
background: 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: if mask is not None and not references:
raise ValueError("提供了蒙版但未提供参考图,请同时上传参考图") raise ValueError("提供了蒙版但未提供参考图,请同时上传参考图")
@@ -295,6 +312,9 @@ async def _generate_gpt_images(
mask_tensor=mask, mask_tensor=mask,
output_format=output_format, output_format=output_format,
background=background, 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, resize_mode=resize_mode,
special_price_parallel=False, special_price_parallel=False,
log_downloads=True, log_downloads=True,
@@ -542,7 +562,7 @@ class O1keyImageGenerator(io.ComfyNode):
io.Combo.Input( io.Combo.Input(
"思考等级", "思考等级",
options=["低", "高"], options=["低", "高"],
default="低", default="高",
socketless=True, socketless=True,
), ),
io.Combo.Input( io.Combo.Input(
@@ -566,6 +586,7 @@ class O1keyImageGenerator(io.ComfyNode):
), ),
io.Int.Input( io.Int.Input(
"seed", "seed",
display_name="种子",
default=0, default=0,
min=0, min=0,
max=0xFFFFFFFFFFFFFFFF, max=0xFFFFFFFFFFFFFFFF,
@@ -587,7 +608,7 @@ class O1keyImageGenerator(io.ComfyNode):
), ),
io.Combo.Input( io.Combo.Input(
"输出格式", "输出格式",
options=GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, options=GPT_IMAGE_26_OUTPUT_FORMAT_OPTIONS,
default="jpeg", default="jpeg",
socketless=True, socketless=True,
), ),
@@ -600,7 +621,7 @@ class O1keyImageGenerator(io.ComfyNode):
io.Combo.Input( io.Combo.Input(
"缩放图片", "缩放图片",
options=["不缩放", "智能缩放"], options=["不缩放", "智能缩放"],
default="不缩放", default="智能缩放",
tooltip="Nano Banana 与 GPT Image 生效;智能缩放可能发生像素偏移。", tooltip="Nano Banana 与 GPT Image 生效;智能缩放可能发生像素偏移。",
socketless=True, socketless=True,
), ),
@@ -616,14 +637,19 @@ class O1keyImageGenerator(io.ComfyNode):
default=False, default=False,
label_on="开启", label_on="开启",
label_off="关闭", label_off="关闭",
tooltip="关闭时保持普通参考图生成;开启后按素材图和目标图展开组合。", tooltip="关闭时按普通参考图生成;开启后把素材图按所选模式与目标图组合,一次排队生成多张。",
socketless=True, socketless=True,
), ),
io.Combo.Input( io.Combo.Input(
"批量模式", "批量模式",
options=list(IMAGE_BATCH_MODES), options=list(IMAGE_BATCH_MODES),
default=IMAGE_BATCH_MODE_GROUP_TO_MODELS, default=IMAGE_BATCH_MODE_GROUP_TO_MODELS,
tooltip="整组素材:全部素材图作为一组并依次应用到多个目标;全匹配:每张素材图分别与每张目标图组合。", tooltip=(
"素材图与目标图的配对方式。"
"整组素材→多个目标:整组素材作为一套,依次套用到每张目标图;"
"每张素材×每张目标:两两组合,覆盖最全;"
"每张素材单独出图:不需要目标图,每张素材各自生成。"
),
socketless=True, socketless=True,
), ),
io.String.Input( io.String.Input(
@@ -659,13 +685,6 @@ class O1keyImageGenerator(io.ComfyNode):
tooltip="留空保存到 ComfyUI output 根目录;相对路径是 output 内的子文件夹;绝对路径可保存到任意磁盘目录。", tooltip="留空保存到 ComfyUI output 根目录;相对路径是 output 内的子文件夹;绝对路径可保存到任意磁盘目录。",
socketless=True, socketless=True,
), ),
io.Combo.Input(
"在线搜索",
options=["关闭", "打开"],
default="关闭",
tooltip="仅 Nano Banana 2 / 2.1 生效;打开时发送 google_search=true。",
socketless=True,
),
io.Boolean.Input( io.Boolean.Input(
"图层拆分", "图层拆分",
default=False, default=False,
@@ -674,6 +693,31 @@ class O1keyImageGenerator(io.ComfyNode):
tooltip="仅 Seedream 生效;必须且只能上传1张参考图,返回底图和最多16个透明图层。", tooltip="仅 Seedream 生效;必须且只能上传1张参考图,返回底图和最多16个透明图层。",
socketless=True, 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=[ outputs=[
io.Image.Output("IMAGE", display_name="IMAGE"), io.Image.Output("IMAGE", display_name="IMAGE"),
@@ -690,7 +734,7 @@ class O1keyImageGenerator(io.ComfyNode):
prompt: str, prompt: str,
模型: str = "Nano Banana 2.1", 模型: str = "Nano Banana 2.1",
模型线路: str = "畅速", 模型线路: str = "畅速",
思考等级: str = "低", 思考等级: str = "高",
分辨率: str = UNIFIED_IMAGE_SMART_RESOLUTION, 分辨率: str = UNIFIED_IMAGE_SMART_RESOLUTION,
宽高比: str = "智能", 宽高比: str = "智能",
生图数量: str | int = "1", 生图数量: str | int = "1",
@@ -708,8 +752,10 @@ class O1keyImageGenerator(io.ComfyNode):
filename_prefix: str = "o1key", filename_prefix: str = "o1key",
格式: str = "原始", 格式: str = "原始",
保存位置: str = "", 保存位置: str = "",
在线搜索: str = "关闭",
图层拆分: bool = False, 图层拆分: bool = False,
复杂度: str = "高",
帧数: int = GPT_IMAGE_GIF_FRAME_COUNT_DEFAULT,
帧时长ms: int = GPT_IMAGE_GIF_FRAME_DURATION_DEFAULT,
) -> io.NodeOutput: ) -> io.NodeOutput:
layer_decomposition = _is_enabled(图层拆分) layer_decomposition = _is_enabled(图层拆分)
if (not prompt or not prompt.strip()) and not ( if (not prompt or not prompt.strip()) and not (
@@ -719,7 +765,7 @@ class O1keyImageGenerator(io.ComfyNode):
if 输出格式 is None: if 输出格式 is None:
输出格式 = "png" if is_gpt_image_model(模型) else "jpeg" 输出格式 = "png" if is_gpt_image_model(模型) else "jpeg"
if 缩放图片 is None: if 缩放图片 is None:
缩放图片 = "智能缩放" if is_gpt_image_model(模型) else "不缩放" 缩放图片 = "智能缩放"
save_settings = _normalized_save_settings( save_settings = _normalized_save_settings(
模型, 模型,
filename_prefix, filename_prefix,
@@ -729,9 +775,8 @@ class O1keyImageGenerator(io.ComfyNode):
) )
if 缩放图片 not in {"不缩放", "智能缩放"}: if 缩放图片 not in {"不缩放", "智能缩放"}:
raise ValueError("缩放图片参数无效") raise ValueError("缩放图片参数无效")
if 在线搜索 not in {"关闭", "打开"}: # 在线搜索已下线:下游客户端仍支持 google_search,这里固定关闭。
raise ValueError("在线搜索参数无效") google_search = False
google_search = 模型 in {"Nano Banana 2.1", "Nano Banana 2"} and 在线搜索 == "打开"
image_count = int(生图数量) image_count = int(生图数量)
if is_gpt_image_model(模型): if is_gpt_image_model(模型):
@@ -740,6 +785,8 @@ class O1keyImageGenerator(io.ComfyNode):
elif image_count not in UNIFIED_IMAGE_COUNTS: elif image_count not in UNIFIED_IMAGE_COUNTS:
raise ValueError("生图数量仅支持:1、2、4、9") raise ValueError("生图数量仅支持:1、2、4、9")
batch_enabled = _is_enabled(批量出图) 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: if 批量模式 not in IMAGE_BATCH_MODES:
raise ValueError("批量模式无效") raise ValueError("批量模式无效")
@@ -874,13 +921,21 @@ class O1keyImageGenerator(io.ComfyNode):
raise ValueError("GPT Image 分辨率无效") raise ValueError("GPT Image 分辨率无效")
if 宽高比 not in GPT_IMAGE_ASPECT_RATIO_OPTIONS: if 宽高比 not in GPT_IMAGE_ASPECT_RATIO_OPTIONS:
raise ValueError("GPT Image 宽高比无效") raise ValueError("GPT Image 宽高比无效")
complexity = resolve_gpt_image_complexity(模型, 复杂度)
resolve_gpt_image_quality(模型, 质量) resolve_gpt_image_quality(模型, 质量)
if 输出格式 not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: 输出格式 = resolve_gpt_image_output_format(模型, 输出格式)
raise ValueError("GPT Image 输出格式无效")
if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS: if 背景 not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效") raise ValueError("GPT Image 背景参数无效")
if 背景 == "transparent" and 输出格式 == "jpeg": if 背景 == "transparent" and 输出格式 not in {"png", "webp"}:
raise ValueError("GPT Image 透明背景仅支持 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]]] = [] images_with_references: list[tuple[Image.Image, list[Any]]] = []
try: try:
images_with_references = await _generate_gpt_images( images_with_references = await _generate_gpt_images(
@@ -897,6 +952,9 @@ class O1keyImageGenerator(io.ComfyNode):
resize_mode=缩放图片, resize_mode=缩放图片,
output_format=输出格式, output_format=输出格式,
background=背景, background=背景,
complexity=complexity,
frame_count=frame_count,
frame_duration_ms=frame_duration_ms,
) )
except Exception as exc: except Exception as exc:
message = format_o1key_image_error(exc) message = format_o1key_image_error(exc)
@@ -1009,18 +1067,27 @@ class O1keyImageSave(io.ComfyNode):
save_location=settings.get("save_location", ""), save_location=settings.get("save_location", ""),
naming_rule=settings.get("naming_rule", DEFAULT_SAVE_NAMING_RULE), naming_rule=settings.get("naming_rule", DEFAULT_SAVE_NAMING_RULE),
) )
saved = ui.SavedImages([ animated = any(
ui.SavedResult( str(item.get("filename") or "").lower().endswith(".gif")
item["filename"], or item.get("media") == "gif"
item["subfolder"], or item.get("animated") is True
(
io.FolderType.temp
if item.get("type") == "temp"
else io.FolderType.output
),
)
for item in descriptors 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) return io.NodeOutput(images, ui=saved)
+220
View File
@@ -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 ``<img>`` 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"]
+2
View File
@@ -4,3 +4,5 @@ Pillow>=10.0.0
requests>=2.31.0 requests>=2.31.0
rembg[cpu]>=2.0.50 rembg[cpu]>=2.0.50
imageio-ffmpeg>=0.5.1 imageio-ffmpeg>=0.5.1
# Optional: better GPT Image SVG raster previews (falls back to placeholder)
# cairosvg>=2.7.0
+124
View File
@@ -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);
});
+245 -7
View File
@@ -3,6 +3,8 @@
import asyncio import asyncio
import os import os
import sys import sys
import tempfile
from pathlib import Path
import unittest import unittest
from io import BytesIO from io import BytesIO
from types import ModuleType from types import ModuleType
@@ -64,15 +66,16 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
self.assertEqual(inputs["缩放图片"].options, ["不缩放", "智能缩放"]) self.assertEqual(inputs["缩放图片"].options, ["不缩放", "智能缩放"])
self.assertEqual(inputs["缩放图片"].default, "智能缩放") 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.assertNotIn("色彩纠正", inputs)
self.assertEqual(inputs["背景"].options, ["auto", "transparent", "opaque"]) self.assertEqual(inputs["背景"].options, ["auto", "transparent", "opaque"])
self.assertNotIn("内容审查强度", inputs) self.assertNotIn("内容审查强度", inputs)
self.assertEqual( self.assertEqual(
[item.id for item in schema.inputs], [item.id for item in schema.inputs],
[ [
"prompt", "模型", "模型线路", "分辨率", "生图数量", "质量", "prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
"输出格式", "背景", "遮罩", "参考图组", "缩放图片", "seed", "输出格式", "背景", "遮罩", "参考图组", "缩放图片", "seed",
"帧数", "帧时长ms",
], ],
) )
self.assertEqual( self.assertEqual(
@@ -106,7 +109,7 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
self.assert_combo_values_are_strings(schema) self.assert_combo_values_are_strings(schema)
inputs = {item.id: item for item in schema.inputs} 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["缩放图片"].default, "智能缩放")
self.assertEqual(inputs["质量"].options, ["高", "中", "低", "自动", "超高", "最高"]) self.assertEqual(inputs["质量"].options, ["高", "中", "低", "自动", "超高", "最高"])
self.assertNotIn("色彩纠正", inputs) self.assertNotIn("色彩纠正", inputs)
@@ -114,9 +117,10 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
self.assertEqual( self.assertEqual(
[item.id for item in schema.inputs], [item.id for item in schema.inputs],
[ [
"prompt", "模型", "模型线路", "分辨率", "生图数量", "质量", "prompt", "模型", "模型线路", "复杂度", "分辨率", "生图数量", "质量",
"图片路径数量", "遮罩", "参考图组", "图片输出格式", "图片路径数量", "遮罩", "参考图组", "图片输出格式",
"背景", "图片保存命名规则", "图片保存路径", "缩放图片", "seed", "背景", "图片保存命名规则", "图片保存路径", "缩放图片", "seed",
"帧数", "帧时长ms",
], ],
) )
self.assertNotIn("并发数", inputs) self.assertNotIn("并发数", inputs)
@@ -139,6 +143,114 @@ class GPTImageNodeSchemaTests(unittest.TestCase):
): ):
self.assertFalse(inputs[input_name].advanced, input_name) 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): class GPTImageNodeExecutionTests(unittest.TestCase):
def test_single_node_forwards_request_controls_without_postprocess(self): def test_single_node_forwards_request_controls_without_postprocess(self):
calls = [] calls = []
@@ -174,7 +286,7 @@ class GPTImageNodeExecutionTests(unittest.TestCase):
self.assertIs(result[0], generated) self.assertIs(result[0], generated)
self.assertEqual(len(calls), 1) 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]["resize_mode"], "智能缩放")
self.assertEqual(calls[0]["background"], "transparent") self.assertEqual(calls[0]["background"], "transparent")
self.assertNotIn("moderation", calls[0]) self.assertNotIn("moderation", calls[0])
@@ -326,19 +438,145 @@ class GPTImageDownloadRetryTests(unittest.IsolatedAsyncioTestCase):
), ),
patch("builtins.print") as print_mock, 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, session,
signed_url, signed_url,
"第 1 张图片", "第 1 张图片",
) )
self.assertEqual(session.calls, 2) 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)) self.assertEqual(byte_count, len(image_bytes))
rendered = " ".join(str(value) for call in print_mock.call_args_list for value in call.args) rendered = " ".join(str(value) for call in print_mock.call_args_list for value in call.args)
self.assertNotIn(signed_url, rendered) self.assertNotIn(signed_url, rendered)
self.assertNotIn("signature=secret", 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"""<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10" fill="red"/></svg>"""
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__": if __name__ == "__main__":
unittest.main() unittest.main()
+55
View File
@@ -108,3 +108,58 @@ assert.equal(backgroundWidget.options.getOptionLabel("transparent"), "透明");
assert.equal(backgroundWidget.options.getOptionLabel("opaque"), "不透明"); assert.equal(backgroundWidget.options.getOptionLabel("opaque"), "不透明");
assert.equal(backgroundWidget.value, "transparent"); assert.equal(backgroundWidget.value, "transparent");
assert.deepEqual(Array.from(backgroundWidget.options.values), ["auto", "transparent", "opaque"]); 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);
}
+117
View File
@@ -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()
+416
View File
@@ -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()
+150 -19
View File
@@ -20,6 +20,20 @@ COMFY_ROOT = os.path.dirname(CUSTOM_NODES_DIR)
sys.path.insert(0, COMFY_ROOT) sys.path.insert(0, COMFY_ROOT)
sys.path.insert(0, CUSTOM_NODES_DIR) 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 comfy_api.latest import io # noqa: E402
from comfyui_o1key.clients.gpt_image_client import GptImageClient # noqa: E402 from comfyui_o1key.clients.gpt_image_client import GptImageClient # noqa: E402
from comfyui_o1key.nodes.o1key_image_generator import ( # 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, _parse_upload_manifest,
) )
from comfyui_o1key.utils.image_utils import ( # noqa: E402 from comfyui_o1key.utils.image_utils import ( # noqa: E402
IMAGE_BATCH_MODE_ALIASES,
IMAGE_BATCH_MODE_CARTESIAN, IMAGE_BATCH_MODE_CARTESIAN,
IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_GROUP_TO_MODELS,
IMAGE_BATCH_MODE_SINGLE_REFERENCES, IMAGE_BATCH_MODE_SINGLE_REFERENCES,
IMAGE_BATCH_MODES,
expand_image_generation_tasks, expand_image_generation_tasks,
pil_to_tensor, pil_to_tensor,
tensor_to_pil, tensor_to_pil,
@@ -55,15 +71,24 @@ class O1keyImageGeneratorTests(unittest.TestCase):
"Nano Banana 2.1", "Nano Banana 2.1",
"Nano Banana 2", "Nano Banana 2",
"Nano Banana Pro", "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-sunburst",
"gpt-image-2.5-flare", "gpt-image-2.5-flare",
"gpt-image-2",
"Seedream 5.0 Pro", "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): def test_schema_is_panel_node_with_image_output(self):
schema = O1keyImageGenerator.define_schema() schema = O1keyImageGenerator.define_schema()
schema.validate() schema.validate()
@@ -91,7 +116,7 @@ class O1keyImageGeneratorTests(unittest.TestCase):
"宽高比", "生图数量", "seed", "参考图清单", "宽高比", "生图数量", "seed", "参考图清单",
"质量", "输出格式", "蒙版清单", "缩放图片", "背景", "质量", "输出格式", "蒙版清单", "缩放图片", "背景",
"批量出图", "批量模式", "模特图清单", "批量出图", "批量模式", "模特图清单",
"命名规则", "filename_prefix", "格式", "保存位置", "在线搜索", "图层拆分", "命名规则", "filename_prefix", "格式", "保存位置", "图层拆分", "复杂度", "帧数", "帧时长ms",
], ],
) )
count_input = next(item for item in schema.inputs if item.id == "生图数量") 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 == "模型") model_input = next(item for item in schema.inputs if item.id == "模型")
self.assertEqual(model_input.default, "Nano Banana 2.1") self.assertEqual(model_input.default, "Nano Banana 2.1")
self.assertIn("gpt-image-2", model_input.options) 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-sunburst", model_input.options)
self.assertIn("gpt-image-2.5-flare", model_input.options) self.assertIn("gpt-image-2.5-flare", model_input.options)
self.assertIn("Seedream 5.0 Pro", 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 == "思考等级") thinking_input = next(item for item in schema.inputs if item.id == "思考等级")
self.assertEqual(thinking_input.options, ["低", "高"]) 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 == "分辨率") resolution_input = next(item for item in schema.inputs if item.id == "分辨率")
self.assertEqual(resolution_input.options[0], "智能") self.assertEqual(resolution_input.options[0], "智能")
self.assertEqual(resolution_input.default, "智能") self.assertEqual(resolution_input.default, "智能")
resize_input = next(item for item in schema.inputs if item.id == "缩放图片") resize_input = next(item for item in schema.inputs if item.id == "缩放图片")
self.assertEqual(resize_input.options, ["不缩放", "智能缩放"]) self.assertEqual(resize_input.options, ["不缩放", "智能缩放"])
self.assertEqual(resize_input.default, "不缩放") self.assertEqual(resize_input.default, "智能缩放")
self.assertNotIn("色彩纠正", [item.id for item in schema.inputs]) self.assertNotIn("色彩纠正", [item.id for item in schema.inputs])
format_input = next(item for item in schema.inputs if item.id == "输出格式") 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") self.assertEqual(format_input.default, "jpeg")
background_input = next(item for item in schema.inputs if item.id == "背景") background_input = next(item for item in schema.inputs if item.id == "背景")
self.assertEqual(background_input.options, ["auto", "transparent", "opaque"]) 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]) self.assertNotIn("内容审查强度", [item.id for item in schema.inputs])
quality_input = next(item for item in schema.inputs if item.id == "质量") quality_input = next(item for item in schema.inputs if item.id == "质量")
self.assertEqual(quality_input.options[-2:], ["超高", "最高"]) 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") prompt_input = next(item for item in schema.inputs if item.id == "prompt")
self.assertEqual(prompt_input.display_name, "提示词") self.assertEqual(prompt_input.display_name, "提示词")
self.assertTrue(prompt_input.socketless) self.assertTrue(prompt_input.socketless)
@@ -150,9 +181,7 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertEqual(save_format_input.default, "原始") self.assertEqual(save_format_input.default, "原始")
location_input = next(item for item in schema.inputs if item.id == "保存位置") location_input = next(item for item in schema.inputs if item.id == "保存位置")
self.assertEqual(location_input.default, "") self.assertEqual(location_input.default, "")
search_input = next(item for item in schema.inputs if item.id == "在线搜索") self.assertNotIn("在线搜索", [item.id for item in schema.inputs])
self.assertEqual(search_input.options, ["关闭", "打开"])
self.assertEqual(search_input.default, "关闭")
def test_batch_task_expansion_covers_group_and_cartesian_pairing(self): def test_batch_task_expansion_covers_group_and_cartesian_pairing(self):
grouped = expand_image_generation_tasks( grouped = expand_image_generation_tasks(
@@ -213,6 +242,39 @@ class O1keyImageGeneratorTests(unittest.TestCase):
self.assertEqual(len(fifty_single_references), 50) self.assertEqual(len(fifty_single_references), 50)
self.assertEqual(fifty_single_references[-1]["reference_indices"], (49,)) 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): def test_reference_limit_is_ten(self):
accepted = [ accepted = [
{"name": f"{index}.png", "subfolder": "", "type": "input"} {"name": f"{index}.png", "subfolder": "", "type": "input"}
@@ -341,7 +403,6 @@ class O1keyImageGeneratorTests(unittest.TestCase):
seed=42, seed=42,
参考图清单="[]", 参考图清单="[]",
缩放图片="智能缩放", 缩放图片="智能缩放",
在线搜索="打开",
)) ))
self.assertIs(result[0], image) 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["生图数量"], 2)
self.assertEqual(execute.call_args.kwargs["参考图组"], {}) self.assertEqual(execute.call_args.kwargs["参考图组"], {})
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) 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) image = torch.zeros((1, 8, 8, 3), dtype=torch.float32)
with patch( with patch(
"comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute", "comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute",
@@ -363,12 +424,11 @@ class O1keyImageGeneratorTests(unittest.TestCase):
prompt="一只宇航猫", prompt="一只宇航猫",
模型="Nano Banana Pro", 模型="Nano Banana Pro",
分辨率="2K", 分辨率="2K",
在线搜索="打开",
)) ))
self.assertIs(execute.call_args.kwargs["_o1key_google_search"], False) 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) image = torch.zeros((1, 8, 8, 3), dtype=torch.float32)
with patch( with patch(
"comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute", "comfyui_o1key.nodes.o1key_image_generator.NanoBanana.execute",
@@ -376,13 +436,13 @@ class O1keyImageGeneratorTests(unittest.TestCase):
) as execute: ) as execute:
result = asyncio.run(O1keyImageGenerator.execute( result = asyncio.run(O1keyImageGenerator.execute(
prompt="test", 模型线路="直连", 思考等级="高", prompt="test", 模型线路="直连", 思考等级="高",
分辨率="4K", 宽高比="1:8", 在线搜索="打开", 分辨率="4K", 宽高比="1:8",
)) ))
self.assertIs(result[0], image) self.assertIs(result[0], image)
self.assertEqual(execute.call_args.kwargs["模型"], "Nano Banana 2.1") self.assertEqual(execute.call_args.kwargs["模型"], "Nano Banana 2.1")
self.assertEqual(execute.call_args.kwargs["模型线路"], "直连") self.assertEqual(execute.call_args.kwargs["模型线路"], "直连")
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): def test_error_wrappers_apply_to_every_model_family(self):
raw = ( raw = (
@@ -491,22 +551,24 @@ class O1keyImageGeneratorTests(unittest.TestCase):
): ):
result = asyncio.run(O1keyImageGenerator.execute( result = asyncio.run(O1keyImageGenerator.execute(
prompt="一只宇航猫", prompt="一只宇航猫",
模型="gpt-image-2.5-sunburst", 模型="gpt-image-2.6-sunburst",
模型线路="畅速", 模型线路="畅速",
分辨率="2K", 分辨率="2K",
宽高比="16:9", 宽高比="16:9",
生图数量=4, 生图数量=4,
质量="最高", 质量="最高",
复杂度="中",
输出格式="webp", 输出格式="webp",
背景="transparent", 背景="transparent",
缩放图片="智能缩放", 缩放图片="智能缩放",
)) ))
self.assertEqual(tuple(result[0].shape), (4, 4, 6, 3)) 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.assertEqual(len(calls), 4)
self.assertGreater(maximum_active, 1) self.assertGreater(maximum_active, 1)
self.assertTrue(all(call["n"] == 1 for call in calls)) 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["special_price_parallel"] is False for call in calls))
self.assertTrue(all(call["size"] == "3648x2048" for call in calls)) self.assertTrue(all(call["size"] == "3648x2048" for call in calls))
self.assertTrue(all(call["quality"] == "max" 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("moderation" not in call for call in calls))
self.assertTrue(all(call["resize_mode"] == "智能缩放" 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): def test_seedream_direct_execution_sends_exact_size_and_output_format(self):
calls = [] calls = []
session = object() session = object()
File diff suppressed because it is too large Load Diff
+201
View File
@@ -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");
+91 -18
View File
@@ -18,6 +18,20 @@ COMFY_ROOT = CUSTOM_NODES_ROOT.parent
sys.path.insert(0, str(COMFY_ROOT)) sys.path.insert(0, str(COMFY_ROOT))
sys.path.insert(0, str(CUSTOM_NODES_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 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["generator_node_id"], 1)
self.assertEqual(job["save_node_id"], 2) 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 = _payload()
payload.pop("thinking_level") payload.pop("thinking_level")
job = JOBS.normalize_job_payload(payload) job = JOBS.normalize_job_payload(payload)
self.assertEqual(job["thinking_level"], "低") self.assertEqual(job["thinking_level"], "高")
self.assertEqual(job["resize_mode"], "不缩放") self.assertEqual(job["resize_mode"], "智能缩放")
self.assertNotIn("color_correction", job) self.assertNotIn("color_correction", job)
self.assertEqual(job["filename_prefix"], "o1key") self.assertEqual(job["filename_prefix"], "o1key")
self.assertEqual(job["save_format"], "原始") self.assertEqual(job["save_format"], "原始")
@@ -110,6 +124,62 @@ class PayloadTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "Nano Banana 2"): with self.assertRaisesRegex(ValueError, "Nano Banana 2"):
JOBS.normalize_job_payload(payload) 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): def test_unified_limits_and_gpt_parameters(self):
payload = _payload() payload = _payload()
payload.update({ payload.update({
@@ -146,7 +216,8 @@ class PayloadTests(unittest.TestCase):
self.assertEqual(default_gpt["resize_mode"], "智能缩放") self.assertEqual(default_gpt["resize_mode"], "智能缩放")
self.assertEqual(default_gpt["save_format"], "原始") 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): with self.subTest(model=model):
gpt_25 = JOBS.normalize_job_payload({ gpt_25 = JOBS.normalize_job_payload({
**_payload(), **_payload(),
@@ -353,7 +424,7 @@ class PayloadTests(unittest.TestCase):
grouped = JOBS.normalize_job_payload({ grouped = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "一组搭配+多模特", "batch_mode": "整组素材→多个目标",
"references": outfits[:9], "references": outfits[:9],
"model_references": models, "model_references": models,
}) })
@@ -364,7 +435,7 @@ class PayloadTests(unittest.TestCase):
cartesian = JOBS.normalize_job_payload({ cartesian = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "全部搭配×全部模特", "batch_mode": "每张素材×每张目标",
"references": outfits, "references": outfits,
"model_references": models, "model_references": models,
}) })
@@ -376,7 +447,7 @@ class PayloadTests(unittest.TestCase):
single_references = JOBS.normalize_job_payload({ single_references = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "单图素材批量", "batch_mode": "每张素材单独出图",
"references": outfits[:3], "references": outfits[:3],
"model_references": models[:1], "model_references": models[:1],
}) })
@@ -404,7 +475,7 @@ class PayloadTests(unittest.TestCase):
single_fifty = JOBS.normalize_job_payload({ single_fifty = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "单图素材批量", "batch_mode": "每张素材单独出图",
"references": fifty_references, "references": fifty_references,
}) })
self.assertEqual(single_fifty["total_task_count"], 50) self.assertEqual(single_fifty["total_task_count"], 50)
@@ -412,7 +483,7 @@ class PayloadTests(unittest.TestCase):
grouped_fifty_targets = JOBS.normalize_job_payload({ grouped_fifty_targets = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "一组搭配+多模特", "batch_mode": "整组素材→多个目标",
"references": outfits[:1], "references": outfits[:1],
"model_references": fifty_models, "model_references": fifty_models,
}) })
@@ -422,7 +493,7 @@ class PayloadTests(unittest.TestCase):
JOBS.normalize_job_payload({ JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "单图素材批量", "batch_mode": "每张素材单独出图",
"references": [ "references": [
*fifty_references, *fifty_references,
{"name": "overflow.png", "subfolder": "", "type": "input"}, {"name": "overflow.png", "subfolder": "", "type": "input"},
@@ -433,7 +504,7 @@ class PayloadTests(unittest.TestCase):
JOBS.normalize_job_payload({ JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "一组搭配+多模特", "batch_mode": "整组素材→多个目标",
"references": outfits, "references": outfits,
"model_references": models[:1], "model_references": models[:1],
}) })
@@ -641,7 +712,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
"model": "gpt-image-2", "model": "gpt-image-2",
"resolution": "1K", "resolution": "1K",
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "单图素材批量", "batch_mode": "每张素材单独出图",
"references": references, "references": references,
}) })
job["reference_paths"] = tuple(item["name"] for item in references) job["reference_paths"] = tuple(item["name"] for item in references)
@@ -700,7 +771,7 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
"model": "gpt-image-2", "model": "gpt-image-2",
"resolution": "1K", "resolution": "1K",
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "全部搭配×全部模特", "batch_mode": "每张素材×每张目标",
"references": [ "references": [
{"name": os.path.basename(path), "subfolder": "", "type": "input"} {"name": os.path.basename(path), "subfolder": "", "type": "input"}
for path in outfit_paths for path in outfit_paths
@@ -769,7 +840,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({ job = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"model": "gpt-image-2.5-sunburst", "model": "gpt-image-2.6-sunburst",
"complexity": "low",
"resolution": "4K", "resolution": "4K",
"aspect_ratio": "智能", "aspect_ratio": "智能",
"prompt": "紫色方块\n---\n绿色圆形", "prompt": "紫色方块\n---\n绿色圆形",
@@ -802,7 +874,8 @@ class GptExecutionTests(unittest.IsolatedAsyncioTestCase):
self.assertGreater(maximum_active, 1) self.assertGreater(maximum_active, 1)
self.assertTrue(all(call["n"] == 1 for call in calls)) self.assertTrue(all(call["n"] == 1 for call in calls))
self.assertTrue(all(call["quality"] == "xhigh" 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["special_price_parallel"] is False for call in calls))
self.assertTrue(all(call["size"] == "2880x2880" 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)) self.assertTrue(all(call["output_format"] == "webp" for call in calls))
@@ -902,7 +975,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({ job = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "单图素材批量", "batch_mode": "每张素材单独出图",
"references": references, "references": references,
}) })
job["reference_paths"] = tuple(item["name"] for item in references) job["reference_paths"] = tuple(item["name"] for item in references)
@@ -969,7 +1042,7 @@ class NanoExecutionTests(unittest.IsolatedAsyncioTestCase):
job = JOBS.normalize_job_payload({ job = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "全部搭配×全部模特", "batch_mode": "每张素材×每张目标",
"references": [ "references": [
{"name": os.path.basename(path), "subfolder": "", "type": "input"} {"name": os.path.basename(path), "subfolder": "", "type": "input"}
for path in outfit_paths for path in outfit_paths
@@ -1162,7 +1235,7 @@ class IsolationTests(unittest.TestCase):
job = JOBS.normalize_job_payload({ job = JOBS.normalize_job_payload({
**_payload(), **_payload(),
"batch_enabled": True, "batch_enabled": True,
"batch_mode": "全部搭配×全部模特", "batch_mode": "每张素材×每张目标",
"references": [{"name": "outfit.png", "subfolder": "", "type": "input"}], "references": [{"name": "outfit.png", "subfolder": "", "type": "input"}],
"model_references": [{"name": "model.png", "subfolder": "", "type": "input"}], "model_references": [{"name": "model.png", "subfolder": "", "type": "input"}],
}) })
+67
View File
@@ -334,5 +334,72 @@ class O1keyImageSaveTests(unittest.TestCase):
self.assertEqual(Path(output_dir, "1.png").read_bytes(), b"keep-existing") 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__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)
+188
View File
@@ -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 <img>.
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()
+294
View File
@@ -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"<svg") or head.startswith(b"<?xml") and b"<svg" in head
def is_gif_bytes(data: bytes) -> 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",
]
+13 -4
View File
@@ -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)] return [task_prompt for task_prompt in prompts for _ in range(count)]
IMAGE_BATCH_MODE_GROUP_TO_MODELS = "一组搭配+多模特" IMAGE_BATCH_MODE_GROUP_TO_MODELS = "整组素材→多个目标"
IMAGE_BATCH_MODE_CARTESIAN = "全部搭配×全部模特" IMAGE_BATCH_MODE_CARTESIAN = "每张素材×每张目标"
IMAGE_BATCH_MODE_SINGLE_REFERENCES = "单图素材批量" IMAGE_BATCH_MODE_SINGLE_REFERENCES = "每张素材单独出图"
IMAGE_BATCH_MODES = ( IMAGE_BATCH_MODES = (
IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_GROUP_TO_MODELS,
IMAGE_BATCH_MODE_CARTESIAN, IMAGE_BATCH_MODE_CARTESIAN,
IMAGE_BATCH_MODE_SINGLE_REFERENCES, 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( def expand_image_generation_tasks(
@@ -436,6 +443,8 @@ def expand_image_generation_tasks(
count = int(images_per_pair) count = int(images_per_pair)
if count < 1: if count < 1:
raise ValueError("每个组合的生图数量必须大于 0") 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()] prompts = parse_batch_prompts(prompt) or [prompt.strip()]
if not batch_enabled: if not batch_enabled:
pairings = [{ pairings = [{
@@ -451,7 +460,7 @@ def expand_image_generation_tasks(
model_total = max(0, int(model_reference_count)) model_total = max(0, int(model_reference_count))
if batch_mode == IMAGE_BATCH_MODE_SINGLE_REFERENCES: if batch_mode == IMAGE_BATCH_MODE_SINGLE_REFERENCES:
if outfit_total < 1: if outfit_total < 1:
raise ValueError("单图批量至少需要上传1张素材图") raise ValueError("每张素材单独出图至少需要上传1张素材图")
pairings = [ pairings = [
{ {
"reference_indices": (outfit_index,), "reference_indices": (outfit_index,),
+264
View File
@@ -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",
]
+134 -5
View File
@@ -9,16 +9,17 @@ from .nano_banana_models import (
GPT_IMAGE_MODEL_OPTIONS = [ 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-sunburst",
"gpt-image-2.5-flare", "gpt-image-2.5-flare",
"gpt-image-2",
] ]
SEEDREAM_MODEL_OPTIONS = ["Seedream 5.0 Pro"] SEEDREAM_MODEL_OPTIONS = ["Seedream 5.0 Pro"]
UNIFIED_IMAGE_MODEL_OPTIONS = [ UNIFIED_IMAGE_MODEL_OPTIONS = [
*NANO_BANANA_MODEL_OPTIONS[:3], *NANO_BANANA_MODEL_OPTIONS[:3],
*GPT_IMAGE_MODEL_OPTIONS, *GPT_IMAGE_MODEL_OPTIONS,
*SEEDREAM_MODEL_OPTIONS, *SEEDREAM_MODEL_OPTIONS,
*NANO_BANANA_MODEL_OPTIONS[3:],
] ]
UNIFIED_IMAGE_ROUTE_OPTIONS = list(NANO_BANANA_ROUTE_OPTIONS) UNIFIED_IMAGE_ROUTE_OPTIONS = list(NANO_BANANA_ROUTE_OPTIONS)
@@ -65,8 +66,30 @@ GPT_IMAGE_EXACT_SIZE_OPTIONS = [
] ]
GPT_IMAGE_QUALITY_OPTIONS = ["高", "中", "低", "自动"] GPT_IMAGE_QUALITY_OPTIONS = ["高", "中", "低", "自动"]
GPT_IMAGE_25_QUALITY_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_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 = { GPT_IMAGE_SIZE_MATRIX = {
("1K", "1:1"): "1024x1024", ("1K", "1:1"): "1024x1024",
("1K", "3:2"): "1536x1024", ("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: def is_gpt_image_model(model: str) -> bool:
return model in GPT_IMAGE_MODEL_OPTIONS 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: def resolve_gpt_image_quality(model_name: str, quality: str) -> str:
"""Resolve a displayed GPT quality for the selected model family.""" """Resolve a displayed GPT quality for the selected model family."""
if quality in {"超高", "最高"}: if quality in {"超高", "最高"}:
if model_name not in GPT_IMAGE_MODEL_OPTIONS or not model_name.startswith("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 系列模型") raise ValueError("超高和最高质量仅支持 GPT Image 2.5 / 2.6 系列模型")
return {"超高": "xhigh", "最高": "max"}[quality] return {"超高": "xhigh", "最高": "max"}[quality]
try: try:
return {"高": "high", "中": "medium", "低": "low", "自动": "auto"}[quality] 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 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: def is_seedream_model(model: str) -> bool:
return model in SEEDREAM_MODEL_OPTIONS return model in SEEDREAM_MODEL_OPTIONS
@@ -200,6 +310,10 @@ __all__ = [
"GPT_IMAGE_ASPECT_RATIO_OPTIONS", "GPT_IMAGE_ASPECT_RATIO_OPTIONS",
"GPT_IMAGE_BACKGROUND_OPTIONS", "GPT_IMAGE_BACKGROUND_OPTIONS",
"GPT_IMAGE_COUNTS", "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_EXACT_SIZE_OPTIONS",
"GPT_IMAGE_MODEL_OPTIONS", "GPT_IMAGE_MODEL_OPTIONS",
"GPT_IMAGE_25_QUALITY_OPTIONS", "GPT_IMAGE_25_QUALITY_OPTIONS",
@@ -226,4 +340,19 @@ __all__ = [
"resolve_gpt_image_quality", "resolve_gpt_image_quality",
"resolve_seedream_size", "resolve_seedream_size",
"resolve_seedream_layer_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",
] ]
+114 -30
View File
@@ -21,6 +21,11 @@ from .o1key_image_catalog import (
BANANA_RESOLUTION_OPTIONS, BANANA_RESOLUTION_OPTIONS,
GPT_IMAGE_ASPECT_RATIO_OPTIONS, GPT_IMAGE_ASPECT_RATIO_OPTIONS,
GPT_IMAGE_BACKGROUND_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_EXACT_SIZE_OPTIONS,
GPT_IMAGE_OUTPUT_FORMAT_OPTIONS, GPT_IMAGE_OUTPUT_FORMAT_OPTIONS,
GPT_IMAGE_COUNTS, GPT_IMAGE_COUNTS,
@@ -44,11 +49,13 @@ from .o1key_image_catalog import (
) )
from .http_error import format_o1key_image_error from .http_error import format_o1key_image_error
from .image_utils import ( from .image_utils import (
IMAGE_BATCH_MODE_ALIASES,
IMAGE_BATCH_MODE_GROUP_TO_MODELS, IMAGE_BATCH_MODE_GROUP_TO_MODELS,
IMAGE_BATCH_MODE_SINGLE_REFERENCES, IMAGE_BATCH_MODE_SINGLE_REFERENCES,
IMAGE_BATCH_MODES, IMAGE_BATCH_MODES,
expand_image_generation_tasks, 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 ( from .o1key_image_save import (
DEFAULT_SAVE_NAMING_RULE, DEFAULT_SAVE_NAMING_RULE,
detect_image_format, detect_image_format,
@@ -341,7 +348,7 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
payload.get("resolution") or UNIFIED_IMAGE_SMART_RESOLUTION payload.get("resolution") or UNIFIED_IMAGE_SMART_RESOLUTION
).strip() ).strip()
aspect_ratio = str(payload.get("aspect_ratio") or "智能").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: if model not in MODELS:
raise ValueError("模型无效") raise ValueError("模型无效")
if model_route not in MODEL_ROUTES: 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 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() quality = str(payload.get("quality") or "自动").strip()
resize_mode = str( resize_mode = str(
payload.get("resize_mode") or ("智能缩放" if is_gpt_image_model(model) else "不缩放") payload.get("resize_mode") or "智能缩放"
).strip() ).strip()
if resize_mode not in {"不缩放", "智能缩放"}: if resize_mode not in {"不缩放", "智能缩放"}:
raise ValueError("缩放图片参数无效") raise ValueError("缩放图片参数无效")
@@ -366,13 +373,17 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
raise ValueError("GPT Image 分辨率无效") raise ValueError("GPT Image 分辨率无效")
if aspect_ratio not in GPT_IMAGE_ASPECT_RATIO_OPTIONS: if aspect_ratio not in GPT_IMAGE_ASPECT_RATIO_OPTIONS:
raise ValueError("GPT Image 宽高比无效") raise ValueError("GPT Image 宽高比无效")
complexity = resolve_gpt_image_complexity(model, payload.get("complexity"))
resolve_gpt_image_quality(model, quality) resolve_gpt_image_quality(model, quality)
if output_format not in GPT_IMAGE_OUTPUT_FORMAT_OPTIONS: output_format = resolve_gpt_image_output_format(model, output_format)
raise ValueError("GPT Image 输出格式无效")
if background not in GPT_IMAGE_BACKGROUND_OPTIONS: if background not in GPT_IMAGE_BACKGROUND_OPTIONS:
raise ValueError("GPT Image 背景参数无效") 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 输出格式") 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): elif is_seedream_model(model):
output_format = str( output_format = str(
payload.get("output_format") or ("png" if layer_decomposition else "jpeg") 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( batch_mode = str(
payload.get("batch_mode") or IMAGE_BATCH_MODE_GROUP_TO_MODELS payload.get("batch_mode") or IMAGE_BATCH_MODE_GROUP_TO_MODELS
).strip() ).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: if batch_enabled and batch_mode not in IMAGE_BATCH_MODES:
raise ValueError("批量模式无效") raise ValueError("批量模式无效")
if not batch_enabled: if not batch_enabled:
@@ -558,8 +571,20 @@ def normalize_job_payload(payload: Any) -> dict[str, Any]:
"layer_decomposition": layer_decomposition, "layer_decomposition": layer_decomposition,
} }
if is_gpt_image_model(model): 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["output_format"] = output_format
job["background"] = background 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): elif is_seedream_model(model):
job["output_format"] = output_format job["output_format"] = output_format
elif google_search: 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 detected = detect_image_format(raw) if isinstance(raw, bytes) else None
if detected == "JPEG": if detected == "JPEG":
return "jpg" return "jpg"
if detected in {"PNG", "WEBP"}: if detected in {"PNG", "WEBP", "GIF", "SVG"}:
return detected.lower() 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" 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 detected = detect_image_format(raw) if isinstance(raw, bytes) else None
temporary_path = f"{output_path}.tmp" temporary_path = f"{output_path}.tmp"
try: try:
if detected in {"PNG", "JPEG", "WEBP"}: if detected in {"PNG", "JPEG", "WEBP", "GIF", "SVG"}:
with open(temporary_path, "wb") as handle: with open(temporary_path, "wb") as handle:
handle.write(raw) handle.write(raw)
else: else:
@@ -1066,6 +1096,7 @@ async def _execute_gpt_image_job(
actual_model = resolve_gpt_image_model(job["model"], job["model_route"]) actual_model = resolve_gpt_image_model(job["model"], job["model_route"])
quality = resolve_gpt_image_quality(job["model"], job["quality"]) quality = resolve_gpt_image_quality(job["model"], job["quality"])
complexity = resolve_gpt_image_complexity(job["model"], job.get("complexity"))
client = GptImageClient() client = GptImageClient()
client.base_url = get_base_url_by_route() client.base_url = get_base_url_by_route()
client.response_log_enabled = False client.response_log_enabled = False
@@ -1170,6 +1201,11 @@ async def _execute_gpt_image_job(
started_at = time.monotonic() started_at = time.monotonic()
heartbeat = asyncio.create_task(_heartbeat()) heartbeat = asyncio.create_task(_heartbeat())
try: 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( images = await client.generate_image_async(
prompt=job["task_prompts"][request_index], prompt=job["task_prompts"][request_index],
model=actual_model, model=actual_model,
@@ -1187,6 +1223,8 @@ async def _execute_gpt_image_job(
mask_tensor=mask_tensor, mask_tensor=mask_tensor,
output_format=job["output_format"], output_format=job["output_format"],
background=job["background"], background=job["background"],
**({"complexity": complexity} if complexity is not None else {}),
**frame_kwargs,
resize_mode=job["resize_mode"], resize_mode=job["resize_mode"],
progress_callback=lambda value: _update_request_progress( progress_callback=lambda value: _update_request_progress(
request_index, request_index,
@@ -1209,30 +1247,76 @@ async def _execute_gpt_image_job(
if not images: if not images:
raise RuntimeError(f"第 {request_index + 1} 次请求没有返回图片") raise RuntimeError(f"第 {request_index + 1} 次请求没有返回图片")
_update_request_progress(request_index, 0.96) _update_request_progress(request_index, 0.96)
selected = images[0] descriptors: list[dict[str, Any]] = []
filename = _result_filename( anim = animation_bytes_from_images(images)
job, svg = svg_bytes_from_image(images[0])
request_index, if anim is not None:
0, filename = _result_filename(job, request_index, 0, "gif")
_provider_result_format(selected), target = os.path.join(output_path, filename)
) await asyncio.to_thread(write_bytes_atomic, target, anim)
target = os.path.join(output_path, filename) descriptors.append({
await asyncio.to_thread( "filename": filename,
_write_provider_result, "subfolder": relative_subfolder,
selected, "type": "temp",
target, "batch_id": job["batch_id"],
) "request_index": request_index + 1,
descriptor = { "result_index": 1,
"filename": filename, "media": "gif",
"subfolder": relative_subfolder, })
"type": "temp", elif svg is not None:
"batch_id": job["batch_id"], svg_name = _result_filename(job, request_index, 0, "svg")
"request_index": request_index + 1, svg_target = os.path.join(output_path, svg_name)
"result_index": 1, await asyncio.to_thread(write_bytes_atomic, svg_target, svg)
} # Raster preview for Comfy IMAGE / native preview pipelines.
_publish_partial_images(progress_callback, [descriptor]) 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) _update_request_progress(request_index, 1.0)
return [descriptor] return descriptors
finally: finally:
for image in images: for image in images:
image.close() image.close()
+23 -6
View File
@@ -24,7 +24,8 @@ from PIL.PngImagePlugin import PngInfo
SAVE_FORMAT_OPTIONS = ("原始", "png", "jpg", "webp") SAVE_FORMAT_OPTIONS = ("原始", "png", "jpg", "webp")
SAVE_NAMING_RULE_OPTIONS = ("和主图一致", "自然数字", "自定义前缀") SAVE_NAMING_RULE_OPTIONS = ("和主图一致", "自然数字", "自定义前缀")
DEFAULT_SAVE_NAMING_RULE = "自定义前缀" 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" _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
_SAVE_LOCK = threading.Lock() _SAVE_LOCK = threading.Lock()
_UNSAFE_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]') _UNSAFE_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
@@ -107,6 +108,11 @@ def detect_image_format(data: bytes) -> str | None:
return "JPEG" return "JPEG"
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "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"<svg") or (head.startswith(b"<?xml") and b"<svg" in head):
return "SVG"
return None return None
@@ -458,12 +464,20 @@ def _save_sources(
"jpg": "JPEG", "jpg": "JPEG",
"webp": "WEBP", "webp": "WEBP",
}[selected] }[selected]
# Never re-encode GIF into itself via Pillow; keep provider bytes.
if selected == "原始" and source_format == "GIF" and isinstance(raw, bytes) and detect_image_format(raw) == "GIF":
target_format = "GIF"
if target_format not in _FORMAT_EXTENSIONS: if target_format not in _FORMAT_EXTENSIONS:
target_format = "PNG" target_format = "PNG"
if target_format == "JPEG" and _has_workflow_metadata(extra_pnginfo): if target_format == "JPEG" and _has_workflow_metadata(extra_pnginfo):
target_format = "PNG" target_format = "PNG"
# GIF has no workflow metadata container in this pack; keep bytes intact.
if target_format == "GIF" and (not isinstance(raw, bytes) or detect_image_format(raw) != "GIF"):
raise ValueError("GIF 结果缺少原始字节,无法原样保存")
extension = _FORMAT_EXTENSIONS[target_format] extension = _FORMAT_EXTENSIONS[target_format]
if selected == "原始" and raw is not None and detect_image_format(raw) == target_format: if target_format == "GIF":
encoded = raw
elif selected == "原始" and raw is not None and detect_image_format(raw) == target_format:
encoded = inject_workflow_metadata( encoded = inject_workflow_metadata(
raw, raw,
target_format, target_format,
@@ -502,11 +516,13 @@ def _save_sources(
except FileExistsError: except FileExistsError:
continue continue
if external_location: if external_location:
results.append( descriptor = _external_preview_descriptor(encoded, saved_name, folder_paths_module)
_external_preview_descriptor(encoded, saved_name, folder_paths_module)
)
else: else:
results.append({"filename": saved_name, "subfolder": subfolder, "type": "output"}) descriptor = {"filename": saved_name, "subfolder": subfolder, "type": "output"}
if target_format == "GIF" or saved_name.lower().endswith(".gif"):
descriptor["media"] = "gif"
descriptor["animated"] = True
results.append(descriptor)
return results return results
@@ -564,6 +580,7 @@ def save_temp_images(
image_format = detect_image_format(raw) image_format = detect_image_format(raw)
if image_format not in _FORMAT_EXTENSIONS: if image_format not in _FORMAT_EXTENSIONS:
raise ValueError(f"临时结果不是受支持的图像:{os.path.basename(source_path)}") raise ValueError(f"临时结果不是受支持的图像:{os.path.basename(source_path)}")
# GIF is accepted and preserved byte-for-byte when save format is 原始.
with Image.open(BytesIO(raw)) as opened: with Image.open(BytesIO(raw)) as opened:
opened.load() opened.load()
image = opened.copy() image = opened.copy()
+11
View File
@@ -217,6 +217,17 @@ def extract_video_url(payload: Dict[str, Any]) -> str | None:
if value: if value:
return str(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 # 腾讯 Kling(v3-t)渠道:完成时视频地址在 metadata.url
metadata = _as_dict(source.get("metadata")) metadata = _as_dict(source.get("metadata"))
value = metadata.get("url") or metadata.get("video_url") value = metadata.get("url") or metadata.get("video_url")
+240
View File
@@ -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 <img>. 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 <img>.
* 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 <img>,
// 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);
},
});
+100 -7
View File
@@ -4,19 +4,66 @@ const NODE_TYPES = new Set(["O1keyGPTImage", "O1keyGPTImageBatch"]);
const BASE_QUALITY_OPTIONS = ["高", "中", "低", "自动"]; const BASE_QUALITY_OPTIONS = ["高", "中", "低", "自动"];
const GPT_IMAGE_25_QUALITY_OPTIONS = [...BASE_QUALITY_OPTIONS, "超高", "最高"]; const GPT_IMAGE_25_QUALITY_OPTIONS = [...BASE_QUALITY_OPTIONS, "超高", "最高"];
const QUALITY_FALLBACK = "自动"; 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) { function findWidget(node, name) {
return node.widgets?.find((widget) => widget.name === 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) { function updateQualityOptions(node) {
const modelWidget = findWidget(node, "模型"); const modelWidget = findWidget(node, "模型");
const qualityWidget = findWidget(node, "质量"); const qualityWidget = findWidget(node, "质量");
if (!modelWidget || !qualityWidget) return; if (!modelWidget || !qualityWidget) return;
const supports25Quality = const model = String(modelWidget.value || "");
typeof modelWidget.value === "string" && modelWidget.value.startsWith("gpt-image-2.5-"); const supportsExtendedQuality = /^gpt-image-2\.[56]-/.test(model);
const allowedOptions = supports25Quality ? GPT_IMAGE_25_QUALITY_OPTIONS : BASE_QUALITY_OPTIONS; const is26 = /^gpt-image-2\.6-/.test(model);
const allowedOptions = supportsExtendedQuality ? GPT_IMAGE_25_QUALITY_OPTIONS : BASE_QUALITY_OPTIONS;
qualityWidget.options ??= {}; qualityWidget.options ??= {};
qualityWidget.options.values = [...allowedOptions]; qualityWidget.options.values = [...allowedOptions];
@@ -25,6 +72,33 @@ function updateQualityOptions(node) {
qualityWidget.callback?.(QUALITY_FALLBACK); 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); node.setDirtyCanvas?.(true, true);
} }
@@ -35,10 +109,29 @@ function guardNode(node) {
if (!modelWidget || !qualityWidget) return; if (!modelWidget || !qualityWidget) return;
node.__o1keyGptImageQuality = true; node.__o1keyGptImageQuality = true;
const originalModelCallback = modelWidget.callback; const watch = ["模型", "输出格式", "图片输出格式", "遮罩"];
modelWidget.callback = function () { for (const name of watch) {
const result = originalModelCallback?.apply(this, arguments); const widget = findWidget(node, name);
updateQualityOptions(node); 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; return result;
}; };
+182 -19
View File
@@ -13,9 +13,11 @@ const GPT_IMAGE_ROUTE_ALIASES = new Map([
]); ]);
const GPT_IMAGE_NODE_TYPES = new Set(["O1keyGPTImage", "O1keyGPTImageBatch"]); const GPT_IMAGE_NODE_TYPES = new Set(["O1keyGPTImage", "O1keyGPTImageBatch"]);
const GPT_IMAGE_MODELS = new Set([ 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-sunburst",
"gpt-image-2.5-flare", "gpt-image-2.5-flare",
"gpt-image-2",
]); ]);
const GPT_IMAGE_ROUTES = new Set(["畅速", "直连", "专线"]); const GPT_IMAGE_ROUTES = new Set(["畅速", "直连", "专线"]);
const GPT_IMAGE_RESIZE_MODES = 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 UNIFIED_COLOR_CORRECTION_MODES = new Set(["不纠正", "智能纠正"]);
const GPT_IMAGE_BACKGROUNDS = new Set(["auto", "transparent", "opaque"]); const GPT_IMAGE_BACKGROUNDS = new Set(["auto", "transparent", "opaque"]);
const GPT_IMAGE_MODERATION_MODES = new Set(["自动", "低"]); 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_OUTPUT_FORMATS = new Set(["原始", "JPEG", "PNG", "WebP"]);
const GPT_IMAGE_BATCH_NAMING_RULES = new Set(["和原始图片名保持一致", "自然数字"]); const GPT_IMAGE_BATCH_NAMING_RULES = new Set(["和原始图片名保持一致", "自然数字"]);
@@ -33,12 +64,25 @@ function findLastIndex(values, predicate) {
return -1; 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) { 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; if (!match) return -1;
const pathCount = Number(match[1]); const pathCount = Number(match[1]);
const pairingWidgetCount = pathCount >= 2 ? 1 : 0; const pairingWidgetCount = pathCount >= 2 ? 1 : 0;
return 7 + pathCount + pairingWidgetCount; return pathCountIndex + 1 + pathCount + pairingWidgetCount;
} }
function batchGPTImageConcurrencyIndex(wv) { function batchGPTImageConcurrencyIndex(wv) {
@@ -113,6 +157,10 @@ function findLegacySeedanceAssetWidgets(wv) {
const NANO_BANANA_MODELS = new Set([ const NANO_BANANA_MODELS = new Set([
"Nano Banana Pro", "Nano Banana 2 Lite", "Nano Banana 2.1", "Nano Banana 2", "Nano Banana", "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([ const NANO_BANANA_ROUTE_ALIASES = new Map([
["特价", "畅速"], ["特价", "畅速"],
["官方", "专线"], ["官方", "专线"],
@@ -143,13 +191,18 @@ function isCurrentGPTImageBatchWidgetLayout(wv) {
const resizeIndex = namingIndex + 2; const resizeIndex = namingIndex + 2;
const seedIndex = namingIndex + 3; const seedIndex = namingIndex + 3;
const randomSelectionIndex = batchGPTImageRandomSelectionIndex(wv); 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]) return GPT_IMAGE_BATCH_OUTPUT_FORMATS.has(wv[formatIndex])
&& GPT_IMAGE_BACKGROUNDS.has(wv[backgroundIndex]) && GPT_IMAGE_BACKGROUNDS.has(wv[backgroundIndex])
&& typeof wv[savePathIndex] === "string" && typeof wv[savePathIndex] === "string"
&& GPT_IMAGE_RESIZE_MODES.has(wv[resizeIndex]) && GPT_IMAGE_RESIZE_MODES.has(wv[resizeIndex])
&& Number.isInteger(wv[seedIndex]) && Number.isInteger(wv[seedIndex])
&& formatIndex === randomSelectionIndex && formatIndex === randomSelectionIndex
&& seedIndex === wv.length - 1; && (seedIndex === wv.length - 1 || hasFrameTail);
} }
function isGPTImageBatchWidgetLayoutWithRandomSelection(wv) { function isGPTImageBatchWidgetLayoutWithRandomSelection(wv) {
@@ -238,6 +291,16 @@ const MIGRATIONS = [
&& typeof wv[9] === "string" && /^\s*\[/.test(wv[9]), && typeof wv[9] === "string" && /^\s*\[/.test(wv[9]),
apply: (wv) => wv.splice(8, 1), 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", type: "O1keyAutoRedCast",
note: "为旧版自动红偏校正补齐末尾 seed 参数", note: "为旧版自动红偏校正补齐末尾 seed 参数",
@@ -320,7 +383,7 @@ const MIGRATIONS = [
note: "为统一图片生成节点补齐可选批量出图字段", note: "为统一图片生成节点补齐可选批量出图字段",
when: (wv) => wv.length >= 15 && wv.length < 18, when: (wv) => wv.length >= 15 && wv.length < 18,
apply: (wv) => { apply: (wv) => {
const appendedDefaults = [false, "一组搭配+多模特", "[]"]; const appendedDefaults = [false, "整组素材→多个目标", "[]"];
while (wv.length < 18) wv.push(appendedDefaults[wv.length - 15]); 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 nodes = Array.isArray(container?.nodes) ? container.nodes : [];
const nodesById = new Map(nodes.map((node) => [String(node?.id), node])); const nodesById = new Map(nodes.map((node) => [String(node?.id), node]));
const defaults = ["自定义前缀", "o1key", "原始", ""]; const defaults = ["自定义前缀", "o1key", "原始", ""];
// 保存位置 是这份补齐序列的终点;老存档若还带着已停用的内容审查强度,就要多补一格。
const saveSettingsTarget = (values) => (GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 22 : 21);
let migrated = 0; let migrated = 0;
for (const saveNode of nodes.filter((node) => node?.type === "O1keyImageSave")) { for (const saveNode of nodes.filter((node) => node?.type === "O1keyImageSave")) {
@@ -1395,7 +1460,7 @@ function migrateUnifiedSaveSettings(container) {
if (generatorValues.length === 18) { if (generatorValues.length === 18) {
generatorValues.push(legacy[3], legacy[0], legacy[1], legacy[2]); generatorValues.push(legacy[3], legacy[0], legacy[1], legacy[2]);
} else { } else {
while (generatorValues.length < 22) { while (generatorValues.length < saveSettingsTarget(generatorValues)) {
generatorValues.push(defaults[generatorValues.length - 18]); generatorValues.push(defaults[generatorValues.length - 18]);
} }
} }
@@ -1407,34 +1472,73 @@ function migrateUnifiedSaveSettings(container) {
const values = generator?.widgets_values; const values = generator?.widgets_values;
if (!Array.isArray(values) || values.length < 18) continue; if (!Array.isArray(values) || values.length < 18) continue;
const before = values.length; 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++; if (values.length !== before) migrated++;
} }
return 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 : []; const nodes = Array.isArray(container?.nodes) ? container.nodes : [];
let migrated = 0; let migrated = 0;
for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) { for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) {
const values = node?.widgets_values; const values = node?.widgets_values;
if (!Array.isArray(values)) continue; if (!Array.isArray(values)) continue;
const expectedLength = GPT_IMAGE_MODERATION_MODES.has(values[14]) ? 22 : 21; // Match by label instead of index so the rewrite survives every array shape.
if (values.length !== expectedLength) continue; const index = values.findIndex((value) => RETIRED_BATCH_MODE_LABELS.has(value));
values.push("关闭"); if (index < 0) continue;
values[index] = RETIRED_BATCH_MODE_LABELS.get(values[index]);
migrated++; migrated++;
} }
return 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) { function migrateUnifiedLayerDecomposition(container) {
const nodes = Array.isArray(container?.nodes) ? container.nodes : []; const nodes = Array.isArray(container?.nodes) ? container.nodes : [];
let migrated = 0; let migrated = 0;
for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) { for (const node of nodes.filter((item) => item?.type === "O1keyImageGenerator")) {
const values = node?.widgets_values; const values = node?.widgets_values;
if (!Array.isArray(values)) continue; 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; 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); values.push(false);
migrated++; migrated++;
} }
@@ -1469,6 +1573,51 @@ app.registerExtension({
migrated += migrateGrokVideoInputNames(node); migrated += migrateGrokVideoInputNames(node);
const wv = node?.widgets_values; const wv = node?.widgets_values;
if (!Array.isArray(wv)) continue; 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) { for (const rule of MIGRATIONS) {
if (rule.type !== "*" && node.type !== rule.type) continue; if (rule.type !== "*" && node.type !== rule.type) continue;
try { try {
@@ -1480,23 +1629,37 @@ app.registerExtension({
console.warn(`[o1key] 工作流迁移失败: ${rule.note}`, e); 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)) { for (const container of collectGraphContainers(graphData)) {
migrated += migrateBatchNanoRandomInput(container); migrated += migrateBatchNanoRandomInput(container);
migrated += migrateUnifiedExternalPromptInput(container); migrated += migrateUnifiedExternalPromptInput(container);
migrated += migrateUnifiedSaveSettings(container); migrated += migrateUnifiedSaveSettings(container);
migrated += migrateUnifiedOnlineSearch(container); migrated += migrateUnifiedBatchModeLabels(container);
migrated += migrateUnifiedLayerDecomposition(container); migrated += migrateUnifiedLayerDecomposition(container);
migrated += migrateUnifiedModeration(container); migrated += migrateUnifiedModeration(container);
for (const node of container?.nodes || []) { for (const node of container?.nodes || []) {
const values = node?.widgets_values; const values = node?.widgets_values;
if (node?.type === "O1keyImageGenerator" && Array.isArray(values) if (node?.type !== "O1keyImageGenerator" || !Array.isArray(values)) continue;
&& values.length === 24 && values[23] === "" // A retired non-serialized HTML panel value can linger on the tail. Every real
&& ["关闭", "打开"].includes(values[21]) && typeof values[22] === "boolean") { // widget ends on a boolean or a number there (保存位置 also holds "" but always
values.pop(); // Retired non-serialized HTML panel value. // sits behind 格式), so an empty string on the tail is never a real value.
migrated++; 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) { if (migrated > 0) {
console.log(`[o1key] 工作流参数迁移:已修复 ${migrated} 处参数或端口`); console.log(`[o1key] 工作流参数迁移:已修复 ${migrated} 处参数或端口`);
File diff suppressed because it is too large Load Diff