From e19ca28423f7e350c23fe915c4da45d73647d530 Mon Sep 17 00:00:00 2001 From: leefer Date: Fri, 30 Oct 2026 14:41:12 +0800 Subject: [PATCH] HEL-892: add source-bound SDPose video documentation Co-authored-by: multica-agent --- .../src/calliope/comfyui/fixed_document.py | 5 + .../src/calliope/comfyui/source_reviews.json | 838 +++- .../tests/test_background_fixed_document.py | 3 +- .../tests/test_controlnet_fixed_document.py | 2 +- .../tests/test_gemma_fixed_document.py | 5 +- .../tests/test_grid_fixed_document.py | 5 +- .../tests/test_qwen_edit_fixed_document.py | 3 +- .../tests/test_sdpose_fixed_document.py | 262 + .../SDPose视频骨架图固定参考中文说明.md | 582 +++ .../build_definition.cpython-310.pyc | Bin 0 -> 18564 bytes .../build_definition.cpython-311.pyc | Bin 0 -> 23922 bytes .../__pycache__/rebuild.cpython-311.pyc | Bin 0 -> 4633 bytes .../actual-sdpose_视频人物姿势骨架提取.json | 1478 ++++++ .../audit-summary.json | 24 + .../sdpose-document-evidence/boundaries.json | 728 +++ .../hel-892/sdpose-document-evidence/brief.md | 1 + .../browser-counts.json | 27 + .../browser-results.json | 1777 +++++++ .../sdpose-document-evidence/browser.txt | 1501 ++++++ .../sdpose-document-evidence/build.txt | 4 + .../build_definition.py | 490 ++ .../sdpose-document-evidence/check-exits.json | 26 + .../check_sdpose_gap.py | 59 + .../definition-0.json | 836 ++++ .../delivery-summary.md | 36 + .../sdpose-document-evidence/fetch_sources.py | 107 + .../fixed-source-index.json | 347 ++ .../sdpose-document-evidence/format.txt | 1 + .../import-protection.json | 69 + .../lint-development-failure.txt | 45 + .../hel-892/sdpose-document-evidence/lint.txt | 1 + .../sdpose-document-evidence/node-check.txt | 0 .../package-check.json | 23 + .../sdpose-document-evidence/pins.json | 3 + .../sdpose-document-evidence/rebuild.py | 64 + .../sdpose-document-evidence/recompute.py | 383 ++ .../sdpose-document-evidence/recompute.txt | 1 + .../sdpose-document-evidence/render_report.py | 111 + .../sdpose-document-evidence/repeat.py | 50 + .../repeatability.json | 15 + .../repeatability.txt | 3 + .../review-delta.json | 15 + .../sdpose-gap-scan.json | 2591 ++++++++++ .../sdpose-gap-scan.txt | 1 + .../source-check.json | 40 + .../source-graph.json | 280 ++ .../tested-files.json | 317 ++ .../tests-added-development-failure.txt | 78 + .../tests-new-development-failure.txt | 72 + .../sdpose-document-evidence/tests-new.txt | 4 + .../sdpose-document-evidence/tests.txt | 35 + .../validation-commands.txt | 21 + .../sdpose-reference/core0150-commit.json | 1 + .../sdpose-reference/core0150-tag.json | 1 + .../sdpose-reference/core0150__LICENSE | 674 +++ .../core0150__comfy__utils.py | 1428 ++++++ .../core0150__comfy_api__latest___io.py | 2227 +++++++++ ...50__comfy_extras__nodes_post_processing.py | 679 +++ .../sdpose-reference/core0150__nodes.py | 2516 ++++++++++ .../sdpose-reference/core0151-commit.json | 1 + .../sdpose-reference/core0151-tag.json | 1 + .../sdpose-reference/core0151__LICENSE | 674 +++ ..._comfy_api__latest___input__video_types.py | 128 + ...y_api__latest___input_impl__video_types.py | 464 ++ ...151__comfy_api__latest___util____init__.py | 14 + ...__comfy_api__latest___util__video_types.py | 52 + .../core0151__comfy_extras__nodes_video.py | 272 ++ .../core0151__folder_paths.py | 496 ++ .../sdpose-reference/frontend-commit.json | 1 + .../sdpose-reference/frontend-tag.json | 1 + .../sdpose-reference/frontend__LICENSE | 674 +++ ...c__core__graph__widgets__dynamicWidgets.ts | 600 +++ ...ontend__src__extensions__core__noteNode.ts | 84 + ...d__src__lib__litegraph__src__LGraphNode.ts | 4229 +++++++++++++++++ ...ib__litegraph__src__widgets__BaseWidget.ts | 386 ++ ...gets__composables__useImageUploadWidget.ts | 126 + .../frontend__src__utils__executionUtil.ts | 157 + docs/hel-892/sdpose-reference/identity.json | 35 + docs/hel-892/sdpose-reference/sources.json | 175 + e2e/run-sdpose-document.py | 78 + e2e/sdpose-document.mjs | 97 + 81 files changed, 29634 insertions(+), 6 deletions(-) create mode 100644 calliope-backend/tests/test_sdpose_fixed_document.py create mode 100644 docs/hel-892/SDPose视频骨架图固定参考中文说明.md create mode 100644 docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-310.pyc create mode 100644 docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-311.pyc create mode 100644 docs/hel-892/sdpose-document-evidence/__pycache__/rebuild.cpython-311.pyc create mode 100644 docs/hel-892/sdpose-document-evidence/actual-sdpose_视频人物姿势骨架提取.json create mode 100644 docs/hel-892/sdpose-document-evidence/audit-summary.json create mode 100644 docs/hel-892/sdpose-document-evidence/boundaries.json create mode 100644 docs/hel-892/sdpose-document-evidence/brief.md create mode 100644 docs/hel-892/sdpose-document-evidence/browser-counts.json create mode 100644 docs/hel-892/sdpose-document-evidence/browser-results.json create mode 100644 docs/hel-892/sdpose-document-evidence/browser.txt create mode 100644 docs/hel-892/sdpose-document-evidence/build.txt create mode 100644 docs/hel-892/sdpose-document-evidence/build_definition.py create mode 100644 docs/hel-892/sdpose-document-evidence/check-exits.json create mode 100644 docs/hel-892/sdpose-document-evidence/check_sdpose_gap.py create mode 100644 docs/hel-892/sdpose-document-evidence/definition-0.json create mode 100644 docs/hel-892/sdpose-document-evidence/delivery-summary.md create mode 100644 docs/hel-892/sdpose-document-evidence/fetch_sources.py create mode 100644 docs/hel-892/sdpose-document-evidence/fixed-source-index.json create mode 100644 docs/hel-892/sdpose-document-evidence/format.txt create mode 100644 docs/hel-892/sdpose-document-evidence/import-protection.json create mode 100644 docs/hel-892/sdpose-document-evidence/lint-development-failure.txt create mode 100644 docs/hel-892/sdpose-document-evidence/lint.txt create mode 100644 docs/hel-892/sdpose-document-evidence/node-check.txt create mode 100644 docs/hel-892/sdpose-document-evidence/package-check.json create mode 100644 docs/hel-892/sdpose-document-evidence/pins.json create mode 100644 docs/hel-892/sdpose-document-evidence/rebuild.py create mode 100644 docs/hel-892/sdpose-document-evidence/recompute.py create mode 100644 docs/hel-892/sdpose-document-evidence/recompute.txt create mode 100644 docs/hel-892/sdpose-document-evidence/render_report.py create mode 100644 docs/hel-892/sdpose-document-evidence/repeat.py create mode 100644 docs/hel-892/sdpose-document-evidence/repeatability.json create mode 100644 docs/hel-892/sdpose-document-evidence/repeatability.txt create mode 100644 docs/hel-892/sdpose-document-evidence/review-delta.json create mode 100644 docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.json create mode 100644 docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.txt create mode 100644 docs/hel-892/sdpose-document-evidence/source-check.json create mode 100644 docs/hel-892/sdpose-document-evidence/source-graph.json create mode 100644 docs/hel-892/sdpose-document-evidence/tested-files.json create mode 100644 docs/hel-892/sdpose-document-evidence/tests-added-development-failure.txt create mode 100644 docs/hel-892/sdpose-document-evidence/tests-new-development-failure.txt create mode 100644 docs/hel-892/sdpose-document-evidence/tests-new.txt create mode 100644 docs/hel-892/sdpose-document-evidence/tests.txt create mode 100644 docs/hel-892/sdpose-document-evidence/validation-commands.txt create mode 100644 docs/hel-892/sdpose-reference/core0150-commit.json create mode 100644 docs/hel-892/sdpose-reference/core0150-tag.json create mode 100644 docs/hel-892/sdpose-reference/core0150__LICENSE create mode 100644 docs/hel-892/sdpose-reference/core0150__comfy__utils.py create mode 100644 docs/hel-892/sdpose-reference/core0150__comfy_api__latest___io.py create mode 100644 docs/hel-892/sdpose-reference/core0150__comfy_extras__nodes_post_processing.py create mode 100644 docs/hel-892/sdpose-reference/core0150__nodes.py create mode 100644 docs/hel-892/sdpose-reference/core0151-commit.json create mode 100644 docs/hel-892/sdpose-reference/core0151-tag.json create mode 100644 docs/hel-892/sdpose-reference/core0151__LICENSE create mode 100644 docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input__video_types.py create mode 100644 docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py create mode 100644 docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util____init__.py create mode 100644 docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util__video_types.py create mode 100644 docs/hel-892/sdpose-reference/core0151__comfy_extras__nodes_video.py create mode 100644 docs/hel-892/sdpose-reference/core0151__folder_paths.py create mode 100644 docs/hel-892/sdpose-reference/frontend-commit.json create mode 100644 docs/hel-892/sdpose-reference/frontend-tag.json create mode 100644 docs/hel-892/sdpose-reference/frontend__LICENSE create mode 100644 docs/hel-892/sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts create mode 100644 docs/hel-892/sdpose-reference/frontend__src__extensions__core__noteNode.ts create mode 100644 docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts create mode 100644 docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__widgets__BaseWidget.ts create mode 100644 docs/hel-892/sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts create mode 100644 docs/hel-892/sdpose-reference/frontend__src__utils__executionUtil.ts create mode 100644 docs/hel-892/sdpose-reference/identity.json create mode 100644 docs/hel-892/sdpose-reference/sources.json create mode 100644 e2e/run-sdpose-document.py create mode 100644 e2e/sdpose-document.mjs diff --git a/calliope-backend/src/calliope/comfyui/fixed_document.py b/calliope-backend/src/calliope/comfyui/fixed_document.py index 877dc698..577afd03 100644 --- a/calliope-backend/src/calliope/comfyui/fixed_document.py +++ b/calliope-backend/src/calliope/comfyui/fixed_document.py @@ -15,6 +15,11 @@ DEFINITION_SHA256 = "c4c7f04fde29dc7485a341207397fcf6191e3fcbe89ecc2d238f4a4f5bc # Explicit path allowlist; a recomputed caller-supplied digest cannot extend trust. DEFINITIONS = { + ( + "example_ComfyUI_workflows/0-基础处理:图像合并-音频" + "分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨" + "架提取.json" + ): "b551c868f57456de9ca37e8b3f622eab95c070947ab45fd1f7b4b26cbf077bd7", ( "example_ComfyUI_workflows/0-基础处理:图像合并-音频" "分离-视频截取合并-图像视频放大/提示词生成与反推/gemma4_提示词反推(图" diff --git a/calliope-backend/src/calliope/comfyui/source_reviews.json b/calliope-backend/src/calliope/comfyui/source_reviews.json index 3b5f3375..86e4af47 100644 --- a/calliope-backend/src/calliope/comfyui/source_reviews.json +++ b/calliope-backend/src/calliope/comfyui/source_reviews.json @@ -5450,7 +5450,843 @@ "scope": [ "结构及用途局部审校", "源具名参数/注释/连线/素材模型用途人工语义局部审校" - ] + ], + "fixed_version_document": { + "source_path": "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json", + "source_sha1": "df93eb64dcb9ea46d761f5822b68766383f8536a", + "source_sha256": "4586c72d8a906d4a956fb7d62307b81e57e4e345324c7e73f63103e56bfffd14", + "canonical_sha256": "dae110f5eb678ef378c44b3c8dc980297676008410dc82b3d55d78542394bcad", + "notice": "固定版本参考说明;SDPose准确版本定义缺失且夹带不同流程缓存,环境及效果未核对,转换仍关闭。", + "user_overview": "这张图拟从视频画面提取并绘制人物骨架,再合成视频;音频和原FPS有直连路径,保存30不能当最终帧率。固定官方0.15.0缺少SDPose定义,夹带不同流程缓存,不能作为当前图执行依据;模型、素材和环境未核对,转换仍关闭。", + "versions": [ + "源声明v0.15.0(core0150)=b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "源声明v0.15.1(core0151)=3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "源声明v1.39.19(frontend)=d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "SDPose的core0.15.0注册/schema缺口保留;官方参考不证明feature/av_inference分叉安装或UE7.7.1钩子顺序。" + ], + "counts": { + "saved_fields": 18, + "linked_saved_fields": 1, + "frontend_only": 1, + "source_notes": 1, + "source_nodes": 9, + "physical_edges": 10, + "source_named_unconfirmed": 8, + "final_scalars": 0, + "final_prompt_constructed": false + }, + "fields": [ + { + "field": "draw_body", + "label": "身体绘制开关(源字段名)", + "type": "BOOLEAN", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向身体绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/0", + "value": true, + "json_type": "bool", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "draw_hands", + "label": "手部绘制开关(源字段名)", + "type": "BOOLEAN", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向手部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/1", + "value": true, + "json_type": "bool", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "draw_face", + "label": "面部绘制开关(源字段名)", + "type": "BOOLEAN", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向面部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/2", + "value": true, + "json_type": "bool", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "draw_feet", + "label": "脚部绘制开关(源字段名)", + "type": "BOOLEAN", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向脚部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/3", + "value": true, + "json_type": "bool", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "stick_width", + "label": "骨架线宽(源字段名)", + "type": "INT", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向骨架线宽,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/4", + "value": 4, + "json_type": "int", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "face_point_size", + "label": "面部点大小(源字段名)", + "type": "INT", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向面部点大小,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/5", + "value": 2, + "json_type": "int", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "score_threshold", + "label": "置信分数阈值(源字段名)", + "type": "FLOAT", + "schema_default": "未知:准确版本未找到节点定义,现值不是schema默认", + "unit": "未知:未找到准确实现,不确认像素/分数单位", + "limits": "未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围", + "effect": "源字段名指向置信阈值,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + "evidence": [ + 1 + ], + "role": "source_named_unconfirmed", + "node_id": "686", + "definition_node_id": "686", + "class_type": "SDPoseDrawKeypoints", + "scope": "root", + "pointer": "/nodes/0/widgets_values/6", + "value": 0.5, + "json_type": "float", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "batch_size", + "label": "提取批大小(源字段名)", + "type": "INT", + "schema_default": "未知:未找到准确版本schema", + "unit": "未知:不可确证批次元素的实现单位", + "limits": "源保存整数16;默认/合法最小最大/步进均未知", + "effect": "按源名记录batch_size=16,不当视频总帧数或最终FPS。固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。model/VAE/image为物理输入;可选bboxes未接,但不据此声称默认全图/单人/自动检测。未找到准确函数,bboxes默认行为、MODEL/VAE具体使用、速度及显存均未知。", + "evidence": [ + 1, + 0 + ], + "role": "source_named_unconfirmed", + "node_id": "684", + "definition_node_id": "684", + "class_type": "SDPoseKeypointExtractor", + "scope": "root", + "pointer": "/nodes/1/widgets_values/0", + "value": 16, + "json_type": "int", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "filename_prefix", + "label": "视频文件名前缀", + "type": "STRING", + "schema_default": "video/ComfyUI", + "unit": "相对前缀字符串", + "limits": "固定输出目录内子目录/计数规则;不是已核对的服务器绝对路径", + "effect": "源video/ComfyUI按参考实现拆子目录和文件名,加五位计数与_.mp4;前缀支持固定代码列出的%width%/%height%/日期时间替换。SaveVideo调用目标输出目录,未核对目标目录配置或真正文件。未禁用元数据时合并hidden extra_pnginfo与prompt;源extra.prompt是不同流程缓存,本轮绝不把它传入执行或声称实际写入元数据。没有第四个色彩控件。", + "evidence": [ + 8, + 12, + 9 + ], + "role": "scalar", + "node_id": "680", + "definition_node_id": "680", + "class_type": "SaveVideo", + "scope": "root", + "pointer": "/nodes/3/widgets_values/0", + "value": "video/ComfyUI", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "format", + "label": "视频封装格式", + "type": "COMBO", + "schema_default": "auto", + "unit": "格式选择", + "limits": "auto/mp4;两者后缀mp4", + "effect": "当前auto。当前链路由Create构成VideoFromComponents,固定save_to仅接受AUTO或MP4,AUTO时不显式传format,由.mp4后缀交PyAV选封装;不能套用VideoFromFile直接复制/重封装分支。未真正保存,实际编解码库、输出文件与播放情况未知。", + "evidence": [ + 8, + 9, + 10 + ], + "role": "scalar", + "node_id": "680", + "definition_node_id": "680", + "class_type": "SaveVideo", + "scope": "root", + "pointer": "/nodes/3/widgets_values/1", + "value": "auto", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "codec", + "label": "视频编码器选择", + "type": "COMBO", + "schema_default": "auto", + "unit": "编码器选择", + "limits": "auto/h264", + "effect": "当前auto。固定VideoFromComponents检查仅AUTO/H264,随后调用h264流、yuv420p;有音频时按视频帧数/FPS对应样本上限截取并用AAC编码。参考实现行为不证明目标编码器可用,也不承诺真实音频存在、同步或效果;不添加新版本编码/色彩选项。", + "evidence": [ + 8, + 9, + 10 + ], + "role": "scalar", + "node_id": "680", + "definition_node_id": "680", + "class_type": "SaveVideo", + "scope": "root", + "pointer": "/nodes/3/widgets_values/2", + "value": "auto", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "ckpt_name", + "label": "骨架模型Checkpoint引用", + "type": "COMBO", + "schema_default": "动态checkpoints文件列表,无固定文件默认", + "unit": "文件名", + "limits": "目标checkpoints列表未知;未读取权重", + "effect": "保持sdpose_wholebody_fp16.safetensors。固定加载器返回MODEL/CLIP/VAE三槽;MODEL槽0和VAE槽2接提取器,CLIP槽1未接。VAE通常用于图像与潜空间编解码是加载器说明,本图提取器如何使用它因准确版本定义缺失而未知;文件名/模型URL不证明权重存在、兼容或实际效果。", + "evidence": [ + 0, + 1 + ], + "role": "scalar", + "node_id": "682", + "definition_node_id": "682", + "class_type": "CheckpointLoaderSimple", + "scope": "root", + "pointer": "/nodes/5/widgets_values/0", + "value": "sdpose_wholebody_fp16.safetensors", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "file", + "label": "输入视频引用", + "type": "COMBO", + "schema_default": "动态输入目录视频列表,无固定文件默认", + "unit": "文件名", + "limits": "参考定义按视频内容类型筛选,执行使用annotated filepath;未读取本视频", + "effect": "保留原长中文文件名,不访问媒体。固定实现返回VideoFromFile引用;真实视频尺寸、长度、帧数、FPS、音频存在性未知。Load679经1737到拆分685,不能将文件名当已加载证明。", + "evidence": [ + 7, + 11 + ], + "role": "scalar", + "node_id": "679", + "definition_node_id": "679", + "class_type": "LoadVideo", + "scope": "root", + "pointer": "/nodes/6/widgets_values/0", + "value": "@小镜子(闺蜜的网课) 今天教大家如何在喜欢的人面前吃鸡蛋,好烫啊.mp4", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "upload", + "label": "上传按钮保存占位", + "type": "IMAGEUPLOAD", + "schema_default": "官方按钮构造值image;后端没有upload参数", + "unit": "无(前端按钮状态)", + "limits": "源image原样;options.serialize=false与widget.serialize分开", + "effect": "image是上传按钮占位,不是另一张输入图或已上传证明。固定前端API检查options.serialize跳过按钮,工作流保存/恢复检查widget.serialize;未在真实前端执行恢复/上传,UE钩子顺序未知。", + "evidence": [ + 18, + 15, + 13, + 14, + 16 + ], + "role": "frontend", + "node_id": "679", + "definition_node_id": "679", + "class_type": "LoadVideo", + "scope": "root", + "pointer": "/nodes/6/widgets_values/1", + "value": "image", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "resize_type", + "label": "缩放方式:按长边", + "type": "DYNAMICCOMBO", + "schema_default": "schema无显式default,选项首项scale dimensions;源实际选择scale longer dimension", + "unit": "分支选择", + "limits": "只解释当前长边分支;不是scale dimensions的宽高/裁剪布局", + "effect": "当前选择scale longer dimension,只生成resize_type.longer_size子控件。固定前端setter重建子项,以限定名加入并在主控件后插入;保存/恢复消费顺序有明确参考契约,但UE7.7.1与目标恢复未知,不把此说明升级为可靠转换或生成prompt。", + "evidence": [ + 2, + 6, + 17, + 13, + 14 + ], + "role": "scalar", + "node_id": "683", + "definition_node_id": "683", + "class_type": "ResizeImageMaskNode", + "scope": "root", + "pointer": "/nodes/7/widgets_values/0", + "value": "scale longer dimension", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "resize_type.longer_size", + "label": "目标长边", + "type": "INT", + "schema_default": "512", + "unit": "像素", + "limits": "仅长边分支:schema 0~16384、step=1;0或极端比例可产生零尺寸,函数未夹到最小1,不保证有效", + "effect": "现值1024。IMAGE输入[N,H,W,C]转通道优先,长边设为1024,短边按原比例round;正方形两边同值。common_upscale使用disabled裁剪再还原维度;不补另两个宽高控件。schema允许0不证明能运行;真实输入尺寸未知,不计算输出尺寸或承诺比例绝对无误差。", + "evidence": [ + 2, + 3, + 5, + 4, + 17 + ], + "role": "scalar", + "node_id": "683", + "definition_node_id": "683", + "class_type": "ResizeImageMaskNode", + "scope": "root", + "pointer": "/nodes/7/widgets_values/1", + "value": 1024, + "json_type": "int", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "scale_method", + "label": "图像重采样方式", + "type": "COMBO", + "schema_default": "area", + "unit": "算法选择", + "limits": "nearest-exact/bilinear/area/bicubic/lanczos", + "effect": "源选lanczos,固定实现经PIL LANCZOS重采样,浮点图像转uint8再还原;这是尺寸重采样,不是加载超分模型,也不能保证细节恢复。音频没有经过此节点。", + "evidence": [ + 2, + 4 + ], + "role": "scalar", + "node_id": "683", + "definition_node_id": "683", + "class_type": "ResizeImageMaskNode", + "scope": "root", + "pointer": "/nodes/7/widgets_values/2", + "value": "lanczos", + "json_type": "str", + "execution_note": "源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + }, + { + "field": "fps", + "label": "视频帧率保存缓存(外线覆盖)", + "type": "FLOAT", + "schema_default": "30.0", + "unit": "帧/秒", + "limits": "schema 1.0~120.0、step=1.0;源JSON整数30,实际有link1740", + "effect": "保存30不是最终FPS。GetVideoComponents685槽2经link1740接Create681.fps;固定前端先写控件后写解析连线,同键外线覆盖缓存。参考Create将传入fps转Fraction,本图最终取值来源是视频拆分输出,未读取原视频,不能声称已读到原FPS。UE widget_ue_connectable.fps=true,目标钩子顺序未知;音画同步与实际时长未验证。", + "evidence": [ + 7, + 16, + 10 + ], + "role": "linked_saved", + "node_id": "681", + "definition_node_id": "681", + "class_type": "CreateVideo", + "scope": "root", + "pointer": "/nodes/8/widgets_values/0", + "value": 30, + "json_type": "int", + "execution_note": "源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。" + } + ], + "sources": [ + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "nodes.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py", + "local_file": "../sdpose-reference/core0150__nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4", + "lines": [ + 587, + 608 + ], + "claim": "CheckpointLoaderSimple静态schema和MODEL/CLIP/VAE输出槽" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "nodes.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py", + "local_file": "../sdpose-reference/core0150__nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4", + "lines": [ + 2347, + 2458 + ], + "claim": "固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_post_processing.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py", + "local_file": "../sdpose-reference/core0150__comfy_extras__nodes_post_processing.py", + "sha256": "220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4", + "lines": [ + 407, + 502 + ], + "claim": "动态长边分支schema、默认、限定成员与执行分支" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_post_processing.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py", + "local_file": "../sdpose-reference/core0150__comfy_extras__nodes_post_processing.py", + "sha256": "220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4", + "lines": [ + 251, + 324 + ], + "claim": "IMAGE/MASK维度变换及长短边比例、round与不裁剪" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy/utils.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy/utils.py", + "local_file": "../sdpose-reference/core0150__comfy__utils.py", + "sha256": "feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286", + "lines": [ + 994, + 1035 + ], + "claim": "lanczos为PIL重采样、uint8往返;不是模型超分" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "nodes.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py", + "local_file": "../sdpose-reference/core0150__nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4", + "lines": [ + 57, + 57 + ], + "claim": "MAX_RESOLUTION=16384" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_io.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_api/latest/_io.py", + "local_file": "../sdpose-reference/core0150__comfy_api__latest___io.py", + "sha256": "babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c", + "lines": [ + 1091, + 1141 + ], + "claim": "DynamicCombo选项和嵌套schema展开" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_video.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py", + "local_file": "../sdpose-reference/core0151__comfy_extras__nodes_video.py", + "sha256": "1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575", + "lines": [ + 117, + 205 + ], + "claim": "CreateVideo/GetVideoComponents/LoadVideo准确schema和函数" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_video.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py", + "local_file": "../sdpose-reference/core0151__comfy_extras__nodes_video.py", + "sha256": "1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575", + "lines": [ + 68, + 114 + ], + "claim": "SaveVideo仅三个保存控件;前缀/元数据/后缀/save_to调用" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_util/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py", + "local_file": "../sdpose-reference/core0151__comfy_api__latest___util__video_types.py", + "sha256": "b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02", + "lines": [ + 8, + 39 + ], + "claim": "VideoContainer auto/mp4→mp4后缀与VideoCodec auto/h264" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_input_impl/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py", + "local_file": "../sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py", + "sha256": "df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5", + "lines": [ + 382, + 453 + ], + "claim": "本图CreateVideo构成VideoFromComponents;auto/h264、yuv420p、可选音频AAC和截取条件" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_input_impl/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py", + "local_file": "../sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py", + "sha256": "df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5", + "lines": [ + 235, + 305 + ], + "claim": "VideoFromFile拆帧与可选音频/帧率;未读真实媒体" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "folder_paths.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/folder_paths.py", + "local_file": "../sdpose-reference/core0151__folder_paths.py", + "sha256": "da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112", + "lines": [ + 428, + 473 + ], + "claim": "保存目录内前缀/变量替换、子目录与计数;不证明目标路径" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/lib/litegraph/src/LGraphNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "../sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033", + "lines": [ + 887, + 895 + ], + "claim": "按序恢复widgets_values,跳过widget.serialize=false" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/lib/litegraph/src/LGraphNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "../sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033", + "lines": [ + 942, + 950 + ], + "claim": "持久化独立检查widget.serialize,不等于options.serialize" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/lib/litegraph/src/LGraphNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "../sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033", + "lines": [ + 1898, + 1979 + ], + "claim": "addWidget把options保存在控件options" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/utils/executionUtil.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/utils/executionUtil.ts", + "local_file": "../sdpose-reference/frontend__src__utils__executionUtil.ts", + "sha256": "b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6", + "lines": [ + 92, + 133 + ], + "claim": "先控件值后解析连线写相同inputs键,外线覆盖fps缓存;options.serialize排除上传" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/core/graph/widgets/dynamicWidgets.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/core/graph/widgets/dynamicWidgets.ts", + "local_file": "../sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts", + "sha256": "f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e", + "lines": [ + 70, + 197 + ], + "claim": "动态分支setter重建及resize_type.longer_size限定名、插入顺序" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts", + "local_file": "../sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts", + "sha256": "77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d", + "lines": [ + 91, + 102 + ], + "claim": "上传按钮保存image占位;options.serialize=false" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/extensions/core/noteNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/extensions/core/noteNode.ts", + "local_file": "../sdpose-reference/frontend__src__extensions__core__noteNode.ts", + "sha256": "1014f719e3d67d9c5183a5e8631d4c2d6581dfe67083f32eb23774ec3074bef2", + "lines": [ + 1, + 84 + ], + "claim": "MarkdownNote前端注释,不是模型运行节点" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "LICENSE", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/LICENSE", + "local_file": "../sdpose-reference/core0150__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "lines": [ + 1, + 8 + ], + "claim": "固定官方GPL-3.0许可文本;只读,不安装或执行" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "LICENSE", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/LICENSE", + "local_file": "../sdpose-reference/core0151__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "lines": [ + 1, + 8 + ], + "claim": "固定官方GPL-3.0许可文本;只读,不安装或执行" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "LICENSE", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/LICENSE", + "local_file": "../sdpose-reference/frontend__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "lines": [ + 1, + 8 + ], + "claim": "固定官方GPL-3.0许可文本;只读,不安装或执行" + } + ], + "comments": [ + { + "node_id": "676", + "pointer": "/nodes/4/widgets_values/0", + "text": "## Model Links (for Local Users)\n\n**checkpoints**\n\n- [sdpose_wholebody_fp16.safetensors](https://huggingface.co/Comfy-Org/SDPose/resolve/main/checkpoints/sdpose_wholebody_fp16.safetensors)\n\n\n## Model Storage Location\n\n```\n📂 ComfyUI/\n├── 📂 models/\n│ └── 📂 checkpoints/\n│ └── sdpose_wholebody_fp16.safetensors\n```\n\n## Report Issue\n\nNote: Please update ComfyUI first ([guide](https://docs.comfy.org/installation/update_comfyui)) and prepare required models. Desktop/Cloud will be updated after the stable release; nightly-supported models may not be included yet, please wait for the next stable release.\n\n- Cannot run / runtime errors: [ComfyUI/issues](https://github.com/Comfy-Org/ComfyUI/issues)\n- UI / frontend issues: [ComfyUI_frontend/issues](https://github.com/Comfy-Org/ComfyUI_frontend/issues)\n- Workflow issues: [workflow_templates/issues](https://github.com/Comfy-Org/workflow_templates/issues)\n", + "evidence": [ + 19 + ], + "meaning": "作者模型链接、checkpoints存放路径和更新建议,仅源文本;不证明模型存在、已安装、可下载或需要立即操作。未访问权重链接,不建议停止TTS。" + } + ], + "flow": [ + "当前图9节点(8实体+注释676),10条物理边,无子图;全mode0。18保存位置+1注释另计,不代表最终运行标量数。", + "LoadVideo679→GetVideoComponents685经1737;685.images槽0经1736到Resize683,随后1734到Extractor684.image。MODEL682槽0经1732、VAE槽2经1733到Extractor684,CLIP槽1未接;684经1735到Draw686,Draw经1738到Create681.images。", + "685.audio槽1经1739直连Create681.audio,没有额外音频处理;685.fps槽2经1740直连Create681.fps。保存30是外线覆盖的缓存,不当最终FPS;Create681经1725到Save680。真实原FPS、音频存在性与同步未知。", + "Resize683当前scale longer dimension/1024/lanczos,动态限定名resize_type.longer_size;长边目标、短边round,IMAGE转换与不裁剪按0.15.0;不是0.17宽高五项,也不是模型超分。", + "固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。Draw的四开关true及4/2/0.5、Extractor的16只按源名说明;默认、范围、尺寸单位、bboxes未接行为与MODEL/VAE实际算法未知,不宣称全图检测或单人,不估算速度/显存。", + "GetVideoComponents685零保存位置:原JSON实际没有widgets_values键;读取get时为null/None,不能把缺键改成显式null或[]。固定参考有video输入、images/audio/fps三个出口,均有物理去向,未实际拆媒体。", + "混合源声明core0.15.0/0.15.1、frontend1.39.19;八实体UE7.7.1,Create.fps connectable=true,其余空映射不证明无UE影响。实际安装、UE身份/钩子顺序和动态模型成员未知,不删UE键或重写源图,不产prompt。", + "extra.prompt夹带LTXVGemmaCLIPModelLoader、LTXV*、VHS_VideoCombine等另一套历史API对象,与当前9个nodes不一致:夹带不同流程缓存,不能作为当前图执行依据。extra.comfy_fork_version=feature/av_inference@a6994ed1只是源保存声明,不能等同官方core安装;原字节及全图摘要保留缓存,不读取其提示词/路径作为当前输入,不增加活跃节点、不重开LTXV兼容调查。", + "Save680仅[video/ComfyUI,auto,auto]三个控件,依据0.15.1的枚举/auto/后缀/元数据和保存链;目标路径、实际编码器、文件、时长与骨架效果均未验证。注释作者更新/下载建议不是本轮操作指令。", + "源物理边:[1725, 681, 0, 680, 0, \"VIDEO\"]", + "源物理边:[1732, 682, 0, 684, 0, \"MODEL\"]", + "源物理边:[1733, 682, 2, 684, 1, \"VAE\"]", + "源物理边:[1734, 683, 0, 684, 2, \"IMAGE\"]", + "源物理边:[1735, 684, 0, 686, 0, \"POSE_KEYPOINT\"]", + "源物理边:[1736, 685, 0, 683, 0, \"IMAGE\"]", + "源物理边:[1737, 679, 0, 685, 0, \"VIDEO\"]", + "源物理边:[1738, 686, 0, 681, 0, \"IMAGE\"]", + "源物理边:[1739, 685, 1, 681, 1, \"AUDIO\"]", + "源物理边:[1740, 685, 2, 681, 2, \"FLOAT\"]", + "源节点686 SDPoseDrawKeypoints:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点684 SDPoseKeypointExtractor:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点685 GetVideoComponents:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点680 SaveVideo:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点676 MarkdownNote:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点682 CheckpointLoaderSimple:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点679 LoadVideo:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点683 ResizeImageMaskNode:mode=0;UE={\"widget_ue_connectable\": {}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}", + "源节点681 CreateVideo:mode=0;UE={\"widget_ue_connectable\": {\"fps\": true}, \"version\": \"7.7.1\", \"input_ue_unconnectable\": {}}" + ], + "flow_evidence": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 + ], + "zero_saved_nodes": [ + { + "node_id": "685", + "class_type": "GetVideoComponents", + "evidence": [ + 7, + 11 + ], + "effect": "GetVideoComponents685零保存位置:原JSON实际没有widgets_values键;读取get时为null/None,不能把缺键改成显式null或[]。固定参考有video输入、images/audio/fps三个出口,均有物理去向,未实际拆媒体。" + } + ], + "steps": [ + "这张图拟从视频画面提取并绘制人物骨架,再合成视频;音频和原FPS有直连路径,保存30不能当最终帧率。固定官方0.15.0缺少SDPose定义,夹带不同流程缓存,不能作为当前图执行依据;模型、素材和环境未核对,转换仍关闭。", + "先查看视频引用、模型引用和保存的实际连线;不读取媒体/权重,不把注释链接当安装证明。", + "逐项比较源现值与固定默认;先注意SDPose八项schema缺口、长边动态分支、FPS外线覆盖及不同流程缓存。", + "保持停用、未检查、未定稿、未实跑;真实环境/模型/媒体/效果均待核对,不执行或生成prompt。" + ] + } }, "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/加载图片合成视频.json": { "source_sha": "c7ef94870dc39bc22b42009141e393702c478ee6", diff --git a/calliope-backend/tests/test_background_fixed_document.py b/calliope-backend/tests/test_background_fixed_document.py index a8b8e131..3c887601 100644 --- a/calliope-backend/tests/test_background_fixed_document.py +++ b/calliope-backend/tests/test_background_fixed_document.py @@ -201,10 +201,11 @@ def test_ten_documents_only_gain_overview_and_new_block_is_independent(): "图像合并成四宫格.json", "图像分割-多宫格分割.json", "gemma4_提示词反推(图像视频音频).json", + "sdpose_视频人物姿势骨架提取.json", ) ) ] - assert len(additions) == 3 + assert len(additions) == 4 for p in additions: now[p].pop("fixed_version_document") historical = [p for p in DEFINITIONS if p not in additions] diff --git a/calliope-backend/tests/test_controlnet_fixed_document.py b/calliope-backend/tests/test_controlnet_fixed_document.py index 6178b434..95547053 100644 --- a/calliope-backend/tests/test_controlnet_fixed_document.py +++ b/calliope-backend/tests/test_controlnet_fixed_document.py @@ -203,7 +203,7 @@ def test_graph_specific_semantics_and_companion(): def test_other_documents_and_block_swaps(): - assert len(DEFINITIONS) == 14 + assert len(DEFINITIONS) == 15 for path in DEFINITIONS: if path == PATH: continue diff --git a/calliope-backend/tests/test_gemma_fixed_document.py b/calliope-backend/tests/test_gemma_fixed_document.py index ac98d363..4cfc4e6a 100644 --- a/calliope-backend/tests/test_gemma_fixed_document.py +++ b/calliope-backend/tests/test_gemma_fixed_document.py @@ -153,7 +153,10 @@ def test_real_document_and_frozen_old_thirteen_blocks(): resource = "calliope-backend/src/calliope/comfyui/source_reviews.json" old = json.loads(subprocess.check_output(["git", "show", "9dac1b4:" + resource], cwd=REPO)) now = json.loads((REPO / resource).read_bytes()) - assert len(now) == 156 and len(DEFINITIONS) == 14 + # SDPose is independently frozen against 7291887 in its own suite. + sdpose = next(p for p in now if p.endswith("sdpose_视频人物姿势骨架提取.json")) + now[sdpose].pop("fixed_version_document") + assert len(now) == 156 and len(DEFINITIONS) == 15 assert len([r for r in old.values() if "fixed_version_document" in r]) == 13 assert ( sum( diff --git a/calliope-backend/tests/test_grid_fixed_document.py b/calliope-backend/tests/test_grid_fixed_document.py index c3ea4fc1..9da9100c 100644 --- a/calliope-backend/tests/test_grid_fixed_document.py +++ b/calliope-backend/tests/test_grid_fixed_document.py @@ -171,10 +171,13 @@ def test_only_two_reviews_change_and_all_old_blocks_preserved(): resource = "calliope-backend/src/calliope/comfyui/source_reviews.json" old = json.loads(subprocess.check_output(["git", "show", "27e6d56:" + resource], cwd=REPO)) now = json.loads((REPO / resource).read_bytes()) + # SDPose is independently frozen against 7291887 in its own suite. + sdpose = next(p for p in now if p.endswith("sdpose_视频人物姿势骨架提取.json")) + now[sdpose].pop("fixed_version_document") # Gemma addition is independently protected against 9dac1b4 in its own suite. gemma = next(p for p in now if p.endswith("gemma4_提示词反推(图像视频音频).json")) now[gemma].pop("fixed_version_document") - assert len(DEFINITIONS) == 14 + assert len(DEFINITIONS) == 15 assert ( sum( len(r["fixed_version_document"]["fields"]) diff --git a/calliope-backend/tests/test_qwen_edit_fixed_document.py b/calliope-backend/tests/test_qwen_edit_fixed_document.py index 0af8df99..a2e84c52 100644 --- a/calliope-backend/tests/test_qwen_edit_fixed_document.py +++ b/calliope-backend/tests/test_qwen_edit_fixed_document.py @@ -244,10 +244,11 @@ def test_old_nine_blocks_and_other_editorial_content_preserved(): "图像合并成四宫格.json", "图像分割-多宫格分割.json", "gemma4_提示词反推(图像视频音频).json", + "sdpose_视频人物姿势骨架提取.json", ) ) ] - assert len(additions) == 3 + assert len(additions) == 4 for p in additions: now[p].pop("fixed_version_document") for entry in now.values(): diff --git a/calliope-backend/tests/test_sdpose_fixed_document.py b/calliope-backend/tests/test_sdpose_fixed_document.py new file mode 100644 index 00000000..6933c85b --- /dev/null +++ b/calliope-backend/tests/test_sdpose_fixed_document.py @@ -0,0 +1,262 @@ +"""Exact SDPose source binding, real document output, old definitions and refusal regressions.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import subprocess +from pathlib import Path + +import pytest +from calliope.comfyui.fixed_document import DEFINITIONS, canonical +from calliope.comfyui.library import build_document +from calliope.comfyui.source_reviews import review_for + +REPO = Path(__file__).resolve().parents[2] +OUT = REPO / "docs/hel-892/sdpose-document-evidence" +PATH = next(p for p in DEFINITIONS if p.endswith("sdpose_视频人物姿势骨架提取.json")) +RAW = (REPO / PATH).read_bytes() +SOURCE = json.loads(RAW) +REVIEW = review_for(PATH, hashlib.sha1(RAW).hexdigest()) +BLOCK = REVIEW["fixed_version_document"] + + +def pointer(obj, path): + for part in path.strip("/").split("/"): + part = part.replace("~1", "/").replace("~0", "~") + obj = obj[int(part)] if isinstance(obj, list) else obj[part] + return obj + + +def doc(source=None, review=None, path=PATH): + return build_document( + path, + SOURCE if source is None else source, + None, + None, + [], + REVIEW if review is None else review, + ) + + +@pytest.mark.parametrize("field", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"]) +def test_saved_values_types_and_fixed_citations(field): + v = pointer(SOURCE, field["pointer"]) + assert canonical(v) == canonical(field["value"]) and type(v).__name__ == field["json_type"] + node = pointer(SOURCE, field["pointer"].split("/widgets_values/")[0]) + assert str(node["id"]) == field["node_id"] and node["type"] == field["class_type"] + assert node["properties"]["ver"] in ["0.15.0", "0.15.1"] + for k in ["label", "schema_default", "unit", "limits", "effect", "execution_note"]: + assert field[k] + for k in field["evidence"]: + e = BLOCK["sources"][k] + raw = (OUT / e["local_file"]).read_bytes() + assert hashlib.sha256(raw).hexdigest() == e["sha256"] + assert len(e["commit"]) == 40 and e["commit"] in e["url"] + assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines()) + + +@pytest.mark.parametrize("index", range(18)) +@pytest.mark.parametrize("kind", ["value", "type", "pointer", "citation", "role", "default"]) +def test_forged_fields_fail_even_after_caller_digest_recalculation(index, kind): + source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW) + b = review["fixed_version_document"] + f = b["fields"][index] + if kind in ["value", "type"]: + parent, _, key = f["pointer"].rpartition("/") + pointer(source, parent)[int(key)] = ( + {"forged": True} if kind == "value" else (1 if isinstance(f["value"], bool) else False) + ) + # Even when source and editorial field are forged consistently, trust cannot expand. + f["value"] = pointer(source, f["pointer"]) + f["json_type"] = type(f["value"]).__name__ + elif kind == "citation": + b["sources"][f["evidence"][0]]["sha256"] = "0" * 64 + else: + f[{"default": "schema_default"}.get(kind, kind)] = "forged" + b["canonical_sha256"] = hashlib.sha256(canonical(source)).hexdigest() + review["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest() + actual = doc(source, review)["fixed_version"] + assert actual["matched"] is False and "fields" not in actual + + +MUTATIONS = ( + [ + "/links/0/1", + "/links/9/2", + "/extra/frontendVersion", + "/extra/comfy_fork_version", + "/extra/prompt", + "/nodes/4/widgets_values/0", + "/nodes/5/properties/models/0/url", + "/nodes/8/properties/ue_properties/widget_ue_connectable/fps", + ] + + [ + f"/nodes/{i}/{suffix}" + for i in range(9) + for suffix in ["mode", "type", "properties/ue_properties/version"] + ] + + [ + f"/nodes/{i}/properties/{key}" + for i in [0, 1, 2, 3, 5, 6, 7, 8] + for key in ["cnr_id", "ver"] + ] +) + + +@pytest.mark.parametrize("path", MUTATIONS) +def test_versions_providers_modes_edges_notes_and_model_metadata_fail_closed(path): + source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW) + parent, _, key = path.rpartition("/") + target = pointer(source, parent) + target[int(key) if isinstance(target, list) else key] = "forged" + review["fixed_version_document"]["canonical_sha256"] = hashlib.sha256( + canonical(source) + ).hexdigest() + review["caller_digest"] = hashlib.sha256( + canonical(review["fixed_version_document"]) + ).hexdigest() + assert not doc(source, review)["fixed_version"]["matched"] + + +@pytest.mark.parametrize( + "key", + [ + "source_path", + "source_sha1", + "source_sha256", + "notice", + "user_overview", + "versions", + "comments", + "flow", + "sources", + ], +) +def test_editorial_and_identity_forgery_rejected(key): + review = copy.deepcopy(REVIEW) + review["fixed_version_document"][key] = "forged" + review["caller_digest"] = hashlib.sha256( + canonical(review["fixed_version_document"]) + ).hexdigest() + assert not doc(review=review)["fixed_version"]["matched"] + + +def test_real_document_and_frozen_old_fourteen_blocks(): + d = doc() + assert d["fixed_version"]["matched"] and d["fixed_version"]["fields"] == BLOCK["fields"] + assert d["status"] == dict(imported=True, doc_done=False, exec_verified=False) + assert d["dependencies"]["check_state"] == "unchecked" + assert "fixed_version" not in doc(path="untrusted.json") + review = copy.deepcopy(REVIEW) + other = next(p for p in DEFINITIONS if p != PATH) + resource = "calliope-backend/src/calliope/comfyui/source_reviews.json" + now = json.loads((REPO / resource).read_bytes()) + review["fixed_version_document"] = now[other]["fixed_version_document"] + assert not doc(review=review)["fixed_version"]["matched"] + old = json.loads(subprocess.check_output(["git", "show", "7291887:" + resource], cwd=REPO)) + assert len(now) == 156 and len(DEFINITIONS) == 15 + old_blocks = [ + r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r + ] + assert len(old_blocks) == 14 + assert sum(len(b["fields"]) for b in old_blocks) == 376 + assert ( + sum(len(b.get("comments", [])) for b in old_blocks) == 12 + ) # ASR history includes flow note. + assert now[PATH].pop("fixed_version_document") == BLOCK + assert now == old + + +def test_exact_topology_nulls_conditions_and_reference_identity(): + assert BLOCK["source_sha256"] == hashlib.sha256(RAW).hexdigest() + assert BLOCK["canonical_sha256"] == hashlib.sha256(canonical(SOURCE)).hexdigest() + assert len(SOURCE["nodes"]) == 9 and len(SOURCE["links"]) == 10 + assert [e[0] for e in SOURCE["links"]] == [ + 1725, + 1732, + 1733, + 1734, + 1735, + 1736, + 1737, + 1738, + 1739, + 1740, + ] + assert SOURCE["links"][-2:] == [ + [1739, 685, 1, 681, 1, "AUDIO"], + [1740, 685, 2, 681, 2, "FLOAT"], + ] + assert all(n["mode"] == 0 for n in SOURCE["nodes"]) + assert len(BLOCK["fields"]) == 18 and len(BLOCK["comments"]) == 1 + assert sum(f["role"] == "source_named_unconfirmed" for f in BLOCK["fields"]) == 8 + assert sum(f["role"] == "linked_saved" for f in BLOCK["fields"]) == 1 + for n in BLOCK["comments"]: + assert pointer(SOURCE, n["pointer"]) == n["text"] + assert "widgets_values" not in SOURCE["nodes"][2] + assert SOURCE["nodes"][2].get("widgets_values") is None + assert BLOCK["zero_saved_nodes"][0]["node_id"] == "685" + fields = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]} + assert fields["681", "fps"]["value"] == 30 and fields["681", "fps"]["json_type"] == "int" + assert fields["683", "resize_type.longer_size"]["value"] == 1024 + assert [f["value"] for f in BLOCK["fields"] if f["node_id"] == "686"] == [ + True, + True, + True, + True, + 4, + 2, + 0.5, + ] + assert {e["commit"] for e in BLOCK["sources"]} == { + "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + } + assert all( + t in "".join(BLOCK["flow"]) + for t in [ + "外线覆盖", + "未知", + "不同流程缓存", + "未找到", + "UE7.7.1", + "没有widgets_values键", + "bboxes", + "不产prompt", + ] + ) + assert not BLOCK["counts"]["final_prompt_constructed"] + + +@pytest.mark.parametrize("missing_value", [None, []]) +def test_absent_widgets_key_cannot_be_replaced_by_null_or_empty_list(missing_value): + source = copy.deepcopy(SOURCE) + source["nodes"][2]["widgets_values"] = missing_value + assert not doc(source=source)["fixed_version"]["matched"] + + +def test_wrong_raw_source_sha_cannot_receive_fixed_reference(): + assert review_for(PATH, "0" * 40) is None + review = copy.deepcopy(REVIEW) + review["source_sha"] = "0" * 40 + assert not doc(review=review)["fixed_version"]["matched"] + + +def test_missing_packages_give_chinese_build_hint(tmp_path): + import sys + + code = ( + "import runpy,sys; from pathlib import Path; " + "ns=runpy.run_path('recompute.py'); " + "ns['require_packages'].__globals__['REPO']=Path(sys.argv[1]); " + "ns['require_packages']()" + ) + result = subprocess.run( + [sys.executable, "-c", code, str(tmp_path)], cwd=OUT, capture_output=True, text=True + ) + assert result.returncode != 0 + assert "缺少wheel/sdist包产物" in result.stderr + assert "uv build --project calliope-backend --offline" in result.stderr diff --git a/docs/hel-892/SDPose视频骨架图固定参考中文说明.md b/docs/hel-892/SDPose视频骨架图固定参考中文说明.md new file mode 100644 index 00000000..c9970d55 --- /dev/null +++ b/docs/hel-892/SDPose视频骨架图固定参考中文说明.md @@ -0,0 +1,582 @@ +# SDPose视频骨架图固定参考中文说明 + +18新保存位置+1新注释;旧14图376保存位置+13注释逐对象不变。15图394位置+14注释展示,155定稿0、实跑0、新增转换0。 + +复用SQLite来源库→正常GET详情→现有说明抽屉;仅新增source_reviews说明块和显式受信摘要,不改变转换/执行链。 + +## sdpose_视频人物姿势骨架提取 + +这张图拟从视频画面提取并绘制人物骨架,再合成视频;音频和原FPS有直连路径,保存30不能当最终帧率。固定官方0.15.0缺少SDPose定义,夹带不同流程缓存,不能作为当前图执行依据;模型、素材和环境未核对,转换仍关闭。 + +固定版本参考说明;SDPose准确版本定义缺失且夹带不同流程缓存,环境及效果未核对,转换仍关闭。 + +源路径:`example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json` + +SHA1:df93eb64dcb9ea46d761f5822b68766383f8536a + +原字节SHA256:4586c72d8a906d4a956fb7d62307b81e57e4e345324c7e73f63103e56bfffd14 + +规范全图SHA256:dae110f5eb678ef378c44b3c8dc980297676008410dc82b3d55d78542394bcad + +源声明v0.15.0(core0150)=b874bd2b8c324d58cfc37bff0754dd16815a8f3c + +源声明v0.15.1(core0151)=3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f + +源声明v1.39.19(frontend)=d91c283b7b758787b4d29126c1a9ac39dc14d6a7 + +SDPose的core0.15.0注册/schema缺口保留;官方参考不证明feature/av_inference分叉安装或UE7.7.1钩子顺序。 + +### 具体连线与处理条件 + +当前图9节点(8实体+注释676),10条物理边,无子图;全mode0。18保存位置+1注释另计,不代表最终运行标量数。 + +LoadVideo679→GetVideoComponents685经1737;685.images槽0经1736到Resize683,随后1734到Extractor684.image。MODEL682槽0经1732、VAE槽2经1733到Extractor684,CLIP槽1未接;684经1735到Draw686,Draw经1738到Create681.images。 + +685.audio槽1经1739直连Create681.audio,没有额外音频处理;685.fps槽2经1740直连Create681.fps。保存30是外线覆盖的缓存,不当最终FPS;Create681经1725到Save680。真实原FPS、音频存在性与同步未知。 + +Resize683当前scale longer dimension/1024/lanczos,动态限定名resize_type.longer_size;长边目标、短边round,IMAGE转换与不裁剪按0.15.0;不是0.17宽高五项,也不是模型超分。 + +固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。Draw的四开关true及4/2/0.5、Extractor的16只按源名说明;默认、范围、尺寸单位、bboxes未接行为与MODEL/VAE实际算法未知,不宣称全图检测或单人,不估算速度/显存。 + +GetVideoComponents685零保存位置:原JSON实际没有widgets_values键;读取get时为null/None,不能把缺键改成显式null或[]。固定参考有video输入、images/audio/fps三个出口,均有物理去向,未实际拆媒体。 + +混合源声明core0.15.0/0.15.1、frontend1.39.19;八实体UE7.7.1,Create.fps connectable=true,其余空映射不证明无UE影响。实际安装、UE身份/钩子顺序和动态模型成员未知,不删UE键或重写源图,不产prompt。 + +extra.prompt夹带LTXVGemmaCLIPModelLoader、LTXV*、VHS_VideoCombine等另一套历史API对象,与当前9个nodes不一致:夹带不同流程缓存,不能作为当前图执行依据。extra.comfy_fork_version=feature/av_inference@a6994ed1只是源保存声明,不能等同官方core安装;原字节及全图摘要保留缓存,不读取其提示词/路径作为当前输入,不增加活跃节点、不重开LTXV兼容调查。 + +Save680仅[video/ComfyUI,auto,auto]三个控件,依据0.15.1的枚举/auto/后缀/元数据和保存链;目标路径、实际编码器、文件、时长与骨架效果均未验证。注释作者更新/下载建议不是本轮操作指令。 + +源物理边:[1725, 681, 0, 680, 0, "VIDEO"] + +源物理边:[1732, 682, 0, 684, 0, "MODEL"] + +源物理边:[1733, 682, 2, 684, 1, "VAE"] + +源物理边:[1734, 683, 0, 684, 2, "IMAGE"] + +源物理边:[1735, 684, 0, 686, 0, "POSE_KEYPOINT"] + +源物理边:[1736, 685, 0, 683, 0, "IMAGE"] + +源物理边:[1737, 679, 0, 685, 0, "VIDEO"] + +源物理边:[1738, 686, 0, 681, 0, "IMAGE"] + +源物理边:[1739, 685, 1, 681, 1, "AUDIO"] + +源物理边:[1740, 685, 2, 681, 2, "FLOAT"] + +源节点686 SDPoseDrawKeypoints:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点684 SDPoseKeypointExtractor:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点685 GetVideoComponents:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点680 SaveVideo:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点676 MarkdownNote:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点682 CheckpointLoaderSimple:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点679 LoadVideo:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点683 ResizeImageMaskNode:mode=0;UE={"widget_ue_connectable": {}, "version": "7.7.1", "input_ue_unconnectable": {}} + +源节点681 CreateVideo:mode=0;UE={"widget_ue_connectable": {"fps": true}, "version": "7.7.1", "input_ue_unconnectable": {}} + +### 使用与核对 + +这张图拟从视频画面提取并绘制人物骨架,再合成视频;音频和原FPS有直连路径,保存30不能当最终帧率。固定官方0.15.0缺少SDPose定义,夹带不同流程缓存,不能作为当前图执行依据;模型、素材和环境未核对,转换仍关闭。 + +先查看视频引用、模型引用和保存的实际连线;不读取媒体/权重,不把注释链接当安装证明。 + +逐项比较源现值与固定默认;先注意SDPose八项schema缺口、长边动态分支、FPS外线覆盖及不同流程缓存。 + +保持停用、未检查、未定稿、未实跑;真实环境/模型/媒体/效果均待核对,不执行或生成prompt。 + +### 逐保存位置说明 + +#### 1. 节点686 · 身体绘制开关(源字段名)(draw_body) + +源字段名指向身体绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +true +``` + +类:SDPoseDrawKeypoints;JSON类型:bool;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/0` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 2. 节点686 · 手部绘制开关(源字段名)(draw_hands) + +源字段名指向手部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +true +``` + +类:SDPoseDrawKeypoints;JSON类型:bool;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/1` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 3. 节点686 · 面部绘制开关(源字段名)(draw_face) + +源字段名指向面部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +true +``` + +类:SDPoseDrawKeypoints;JSON类型:bool;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/2` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 4. 节点686 · 脚部绘制开关(源字段名)(draw_feet) + +源字段名指向脚部绘制,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +true +``` + +类:SDPoseDrawKeypoints;JSON类型:bool;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/3` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 5. 节点686 · 骨架线宽(源字段名)(stick_width) + +源字段名指向骨架线宽,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +4 +``` + +类:SDPoseDrawKeypoints;JSON类型:int;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/4` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 6. 节点686 · 面部点大小(源字段名)(face_point_size) + +源字段名指向面部点大小,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +2 +``` + +类:SDPoseDrawKeypoints;JSON类型:int;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/5` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 7. 节点686 · 置信分数阈值(源字段名)(score_threshold) + +源字段名指向置信阈值,原值按源保存;固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。 + +```json +0.5 +``` + +类:SDPoseDrawKeypoints;JSON类型:float;角色:source_named_unconfirmed。 + +源位置:`/nodes/0/widgets_values/6` + +定义默认:未知:准确版本未找到节点定义,现值不是schema默认;单位:未知:未找到准确实现,不确认像素/分数单位 + +范围/条件:未知:布尔/整数/浮点是源输入声明和保存类型,非已核实合法范围 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 8. 节点684 · 提取批大小(源字段名)(batch_size) + +按源名记录batch_size=16,不当视频总帧数或最终FPS。固定官方core0.15.0未找到SDPoseDrawKeypoints/SDPoseKeypointExtractor的注册、schema或函数。源cnr_id=comfy-core与ver=0.15.0仅保存声明,不能证明此官方版本提供该节点;不借其他版本补定义。model/VAE/image为物理输入;可选bboxes未接,但不据此声称默认全图/单人/自动检测。未找到准确函数,bboxes默认行为、MODEL/VAE具体使用、速度及显存均未知。 + +```json +16 +``` + +类:SDPoseKeypointExtractor;JSON类型:int;角色:source_named_unconfirmed。 + +源位置:`/nodes/1/widgets_values/0` + +定义默认:未知:未找到准确版本schema;单位:未知:不可确证批次元素的实现单位 + +范围/条件:源保存整数16;默认/合法最小最大/步进均未知 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py +- [0] CheckpointLoaderSimple静态schema和MODEL/CLIP/VAE输出槽;nodes.py 587~608行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 9. 节点680 · 视频文件名前缀(filename_prefix) + +源video/ComfyUI按参考实现拆子目录和文件名,加五位计数与_.mp4;前缀支持固定代码列出的%width%/%height%/日期时间替换。SaveVideo调用目标输出目录,未核对目标目录配置或真正文件。未禁用元数据时合并hidden extra_pnginfo与prompt;源extra.prompt是不同流程缓存,本轮绝不把它传入执行或声称实际写入元数据。没有第四个色彩控件。 + +```json +"video/ComfyUI" +``` + +类:SaveVideo;JSON类型:str;角色:scalar。 + +源位置:`/nodes/3/widgets_values/0` + +定义默认:video/ComfyUI;单位:相对前缀字符串 + +范围/条件:固定输出目录内子目录/计数规则;不是已核对的服务器绝对路径 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [8] SaveVideo仅三个保存控件;前缀/元数据/后缀/save_to调用;comfy_extras/nodes_video.py 68~114行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py +- [12] 保存目录内前缀/变量替换、子目录与计数;不证明目标路径;folder_paths.py 428~473行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/folder_paths.py +- [9] VideoContainer auto/mp4→mp4后缀与VideoCodec auto/h264;comfy_api/latest/_util/video_types.py 8~39行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py + +#### 10. 节点680 · 视频封装格式(format) + +当前auto。当前链路由Create构成VideoFromComponents,固定save_to仅接受AUTO或MP4,AUTO时不显式传format,由.mp4后缀交PyAV选封装;不能套用VideoFromFile直接复制/重封装分支。未真正保存,实际编解码库、输出文件与播放情况未知。 + +```json +"auto" +``` + +类:SaveVideo;JSON类型:str;角色:scalar。 + +源位置:`/nodes/3/widgets_values/1` + +定义默认:auto;单位:格式选择 + +范围/条件:auto/mp4;两者后缀mp4 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [8] SaveVideo仅三个保存控件;前缀/元数据/后缀/save_to调用;comfy_extras/nodes_video.py 68~114行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py +- [9] VideoContainer auto/mp4→mp4后缀与VideoCodec auto/h264;comfy_api/latest/_util/video_types.py 8~39行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py +- [10] 本图CreateVideo构成VideoFromComponents;auto/h264、yuv420p、可选音频AAC和截取条件;comfy_api/latest/_input_impl/video_types.py 382~453行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +#### 11. 节点680 · 视频编码器选择(codec) + +当前auto。固定VideoFromComponents检查仅AUTO/H264,随后调用h264流、yuv420p;有音频时按视频帧数/FPS对应样本上限截取并用AAC编码。参考实现行为不证明目标编码器可用,也不承诺真实音频存在、同步或效果;不添加新版本编码/色彩选项。 + +```json +"auto" +``` + +类:SaveVideo;JSON类型:str;角色:scalar。 + +源位置:`/nodes/3/widgets_values/2` + +定义默认:auto;单位:编码器选择 + +范围/条件:auto/h264 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [8] SaveVideo仅三个保存控件;前缀/元数据/后缀/save_to调用;comfy_extras/nodes_video.py 68~114行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py +- [9] VideoContainer auto/mp4→mp4后缀与VideoCodec auto/h264;comfy_api/latest/_util/video_types.py 8~39行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py +- [10] 本图CreateVideo构成VideoFromComponents;auto/h264、yuv420p、可选音频AAC和截取条件;comfy_api/latest/_input_impl/video_types.py 382~453行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +#### 12. 节点682 · 骨架模型Checkpoint引用(ckpt_name) + +保持sdpose_wholebody_fp16.safetensors。固定加载器返回MODEL/CLIP/VAE三槽;MODEL槽0和VAE槽2接提取器,CLIP槽1未接。VAE通常用于图像与潜空间编解码是加载器说明,本图提取器如何使用它因准确版本定义缺失而未知;文件名/模型URL不证明权重存在、兼容或实际效果。 + +```json +"sdpose_wholebody_fp16.safetensors" +``` + +类:CheckpointLoaderSimple;JSON类型:str;角色:scalar。 + +源位置:`/nodes/5/widgets_values/0` + +定义默认:动态checkpoints文件列表,无固定文件默认;单位:文件名 + +范围/条件:目标checkpoints列表未知;未读取权重 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [0] CheckpointLoaderSimple静态schema和MODEL/CLIP/VAE输出槽;nodes.py 587~608行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py +- [1] 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 2347~2458行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +#### 13. 节点679 · 输入视频引用(file) + +保留原长中文文件名,不访问媒体。固定实现返回VideoFromFile引用;真实视频尺寸、长度、帧数、FPS、音频存在性未知。Load679经1737到拆分685,不能将文件名当已加载证明。 + +```json +"@小镜子(闺蜜的网课) 今天教大家如何在喜欢的人面前吃鸡蛋,好烫啊.mp4" +``` + +类:LoadVideo;JSON类型:str;角色:scalar。 + +源位置:`/nodes/6/widgets_values/0` + +定义默认:动态输入目录视频列表,无固定文件默认;单位:文件名 + +范围/条件:参考定义按视频内容类型筛选,执行使用annotated filepath;未读取本视频 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [7] CreateVideo/GetVideoComponents/LoadVideo准确schema和函数;comfy_extras/nodes_video.py 117~205行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py +- [11] VideoFromFile拆帧与可选音频/帧率;未读真实媒体;comfy_api/latest/_input_impl/video_types.py 235~305行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +#### 14. 节点679 · 上传按钮保存占位(upload) + +image是上传按钮占位,不是另一张输入图或已上传证明。固定前端API检查options.serialize跳过按钮,工作流保存/恢复检查widget.serialize;未在真实前端执行恢复/上传,UE钩子顺序未知。 + +```json +"image" +``` + +类:LoadVideo;JSON类型:str;角色:frontend。 + +源位置:`/nodes/6/widgets_values/1` + +定义默认:官方按钮构造值image;后端没有upload参数;单位:无(前端按钮状态) + +范围/条件:源image原样;options.serialize=false与widget.serialize分开 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [18] 上传按钮保存image占位;options.serialize=false;src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts 91~102行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts +- [15] addWidget把options保存在控件options;src/lib/litegraph/src/LGraphNode.ts 1898~1979行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts +- [13] 按序恢复widgets_values,跳过widget.serialize=false;src/lib/litegraph/src/LGraphNode.ts 887~895行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts +- [14] 持久化独立检查widget.serialize,不等于options.serialize;src/lib/litegraph/src/LGraphNode.ts 942~950行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts +- [16] 先控件值后解析连线写相同inputs键,外线覆盖fps缓存;options.serialize排除上传;src/utils/executionUtil.ts 92~133行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/utils/executionUtil.ts + +#### 15. 节点683 · 缩放方式:按长边(resize_type) + +当前选择scale longer dimension,只生成resize_type.longer_size子控件。固定前端setter重建子项,以限定名加入并在主控件后插入;保存/恢复消费顺序有明确参考契约,但UE7.7.1与目标恢复未知,不把此说明升级为可靠转换或生成prompt。 + +```json +"scale longer dimension" +``` + +类:ResizeImageMaskNode;JSON类型:str;角色:scalar。 + +源位置:`/nodes/7/widgets_values/0` + +定义默认:schema无显式default,选项首项scale dimensions;源实际选择scale longer dimension;单位:分支选择 + +范围/条件:只解释当前长边分支;不是scale dimensions的宽高/裁剪布局 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [2] 动态长边分支schema、默认、限定成员与执行分支;comfy_extras/nodes_post_processing.py 407~502行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py +- [6] DynamicCombo选项和嵌套schema展开;comfy_api/latest/_io.py 1091~1141行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_api/latest/_io.py +- [17] 动态分支setter重建及resize_type.longer_size限定名、插入顺序;src/core/graph/widgets/dynamicWidgets.ts 70~197行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/core/graph/widgets/dynamicWidgets.ts +- [13] 按序恢复widgets_values,跳过widget.serialize=false;src/lib/litegraph/src/LGraphNode.ts 887~895行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts +- [14] 持久化独立检查widget.serialize,不等于options.serialize;src/lib/litegraph/src/LGraphNode.ts 942~950行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts + +#### 16. 节点683 · 目标长边(resize_type.longer_size) + +现值1024。IMAGE输入[N,H,W,C]转通道优先,长边设为1024,短边按原比例round;正方形两边同值。common_upscale使用disabled裁剪再还原维度;不补另两个宽高控件。schema允许0不证明能运行;真实输入尺寸未知,不计算输出尺寸或承诺比例绝对无误差。 + +```json +1024 +``` + +类:ResizeImageMaskNode;JSON类型:int;角色:scalar。 + +源位置:`/nodes/7/widgets_values/1` + +定义默认:512;单位:像素 + +范围/条件:仅长边分支:schema 0~16384、step=1;0或极端比例可产生零尺寸,函数未夹到最小1,不保证有效 + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [2] 动态长边分支schema、默认、限定成员与执行分支;comfy_extras/nodes_post_processing.py 407~502行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py +- [3] IMAGE/MASK维度变换及长短边比例、round与不裁剪;comfy_extras/nodes_post_processing.py 251~324行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py +- [5] MAX_RESOLUTION=16384;nodes.py 57~57行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py +- [4] lanczos为PIL重采样、uint8往返;不是模型超分;comfy/utils.py 994~1035行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy/utils.py +- [17] 动态分支setter重建及resize_type.longer_size限定名、插入顺序;src/core/graph/widgets/dynamicWidgets.ts 70~197行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/core/graph/widgets/dynamicWidgets.ts + +#### 17. 节点683 · 图像重采样方式(scale_method) + +源选lanczos,固定实现经PIL LANCZOS重采样,浮点图像转uint8再还原;这是尺寸重采样,不是加载超分模型,也不能保证细节恢复。音频没有经过此节点。 + +```json +"lanczos" +``` + +类:ResizeImageMaskNode;JSON类型:str;角色:scalar。 + +源位置:`/nodes/7/widgets_values/2` + +定义默认:area;单位:算法选择 + +范围/条件:nearest-exact/bilinear/area/bicubic/lanczos + +源保存位置;mode=0,源声明core0.15.0。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [2] 动态长边分支schema、默认、限定成员与执行分支;comfy_extras/nodes_post_processing.py 407~502行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py +- [4] lanczos为PIL重采样、uint8往返;不是模型超分;comfy/utils.py 994~1035行;commit b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy/utils.py + +#### 18. 节点681 · 视频帧率保存缓存(外线覆盖)(fps) + +保存30不是最终FPS。GetVideoComponents685槽2经link1740接Create681.fps;固定前端先写控件后写解析连线,同键外线覆盖缓存。参考Create将传入fps转Fraction,本图最终取值来源是视频拆分输出,未读取原视频,不能声称已读到原FPS。UE widget_ue_connectable.fps=true,目标钩子顺序未知;音画同步与实际时长未验证。 + +```json +30 +``` + +类:CreateVideo;JSON类型:int;角色:linked_saved。 + +源位置:`/nodes/8/widgets_values/0` + +定义默认:30.0;单位:帧/秒 + +范围/条件:schema 1.0~120.0、step=1.0;源JSON整数30,实际有link1740 + +源保存位置;mode=0,源声明core0.15.1。官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。 + +依据: +- [7] CreateVideo/GetVideoComponents/LoadVideo准确schema和函数;comfy_extras/nodes_video.py 117~205行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py +- [16] 先控件值后解析连线写相同inputs键,外线覆盖fps缓存;options.serialize排除上传;src/utils/executionUtil.ts 92~133行;commit d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/utils/executionUtil.ts +- [10] 本图CreateVideo构成VideoFromComponents;auto/h264、yuv420p、可选音频AAC和截取条件;comfy_api/latest/_input_impl/video_types.py 382~453行;commit 3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +### 零保存节点与源注释 + +685 GetVideoComponents:GetVideoComponents685零保存位置:原JSON实际没有widgets_values键;读取get时为null/None,不能把缺键改成显式null或[]。固定参考有video输入、images/audio/fps三个出口,均有物理去向,未实际拆媒体。 + +节点676,位置`/nodes/4/widgets_values/0` + +作者模型链接、checkpoints存放路径和更新建议,仅源文本;不证明模型存在、已安装、可下载或需要立即操作。未访问权重链接,不建议停止TTS。 + +```text +## Model Links (for Local Users) + +**checkpoints** + +- [sdpose_wholebody_fp16.safetensors](https://huggingface.co/Comfy-Org/SDPose/resolve/main/checkpoints/sdpose_wholebody_fp16.safetensors) + + +## Model Storage Location + +``` +📂 ComfyUI/ +├── 📂 models/ +│ └── 📂 checkpoints/ +│ └── sdpose_wholebody_fp16.safetensors +``` + +## Report Issue + +Note: Please update ComfyUI first ([guide](https://docs.comfy.org/installation/update_comfyui)) and prepare required models. Desktop/Cloud will be updated after the stable release; nightly-supported models may not be included yet, please wait for the next stable release. + +- Cannot run / runtime errors: [ComfyUI/issues](https://github.com/Comfy-Org/ComfyUI/issues) +- UI / frontend issues: [ComfyUI_frontend/issues](https://github.com/Comfy-Org/ComfyUI_frontend/issues) +- Workflow issues: [workflow_templates/issues](https://github.com/Comfy-Org/workflow_templates/issues) + +``` + +### 固定原件索引 + +0. CheckpointLoaderSimple静态schema和MODEL/CLIP/VAE输出槽;nodes.py 第587~608行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +1. 固定0.15.0内置扩展清单未列SDPose;不能据源cnr_id/ver确认其schema;nodes.py 第2347~2458行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +2. 动态长边分支schema、默认、限定成员与执行分支;comfy_extras/nodes_post_processing.py 第407~502行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py + +3. IMAGE/MASK维度变换及长短边比例、round与不裁剪;comfy_extras/nodes_post_processing.py 第251~324行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py + +4. lanczos为PIL重采样、uint8往返;不是模型超分;comfy/utils.py 第994~1035行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy/utils.py + +5. MAX_RESOLUTION=16384;nodes.py 第57~57行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py + +6. DynamicCombo选项和嵌套schema展开;comfy_api/latest/_io.py 第1091~1141行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_api/latest/_io.py + +7. CreateVideo/GetVideoComponents/LoadVideo准确schema和函数;comfy_extras/nodes_video.py 第117~205行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py + +8. SaveVideo仅三个保存控件;前缀/元数据/后缀/save_to调用;comfy_extras/nodes_video.py 第68~114行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py + +9. VideoContainer auto/mp4→mp4后缀与VideoCodec auto/h264;comfy_api/latest/_util/video_types.py 第8~39行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py + +10. 本图CreateVideo构成VideoFromComponents;auto/h264、yuv420p、可选音频AAC和截取条件;comfy_api/latest/_input_impl/video_types.py 第382~453行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +11. VideoFromFile拆帧与可选音频/帧率;未读真实媒体;comfy_api/latest/_input_impl/video_types.py 第235~305行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py + +12. 保存目录内前缀/变量替换、子目录与计数;不证明目标路径;folder_paths.py 第428~473行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/folder_paths.py + +13. 按序恢复widgets_values,跳过widget.serialize=false;src/lib/litegraph/src/LGraphNode.ts 第887~895行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts + +14. 持久化独立检查widget.serialize,不等于options.serialize;src/lib/litegraph/src/LGraphNode.ts 第942~950行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts + +15. addWidget把options保存在控件options;src/lib/litegraph/src/LGraphNode.ts 第1898~1979行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts + +16. 先控件值后解析连线写相同inputs键,外线覆盖fps缓存;options.serialize排除上传;src/utils/executionUtil.ts 第92~133行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/utils/executionUtil.ts + +17. 动态分支setter重建及resize_type.longer_size限定名、插入顺序;src/core/graph/widgets/dynamicWidgets.ts 第70~197行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/core/graph/widgets/dynamicWidgets.ts + +18. 上传按钮保存image占位;options.serialize=false;src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts 第91~102行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts + +19. MarkdownNote前端注释,不是模型运行节点;src/extensions/core/noteNode.ts 第1~84行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 1014f719e3d67d9c5183a5e8631d4c2d6581dfe67083f32eb23774ec3074bef2;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/extensions/core/noteNode.ts + +20. 固定官方GPL-3.0许可文本;只读,不安装或执行;LICENSE 第1~8行;提交b874bd2b8c324d58cfc37bff0754dd16815a8f3c;SHA256 3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/LICENSE + +21. 固定官方GPL-3.0许可文本;只读,不安装或执行;LICENSE 第1~8行;提交3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f;SHA256 3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986;https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/LICENSE + +22. 固定官方GPL-3.0许可文本;只读,不安装或执行;LICENSE 第1~8行;提交d91c283b7b758787b4d29126c1a9ac39dc14d6a7;SHA256 3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986;https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/LICENSE diff --git a/docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-310.pyc b/docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e23054e2b26fe55e30cbd720033fb081a971e023 GIT binary patch literal 18564 zcmch933OD~nPzP&Er`X~2IEy;W7(jR01HSPCxpc&W{UwQ!Esj?x=&J>QkDD`4C+!M z5ZXXOGKf_IBo?#SNW#XT6?OMaX6tRHr>Cd;&GgK4Qm>ZTJaf7yImbyi^ZoaKRVo&{ z&zzhy#(H}9zPtSQzyJQ*A!fe=^?Lg&sal)J8PL&yBeie@EN+=^NatTDUH)q3|Eyb=co%6qRezVwZ7Aj%Q zP!)ebs|W_od@Z8t{vFD0%`DKA+JG7W`ZYB3(0pc&FluTw(~EtG2nFcN*%=5K%4LT- z0~3CE*jF8?QGC0Cfk;inS7U_qU`0UUP^%48D4MTY356mH0+kCFEiPXy7A{<0g<{R>X_%K zck0fl^Dze@uimA*`#e!szq8)0=e*|?sBd#nU8_U5xJ^HpVxFVTY1ewvwe_AVN1Lm~ z(c)}zRk}rv@b1g2&xz&`3lQ;(X^lDcUb|cEmmd@liHA|n zm*qKPu6RVuL%G22|EPFWJcjZ#S$Bc2t{p*-C#KQCSo-#~eW zEWap<#Y^I4lxNEFe6c{32p`I`>~g6n6AMv(K$aJY#o`rFj`D1jmx!fenfRvoEtDU$ z%dd*%;x&{XvdiBR-xe!Sepr^jBUXx4Vl~QhWO%@ALACct^ zVx!n3zK8NW@zyHGy9M=+MsuQ%ip{7m7F!x~oR0VZJm_e1i&Trd(kb2+-`|&C|Csne z{o~??X#ePsJoQi1KUx1&eNpr=u`T*U^vUQ`;vMlL@ouz8{PtW&^zpe4;m7aXDyR6J z#sZA@-_bH4wu=fOgd!?Mm8h1jg48PNt#WZYw0ckM5Ft?`!XhGS#rsh&MsYRfJ019@ z3Qg$vX5iaS@j-NY^nt8zyToo$Cw^B%MZNfO^pWVp(FdasMdwrjrvwA~|3oy1Jz}qD z6#GPzXpZJZ3!`(XRaK5X!%swuXa$UIV!t>b+R-9EIxSidotxF7LmUJQouW&8C=Q`T zK?a7yqFWphN5wI5T$~Um0pFbHtSYzYvFGmmNidk20rv8&33x*^ncS2^)^ z?JPY%?aixyy2?@IaJlNAsee|_jk?8W^Bj#%?CEDea@9Xq|9td$aebace7?igyNcO843cJ1$>_V;%>P&=Dz`=*Hz$b%Q~oo4<6>Y>gTBhlw~I`Q^m^abHCsQpXS zp2pV;qfc{df(fM;8l7^U-=Y?Ju0DP0J9_^U@lQM4a*f}@8oz;`C+c5}KGT;MbhOes zFl+RQO4mHc1?SXCr`~M1erm7%pGCjX<2dDszNpWLzS!t|Z>IR?Xz?%RIe?dci8op~ z)`-%-I+Y{-us835Q{u(-{u?&z&j62qBv*MHus@5^MhX2%f?oV_eX;lx@u%Wni+>Y+ zT>KgM=--Mz7ynNDMOA+NOVO9azZZYG&w+jWt9g!9Sp5=*tTpXg>}I-F&yPCwS$z+X zwC$VS@4)+m+3)&8QDB9?iT@BS7XML>;i3NGudAGM9eTd_BS-}L_n*XnhGZBO|3&;w zM}G8~R#)`d=u7&;`W(Hm)z#>ve`x(P@dwP2fb-|TL#)G7<;2LAh>Jv(Ma*IRG|?R0o@0kgds-qtC+hM*f9-Ip zOQP=do1PQ(_IdjqeYyP@afeg;Cbe}s=-KKaGK%J0a0*gAm<8g@6?Ip+q8^dk>*meZ zb6Pz>YR)5MJ>+e;Lu-;YCF5xkEn_}j_CRaC`#?Q(rhxWr1!b!)ygTs@K@r;?rKVH4>{5Xlhv`w3+KBw5&ZKhwt5r%^*;T8)_7sYm z2M<@nOOCqdrRFbrH57rK*Ip~Z)=U*Lear&+-A@ymUadN?@Rjlu*-dp1m6W8dip;M1 zirwm?G-*zVj8QYEA`}SL6z7{BK%koisuB?X?Ynh+%B>D))uG^a^)YInU#;vC!74@5 zO?OBMn_i)ixde-WYEm?7_owUdCc*Hr&`KWWD)8ll}zuN^aFMfM}?YUi;S2z1! zT$y)TtBk zhCNzEwNewX4z;h}xN7w}-^z7sH~HRPu{wF{u+=gezc>+mIUhrv#KU+CLs>ne*1*Zq zlCoDyO0DLm#Kb_n?Xq?4NPM`->Npbby<)W<+q`NMjNmWEdt$>K$;OFz$3T3vt0JuW zgTe>XKG8pr95`<^-QcO~o`)Myx!aF@Q3IM!F2N5gTKCtg5%8rJ3|G;Tj$yNdzre%z z7QwOq5`a$~nM~dqf$1La9^}z}j>@s)7@uBFbOF|QYnS!m@!0Uec-zHfe>*o${R(3Q zSJ7yMptb8)yuRAEe#PcD6Jyt{(T}XosCW@vYSyAKRy`0)Nh?Wki5|ZC{xtC?xFQ7e&By=_2!N1wr*Lwal`Vm@= z1!{x7Pyj@%`~1NOA!#M14H`7}H_&_4?r@+cSOJG#UY$ z?0AOEtd@!Rk)hNo8cU_I*5I)j{-10d8*7RUx5b99#3oN!SC7XJUW|?10D7#pj>LF_ z&uVH!XAqRn>N-dj5x?;sjY%RO3 z@l*XkTI#=HmS7pp_gZ?DH1Hb8&-j66Yxp8ol|6(HRf&Twm=0W=92`sZp0Nf_TUQRn zCJxultc-*pIQ+HnxFwN)LaX^J8hs;1=iN&53|JFKAQjTP)pt3f= z!3K!C5?u>^KpgiIJS4}(+uN+s&iJ0Q*7=SPf}%>%HNSLqwJ*lolQ%z0PPTA$iKb9^ zB3P#^uY~4Nf&(2_`1qqIgTP<$K*fj_(zl#Iou zeuR-yO?Vgz9#&H;ceNVEL9EG(=i;Zkl9Q(sqmx$iiA2w^)zuy(n$%L=0|3@Ke-xjR zA2la>j#k!ciSff=Gwj1Xu*VM`N}V_#8{Quq@2h)};2|~R<1Mh!>JuzrcvTufN8FtH zDM9yLf=)_lTRtnguBecJ*4QW{tEy-~ykyFfP$XOh;-U(c*;ZEv2qxZn$ZEQf>L0~+ z)~zED5JUnMDk`u7>d+_<VqOjn$OUbwKah%WovB+@`&LiFyA3C zD+$accpDdydy#CWOek#COYni9Hy7LrwFDjP$Y&BqLKh%8kO{UY70#RBg?Tq zfXGPXgYX8lAQt&}F#g%4RLg#*p(*h{*#$k7+`l)mcLZik33{q!^dN;`=B``2a`lGI ztECKPZEOu3j~^X*ebc%Hi%Lq91H<6z_|X?EOVkI zB_v>T1-2_8(?bH+oWYWx0y_Z&l}wL;@Q#5yjMWZS!l?vU=ONW7A8%07Co$`oa zgx+_93n4rfLm2`&b#;9hlJ(~JDs?;~=v6dc0bLyLTPJO{~mw_Al!myvx9%K1Lj!vQaG!E@=WmRL0wGS*=5C^Q=+>AH1pTmZp~G=w)#A?^_GV0_8iaoy?_ z8w|2zvp>e$Tdb}Rv&X;;1#*V!Kv-yUig??BRO6+upF)*NuYSE6;=LLsgTxS= zgxF+1X#p61$6KMP?w!WWS+j2AimzG;kHCG+2k*mc#%dzF-YbbS7bv_hO-`Ew(j3Yh zz?2TANgNykAkf{AyUc~`H%Pgf87afxJR}Sv^kbH@-I&JC#PvQOFAg3M6ox?<%Zy+R zH(Ep8zW9;rSiLX)`2eIkiTcqla*lBNzF{)Lx?1C( z9Z9w~T0Ped@;UL{I(P=~LuX+m?h58MTJX{8>4Owt-;04{#^U}EI?Rk9S^#Uc9s=yB zWaPrlN#1Hi(Ha`H28Ve;(AMyP5=Yv3;qkV~3*+Y@HB!=sszqz^_Cm3Rx|tCaLksE!e(2vP;nj7YD%+?XihwB6WD;&=2Q^ z5*LRUdaLOY+z=nFbad30Y`H=fo7`DaMQPTtiC=nd7>vi}0br>B1P}m+4*-|dbQ9_# zHZcj0jOYr=h8*hs@#D8(YG#l^6f)=jfeEC2cGT*UZVYKbaqdj|##244@gtbQ%vrf{ z{dYDRuK+b{Z6cmw2Rk%aLGXkSkx2Gm0^IRqeXPZ~-sX2iHXL@tt`5V861yT<n)|Qo*Xn{&3Im1ZLX;`&wNbK)R zPE1%QF2Vh`dQRUNe1Qv$$O~qY)p#w1d;n_kwh;TtT!Fq=6UA##UB)|&;n6JBaMBtc z26Et&aPkrcM0}z*ad|X#?0RDSD7=J3ADpg1D+9&gb+#qgFU`zgeY7_=0ii~lX$?UB z^kvId7N&{uQS1D*WJCKDf*9{z9X<|dY<+7Ti6iOfG0un*dWk%&rg3Xvgbbj8)2S0p zQ_>?p6F`swHe)t6hH0Fcgty-)&+I#YWDnDB^7R}4E_LnPn`~(0b$~G6h( zyiu5pa9qA*Sz@fSY{{Y}Fk>k)(Ar$S^c5Sn#tCbvIRh{x6m$|34eut#FujI!uB2kR z*OOu=%A6)cY+E-$$**E&l}-!$T!?+78v3Blq)5Z!DC`37=+pjqZyS$}je1$`gwV)yOf8ARGJ+C9E4yKi6$b{VG}cB~y1uJJ!GiW~wg zlD(p|LrB|3+|&6{Y`DQ1?_<&fs}UXF{FJ+75M(pFbof?mTFY^Sdtld4nLxf?su1+1gj6e)K)fqZ4AAC!?<7>(7 zT_4bPkVkD!%kt6X?k2`B$GdOA*R;lADV`)?WdPPJT=l~ZE7q@F$+DOj%XVyz^^w>g z@3j3jK)`Xx)JI1VjU@k5DH1^(1dzTwaS{9qDGAUne&8~<;P}8)L!%Hgkjd3est(OK z*Z^1e;yL)!M5b*W3>vq>z`SL5&nR{MMC#+?J`U!RwRWw+co7oa9_4Gmpl#~BlIT8z zz+D!qvcnlbHHT-WI9u+HmK_YC?HIvev9Sx8@CTTTjKh%|*w)zam>uKkI><2*T95Pr z({yp8HFq8dGU*hRelc-cM!O-!G+n7(UWQedl1X%W4+#eukOye7(Tjj6)pLVQR@xM4 zs1Qq>M{ZzU-7AF@bMreJ=D#uj`}0@6i*-Yx zruH0;jUPv}4Z|?J$$?wI4Ru77og_fy5kf~oCi4VD&{xk9!%Uow4WFl6MOQoI9HxSI zUlR%Yjao^PtXD)(hOLB6i_IO$$>SK1a}rF$|OG=ELvIa*Wev^ZP*3AJd z!Yq`~`)d@vIwFjRX=~-ts!XDTg@x$}AX~r$F>nm#GP7;n%V7l{G@Jt3h0us^dyo=r z0h}E|Ym_Ps{2;?2Gbjc{6(Jtb)vf{9>8K33Wzb?su@tRav0>%5jhizNpcQ*v3>mhQ zGcRfE0x!wQ6C}1Wv7Q&uARXCazo_y<)|zlyED#fCt3mJ)qSG0nhWG5iHNn)?j(BzUvKbe^9*Z>| z9mWa5(-4%H0vo%A0&EBh)0WHp3WH5Y`QR#_x&Z3IS{To4=`gj+_O?wAe&YtHLRuu{D$I(a~nn=Q=V4@Fw1q-KnAqk7Jv8XT;KyVlIR}8Lg6h! zBHO!g>;|L@xH5I69sDaqjDNfDplI&+ME^T6xm4pPJ zck`CF)^2#cZu(A{u0wK(PDsiQlp+`$;dY4VB|d?0`P9IHQgAY*dKp7(R#R#xoy74$ zT)-krUfgH3p1^W!Ug40%;0OgddpoTC{cuxQZg6VH_!zW>eYgV<7!qkioEVw5COr*h zwbF|LKA{$4quq#G@a({wzXWMIA}_g8SOjpx81mQ{c{%XiAkP5K^D?CNyzlvHC0JFh zKkthlyAba^69>kRT~8;e_GZw_DMjADY#cDHP+SI!lsPNLO{%GblHpK~7?Wf^xt`cR zlCU4`A@?bryTpuqva~vg18HHLbVXp;UmLCphASgj5o=Z~322hvO1K833nUZ4e7+}f z=|EaI5UD3827qMRg8lp9rZG>j#{!6K0+wbKSdHw8G%N(5w6YVQARmcMypnAD)S9@Q zQ7WdlGNRT5boRgG;aF>E52X?M#$ne%up?h81v^*R_86VLNM}+dahy*!G;uN&+hr7G z>?>+SOwA_S;ai}RME5o3?ypIS+JfIs|H6iVz_B`yt=PI{BNn`V6X|4GICeu4CfT6C z3a^Fuvilm*jh)^dJ-=!9injqeFO8`gvK@JHY}_6GSEA=SO?4iDvl~9>3hu#HroG#8 z|5h&-y29Y1Mt*I9FRW9Y(TkZP#qw*)6Ybm zy>{*y^b7{hXfFr_9|R-`mCbN;+P;0>tlikN@0Wp z8l39c47{o&0oAwZ@qK#yfF9fEL8(Ke<>*ws`W`((TtSB!RGl6>sUlA$H%RrG3`u=IncQshJ~Bz^D|^HVd;;hAM?X>T>ynjIZv2bi&h4Zu?5j8LW@e>24JS z;4miffGY|9W8)=t_!cM_TbUi;!cmKE;yonaN#cUYj}9SEn;f8=F|ijkXF8>r*&QBl z3g-w7$P6RKCcAw203ux2f>duq5)$y^16Idp@xvW}g&Bnd9~=*2plB{gI61Gir#F7} z?3OJQ_$jsn2=cjNm;9?Ivuj|@`3 z=|&o@*j4A{Oq%_>O#J|ZY(dJBC^X( z5B)OeXgXGbMjY3tY>2TBl|<(<;=#I!DG=Txu)*}tYtJToMy7A;YKqs75hiULAx+X8 zMdyGVn|&0D>pTbe5OU%H;T>f>HP9q^T;}YlL-zhOS_^PMPSa#M9+}e$!eSI{)#=nB zpDqyaw;7r92wKCg7IYzF>`qW7a{

Wfz-vB2BuG1m-Kz5ZAwyl;;?P!Nz<7yEd?Fpo41+} zGxVX2Fq!P6nc*G|!`!)#P9++LZ9maV?yuBMv@#9>-a3UiItf4-kOr|MXAnQt1$Yw& z2d%S>kl<_{U9j1#HGqU@SA_vUFaybtyI%aq}<65AdOY@+C+MP~fqw z6bE|JF@6dYP#F7a7vKR5h~E?4!N%WPw)9TAJW$31!Ci#0gnn2POd^EB8C&cX;>-=5 z(V-m9UgK{8S|;p@xFF6z-7BDA?A!4|%#T8ejFf2AWh2FS+ zDe9-(5{8@B{lBqpT1mhV!3agux%o0CyQv=XJ4R%aDRuS~92A>a?VCjsA+Y~#cZj^H zy9dEn%$X)(@;kGR$?H4wSH!Onf3wQrdx$c8;}7 zP*4fL5yQ#jlrSZjWzip%zz>Q`IMe~t-;R_??;GEk2iZ5LHT@aZB=;LRyq+FDtw63A z@=uF>3w@;}uKxbZS!ujML`#Q`?Aj)>Ett1_l3{$Hcs|rgfu+uKL_w4qZDXNk9fTA7Au53=8*2D} z^4K9Q{Yxx8e)A@&h-{_GG=dGqLF6(_m_9IAR4j6-SA;*_V#7&>X~?8}a;lj@Qu z-8dUAQ`wG z3Lr#cTTy`s`t%Zhzx~E$zclq>=5I$-4M!C1e8q)h*1=}0^Hby^V5BFnv2HlX5?~oz zKxu$t`ABXgTdvc2ir+v{0%Z)pG{gMxz;^gyg;BhJc_mH|I^J5auC z*CtXELoGw@l2S?;eCT># z-YhZ5u?0tD89gW0Tz0B72rict;Fn5g6xE05LAO`4PWctQ8VYJUh^_XuVepQ;Gy0^X zZr)wz`ledRD6P5+j8G~(qXDy> z3)@?fb~9)DW5eBFBNW&UrZXRstiIkL{%XY2$ybT^2mdj|pYqzY<4q%&#RX1_2C57k z=muh2owMdZH*hiwZf_$6>33P)}=^TF&Wak_GP zS}Xb^;m~gMkT>0=Tr z;)o2zx%o5@DGicH&h;WGgD zq-=|4;+QGZ0v%q-6mYAq%$#n2;VX9LtjraBzg^>n;~%V0AdPT;!XJS$-x*XsF!OA! zPLUVfk)p%hOq(j*-KRT7HFV)0hq>vGGJv-5^kI>9x z9Ui6|)M~n6@v6_tVqLJ7gKT+zdDP7BSD&U29>Rk94E3YaCi1Thm>yCpW{w)bMTO#* z&72_aA?z|e5_@j=mk1q6e3}JFu+X(pM4;3KG+e<{n9a;nl`4#*?l!&bG|`AiSedzY z8W@qRz^-78QG*lie6<39rGZj5fC}7h=Fq}4m1Md49F30XJl)GNb1@!{mg9~g0yi4L z>c(vo+&GkfMFSTmw*&MFoXVw69*W$UZv3SP^(`v9s{*y^1{!k}JvP#Vh!mknWS2Dc z5>;HL3TIILkbZmlK8@*oj{`(`X(~{!P+L;TkOVK$`^)s0Pmk}>gH*ejBb6~}EX@Vs zoaZcb7U16;=WN`1oaJ)OEO2^myWCSp^gX|F<$hg>+RsA!|JQzBH|GD}Z+W>`yK9CE z|KFaK8F{aZSIwm)GU_ zg{$!H+Cmq`xKHcC`;Kw{+WU{3_Z86Pc|3oI)laQOzUAF_KC1Q3^yGV-Ui_mcF!H|& zW-m-EwkLlMXsZC<9zorc&KKmD8S-vzf$WQSXP)zMr}vk6w>`Iu zW&+c_pw7E-(0_=lC<{m=7D*EFuf9Kb2y zB#3{F*6BU|wfC>pzXUHp)WO zZJDea6Ecjl!RSJgAQFPCKm!tnnmR}wKc&YtdJNEm;?#1|EPIi-miaU9RT!a0NO_Im Zk+)?$jzU+Six_pbix%R!o#&n5`M)0L)8YUC literal 0 HcmV?d00001 diff --git a/docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-311.pyc b/docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0c3522b24a8c19d98793cde90b6cbdfec075495 GIT binary patch literal 23922 zcmb_^d2~}(nx|yRvb-;V!C=6w!7LVL3nU?l!xjizg(WE}DMk3ow!mASBo?<^5n+?T zU0UnW!h#u6SZcTNp<;YIdkU3oJ#enllfL&gde=YjZQ}n-A@#SXt#kR!I zBa6=oJ*u`O{j0}I4h^y;h3QJwTT)rVKGl{qmdNz`)LYV-W`im}spc0;$}E*;t2xii zEVe4iVk*y*%q3>YTv=?MnYXpdUdi%oRe82Db6#;(MRmE^X3n#kc9>aSsbs1yo0(T> z-eH#V%)89RcAIHyxw#-n^X99)$)?K6Dx1k>sj9TD#dqy`ldUXBn6OiO^S!~a-^`VX7&a7ty1s@oQRc5seinp@hd zTF@E)i@%n*&{OokvAh7v#IIexF+c7n^~|5tujFgIDdtM6T{0U@)?$mrn`o_)Y{u>8 z-Bxds)m&|oOdy>V&9nroH=fxms;yofXjsL}Kz;lUQ@P!2CD`(QI&LVdsxTXNSxi+G zRfYKaJT zpF^qII9oz!Je6u&n97d0SPf9Cv2kr9+HNBb;(v_KbZEx&N2!~^;{IGnV&`L;$l4Cg zeBtQYf8FS{+EUe_S*{tbnXXwS8Wz7#UmG8%a>O$oOJI6vn53)m;CcKn{%UpM+GLi( zQis$gD79%Uon^4hA+`E&Z5A8Gh7YMtRBA`CY&MdO8d3}GsX&#(a@go0waH5D7?#V% zvT;LdQ+Vxomd7TriEPr4+SG9EWHyCO9a5X7)V{=~v3xdtNNu`OJA=(+vsl59+Kh0m zfz4)xLuxaX+Bs}4o5$u4sm=8B#keT>C0}jV&HhJ3L(bI(vh?Iiz-k zQd`8{VoTW4A+^~`?J~BUtzd5tsU4}*u4Jp&J8bok+EGgF8n%|LW9x_1=CEHZRehLQ zJDOTKMzeR(Y8u-R+e)pf&$6fv6)>NxphV3!?Mtj3!#3CEviHz;$_J3j+Of6cYRA{+ zVU#iKeaBeGILCPQOSXmm%8|!Dr~#Wga;an=^5=w7HT(5dNbJq9)MAdQytk2k#7t}} zD`t$DS&7oGRP=M`O5>jG$@`Tt3){xFvvO9!Dp{37=SV1xyNX@^W_af(>jCgpvyYjC zmR7X1F}owxk@>=wJJ?RPi|uAL>@S$ZG0HK*G0ZXCkzE?k77T@-k6p`t!#-h7wugPn z_Og8ry(7gjlKPa!KNpr-wx1oqY7a6Ot7C`IKGBivNOFvPVf(|Z9FAW5-z|JHbw}Q>+QA%ywjyYS`)L!hMFFWzFmyJI^k#7Ix8*=E!oSmuj91^BH!D zeGV8dvn%W>yN0&uH1Z4DwzBKI?G1L5-Fi{mQWd*>NzFb2Us&+}$81Mw9Nx9z-LXG@WqZCGR$+la_B#P=(sGgss-dN+6Z@W9O}%iqWF6 z^o@e0M0VdXWrtddb4=aCXRU9uMJ7@?CdBrORK<=T(`RaIUG$owDQp`Pf%wJqIHt0{ zy!G#{!ZNu@mN5T|9UmI&1m}g9csaIqnq%VgDQ{8L6~wN`F}5TwvZgEQKbIf=+;*|E zv45}d(O)@UI;%RTbxgC34Xp_rKP`4$+rrYoev5JbLj+E6;(x@OXfBH44%B{oE}s3T zX8jd)?12bK>z)B_CH_~bg(D4{%5R?cTB9C<(TA{ZkrK-(l#sVIYK~H-K-0mB z9J}P&___ob&ru46I}2e4H-bjh5azGd*`i?D7FKi)UF-}kVRz}pV*!FFS0+YGwT`&r zxLtAEIYiRy4o%dzmu*oSi9^>CcDPS@%m}3rJ@fLMPALNqKPA3aYOXZzs+L}_nZkYkg4fEc;Ne?e zF93^2zJ!~NM=$GQ6n_e+0xGAfH)9Px?vGnOZXJGkXZz$!pR|0^QP{D$d(pSr$FHvL zeRZ`v6Gi01+e@Sty-9p3BSGucS<6gw<}U~mqtpy9Cf~%gQZVB?8u)SZ3Y@gV1cXc{SzcO0SNYDdd8v zOm(@%CI-`)s;kYFEI&!gMHhjtc&p7Mp%30m6X`7(4_+-Z*-T#TR+H82O@M?;7EB1t zmRPOihJ5r<9{o8L{CYL0smXd4v$PWHC@l6*fBF;RCn*^MkKwXu1s?k{*7T!HS<|1g z#-;XT40nIrl-u}8U&hq$(&s!*pVOB-r@hrTc}f3drH5!QN{>FJA^A}9U|f7^nkQ@6pa%bbKW<+8#~rzMKj|B{+%tN7 z%dn6eroy_~UVX0M5Pfl#WS(6( ze|C+&5;U_S3}tx-#y|ECZCJ8;<$A;BqGf@H$K`{azH2>}8Sv^XXHeMR#ZdCuPPy&O?1IAi1+(P? z`~5v_zPju37bkoj`{g4ie9bpx*QpIl*CQJFL-*N%jw6A+J-#DtzD{>>rDU`)17fWH zi*13n%kutvV(OYHh{u-fHiAJVlhweNV1x|XjMY*V_6)0~vXqu|3XEX+ClvNK2#!Oo z06uu)QQ+YN#87>Wcf@GF$IGrJj86}z-GJ5Sa?77J4Rjp!)m;l*tQU=g{}*FemeOd1 zpp|QiRxC5DDcbOkzw55tc~x#`@*TM(HypwQ{tLG;hwo0~z{A5BRH8^SMx(WTzDKUR zQIp2uH`r~Ka*q3dgzB;+LxtEEVd!#GWpPcFb)chj{mRwBgGYh~5Bgf}V<0=ou~2^K z3_NNSsPZ-4@wHx*&mRul+Ycy%)VpT*nxglO?=IW0ZuO>(E7z@ET)1HF!g)0#1$n@5#ptCM`@d4;8e_bzMIi-;OixYCU z(;MQT!kRJ9p#_CIY4D&OLk9m2g`ITU5-1a!c{5cSR+w%40W(!sRYKye2I4gSPCj@5 z6c4kRe6YuNqCL2j#*%2P zw3(nXr96|}hG25_ynj4!45gR`pw(poXXLdE7mF`m5L46rtrVb%ri9x zdb4^3C2iJ1-4)oZmYpPVpP=9p=c})iI~#m^F3FdV?6j~_v(0K0d4nIi>jU?{3OqU} zUKd!+lqa&(m=~8|H#b|_Xq6`ZcTtr<;gm)6 zYyu}^vB3{8QgA;CyBUSN-zB=r&TcSk;M(WD^X|Z-^Zw39@`2O-vmLU#-a8jABUKM4$r{uJ9;d5`tm@>p@Hs}nrQ?NZ8HWz0tKxGCKQZV zm6f0)X%7CDpj$=IaV@RrXS2;_mY@OUu1;uH$!rDUxlk6AS5=mRx#)$^*|Pfx7{=Fd zOx}Mbc(D`YtXWMUAe#p+G)uq=xWh^rIl~USnfSnJ2muA5#P&fcJgdQOHLt8Nm6|tI zmqQ;3I0?*O5tty~Vn?9#nF*;ouhxzvnpanDsj%26;avG#HRIH_fbdZ7#N2X_?#z<%O{Gy;`cP88*ZarI)wR+**X zT^LbICDYD#%)7bmW;KX+q3_GcU@At!)PH6l7)d@*51A2I1&zf%`+Mi7VcTml->qiR zT+qNU#1;!Pj`m!>+sdD}LlFyJf!!wbvhVg~!C(G57g!3ZP(!Xi+=>Cz>&1RcG&%QJNrqKgY{V{s76?yUPMrcP{ z8DFh96F?h8ThDV4uUWZv;|s77-4i3H6GC9B!;s~=+dcsZRo3?D0~}b8+Z&#pK>9VI zoti#N)ghf}4lD7i(N>22q6{_&#}K@Zfkzi@?o^<*U~fy=Wz31ku+! z>^ZV#Uq%2n-|%0!LI*dv4Xa2%NJ51K2u_F4_>Z;&5EuhciQ zp`Q>r#V^|1;J@2q5Q~FLg&oLFj2a$6?$|50HyV5=?qc-@-`8!}CTQ>Ibd%4v|B8@e zSc8gD_C*(53d|5ZcV52#rLU!ftU9;L_tl9&{a*R(T|31+P%j_70Qj*9VkFTO!fii@ zO8IOHw19Bt1du|oM1Lq9A&g*J04uwW0d~9;$c5h&c(@l|<@QebPKQ_!wtu)({uA|L z;l8>@fjgaKUwwTThgYyHwD*7c5RMpaRwrD(^UY8t-ccfMXe6c2jCLFfsVuQbc=nEb zfoAk3Z8h17%Oczow3l{*{f?wd;5OI9XPKXbcIQZkceI@Ydtb7ieI&q|Z35~!h1#KB< zYlqn#Stxu&fmgZbxN>~R*#+YscqMc;JN;d*Es%Gq9R<9uV!#gdg%QQX;%^pLwxUDX{i;MS)ydzYiQX0CC*bVq5e4D6o#0Y|zz%U+Qq~Rc!@7!J($oBQ{ zt001KK$L@BJE8i_w0{~)stXqsSWP83zE+9DQ&y~6F(eMP1bTYp)2)an$Y;;TMswg( zBb0-g_-j1QhJFBQ@iYhY6jFh{SQ7<+@VZb?8pESm(0NAg=m2uyw`-I2pk+_@`k3E}95XOORcI?w~9M#PlcpnqDTb*oUO{_als@)rST zeFQ-Q@9rZ85h2<1?rKs;+;J2*BTi^0_K^2?%WV(H0BSoQJiR}nJrcta2_Cw%Q*>4E zxDXOSe*1zj-9@EvS(PR~Pxue1Ys04j=U%Z6NT|{eE^*rfKi9VBvfPw!J-a`++dP&`{Wu1k(s=Vhpd&&b>9hF+J;=39rnX%wu+& z)?<@jDuk7LLBfecFeT`0!FI+~8Wu-!9JpIwUi3BBiP1qQC`3EOt0Bg)9~6&_JAwW~ z_Yhr#8EP-0`cAj-2ajGr=nkVj<17n*5JDk*&`1OTYlnqv|34Uo4*?O0UQx)yB(jn8 zG+Z6%aLU~+g7qM3#K-r)6kWmyQUsoRkVWfPionD(Fo{Tqzz2{o-@h`@)9m|tkJ#G{ zB0ln>pa!WV$deKS6220v(b4ttmT_bbVdUSqOuCl}qD z9Od+L>iWB{`x+m@d6m0iDV`xPvrHV|hM%wDoOhhl>J74=8 z4mz=E-4OwrXoZ0V$%f9z_xhgT%_f704wJR^h0{I_8eJLXXTTsbHQewwUO*%;3RThZ z5ujScdm@s}sbh_ft`IpMV6cI%E8%zwgp7>C2lqhMfsQUEXyiUBf-JNi?gNJS;+`vT z_d$rLbrhew*rw>VE1&s0uhQr}2R1Exx!~o3LNLDA;uNM*%x2EjhYrC)2=LuNK623C ziLfKWKX-!XuwC6kU=SQG7K~_rMYRpf`f20~*3PLUCQ{f$Grw?-T}QOzR*US;q31jgpF@jTZRYC5g;@1$GKtRbA?3g$`~YpB^BN!up1mhbRw4>FR7fN) zBiYa{Of&SR1p;j(n9X(AY3z$ZX5j}E&Ypv4?WbHx32FY-+L>?9d~fEG53z1+sKGtQ z2fCXOzQZsA-ay+!;D$Qlm6CNpC=*JDL&g&i#L%}tCxPj?G|+LGk{|AR=s8RU@4lj{ z(rB;dEGhOCX5n!#rtso{BY{Uv7*HfR1P_z5PHG4C{S7#T;M_2O3B1Ys_aLS;n>H4{ z-%@0NN2t(W*)xRS!S@WI0R(CSZ5RD*r)c#DI|VKY*}~Z8OY(P}lkYr$`VHKQ>7;-jwtBcky*|Kg!7y`5sUYCFj z-){>(V30@82y7uW9R|iWCz;T^Mmu+Q!E8IC)hg`v z2LH8V+|N*?r?7y_&m1%f%MV_01-oj)y0yZOnTt2|isjW@2jp)re0kn%y9;t5Aec*x z1l&ZsA4Bn`R{BjW^oWg(wB3ERm+ex593?MKhLWVdA zGLa@U4W-FKivd2dEe>=xB5omO2i}YY$omm{@s+|NfEy+tALt@42fiEh8NivsLuykD zQ_9Si(lXl=gYVQ8U-JbYFn;Q8DC_lU7`-A#Dd-oC1Hmg4m%$==5=`JGxc>-c*Reff zOw#$}dV+qWVXy8X_bHSN#f;+4P?-fMxhrvp34vi_b!DlgvZM+t5<4rF1T^uw0`Uf{ z3nUZ6e7(otdN`yUh}8oUe(gZg{w=wR z-7{dX5IuyIsZg8KU#L&wSdR9v(=B%%hdvezC3plB_Z_=UcJL!2ktGN~N&N7GBNa4Chih79MSJ)=PsDU=6>v`d@0#~bKzwmIRps4SD7xahk zWV?t7ieU|c;ek>Z;eaMTL3$r}m9|hpc}IydxDxp^l97s!P$17&LC;lGd@Nqhd&uUK#s!m~Y)9fZ z&_+pU5-;qWp&VtHI%2#C&Jh~mDNBq^c6rBPM7ThLV6!s-4S4ggeB>+N@gsmm2#N@N zh?r)-FQA6^ol^N5Gon*;~KdjvKF|BJOp zv%Ns3Vbd~-*LM*n6&oSM(jtm30&>FaqflJK=YS6(Cov$rqp+t2o^%2fZx+09IK{A8k2fIqojQhDIcWVjzbv40PdS z1Kp5?frA{85>15Q^BiLMS}d-*0!aA)_B0n<=#be(mJ!J^&OUKd3yKC>7l$MSf6}_R z@5^md($YQ06+4fc&V*^M=mfq6sR=RdpD76A$xfOX?qLVao#*VS#N)8-dz#7p<$DvY zOoRX*o6vAm9=sJR|Y4Fr-z-B)QjD?3> z6w1rG7J|5loBz;#Se!Cg@G{Z@6nHG0jT1tl7(ayxD2#pE4R`*vX zc%;lqQEKsi0gU8#c{pjo!nv4NY$OOU&O=2w3%+3CJkb*q^Dy^xcf%mG@JfVUWQ z?vTD1H#YRmfte>7&qrfQ#V=S$sTFz>?-$~I#4QnU)4HEx-Lw*uomr|Vnl73z5^NXg z!Rs-iFqwjv&cQ)Zm{qwm&JhCpUvY=Xn;JR@YB6Vsg~{)XI^zR7HEh=rV}@888!8qU zhJ?d6hn7k9>Vkzte*cqcy& z$2F1AdO`RH@QOf*u#!nm_|Z%yFj6mKEj<)e0&pa7{Cp-%2_drRkC(s?zP>C%9Wecs zNE!FOQ72?j_~x{x$5<1mH*$Dq&x+FufR_Dn#(O{sv z9WfY@Gc$;c87=Fdu&n1wBEnv=Qhx?Ill*&StKhbMtX04dmf=VUC9q1(Hdt@aah3M+ za>H7j1r=aG_ra5Z(nMolBhoYQo5_TxW`Out9|9;v$#UZjDw;cVWY_K|+d{~efeVZQ z94}6ZQedg!bK)RMjn)aJCLe_p{25*XQ3}-X|M)pZTKZ2|y6^sd+9IMiRly@5C{8vP zV#3e~#KMBPiwX)CfqCTpH-$=7qMn#R$PdLM@S_r8e?8=@)0vo_(@2u}np))ceZ-O6 z2!+1gv`p^#LOzaDZrH^sPZc(FLc6meI<8Jz7e7iT*c0f(k>(gaaA8QoEvzH>5D0}} zZKTk-l8)N4?GIqYM>~OH&sx3l{mm=P6%{7Zfore47iA-f&cCfJJZtxdDphBe@Ycc$dyo{2Mk(piIEe z%`hW8u!B z$6O7f2qizG_$D4ssY>Zu(3o0W3VOj0n5dchR@_ziE;q@4;eRzKKZ~o+rRzX;GD#sX zQ6|xu<=52`Vn`| zXQ7)@)tmBx_pa`7F-RcjI1=1= zP>`^MkPv$d3b#(<@Fwc&8Qy5|ChE6&@J4qo;f2Uc$iWQakLjbH6K^Fw7pY5u)MPt9 z1%We3JVwnu&7ahH+zGYQ`FkhW67E9#YcvBGojd)(mrO)tEI))-Y zP9hq3)s@i{kQ(vsXHefws3#}csTx#iQ*}{=PK6sc@v6inYIl*FHLmE@zlBeesYTap z5zp$438Q)D~nAcrjm}M_?Hm%TOukQrGh+V zejq;I7WHPW0P*6R%kY3tYhml=TZ_bV$ApfzyJv{!a1TMAS_~s-0QE@PUswa;RITB8 zuJBpK`R3M2cxQj!{zFFq8tTM$g6&x`9-?=5=(iw=OOOs?FUNW56beH!-1)<)X{&cw zbi6+FGBsqM7^^DFccTZtV9Q--Yt%QKi}$8gm+iLFFA^EexD0_K>zKux3WptU$UZko zR_`eBRe1K4dqCjAUTnkBIt~1oU_83yYq_&89mcabP)$dx?G);uO9&UP_?r(aF*|;c ziZ%!C(25f#;f)0t7Tbupr2w(#=p*Y<7-|tVXeGh=2~+6g(s(EGgO&>4aj? zNf~c(){r#0augGXmFTvbIG06RIpF-N)wi!fk+=Of(JPv|fLXX0!rBT&Vd>CIv{MCP z1I$AL=LE}d01LKH${6fvMr4t20Oy_G91+g|$KU!W^o$4u3{@qKDg;?M;baKmBD9an z4-p}!9D#xtaT?>9#5GcHM)5X4swDIi?UhTWf)~}N$;~n30abEy7sMV`kw`rqShaU&S z6y8L0C4PkqzY}JbD8(uLf&kEfTfG|i9@0zvYmKE^ggf;{e(29=l%`OHmargArG9kl zmH$GQS4*3>H(oN~4obek8*jlClU-gd$DRhBK7x20pWY;-y6Cn#Vu4a24VM%NczX4c zxfJ6_yS+N$zS4+D9eNX#ggj!3rd^f_dj&2jh+8xGH8V<{0V+tlH=Y(|mC^{VX*4?W zBy{DMYf4Sk z(gqrHB^7iPMcPXh@s#JYN?*{6FX@HaBAupxb>ga&SG`Sy>hvKlkiMd}1ymTQprfzS zW)xQX8o5mI&py40KW;dAdSnqKl3f;Do=8%bLpTqHGb@%>Sv2_s;m+2VIF;!dsU03Wkc`uvZtE3EZvVP6wXzH zI^5TFSy9bDDYysh(SPtXS(kwpD4cH(rm500T^o3{!J|*+pOt8lMlI5G&gE#4n&Da! z+hRFdq*9AiopTvlq-VK`(V}$ z(pGXbcrdr=gwzOnaJHl$y8<|!fARt%XrCEYcb!-f_~ywQ5JNFmr#biiRO^ohLD z(jjAnF)%+g%XYMg#=x^J-hNSwoX{A*9MVF;kw-r()M5!*5SCB?OJOWVwOBo*MRJ;J z5??LG5Y(KD7RfY5vd+0AdW^{-d{hk?BfOS5p%xp_;<>Bc9BNTCq(vC(`5wK%>0-2q z#(KuQL6thbSS?DI25WX{Tua9_XlxAyYS_bF-MB5iU!ZkfNR$c;

FLWh=aT&4R^nf-cLuSP*)U# zycn%?MZYwUK9_fWlXop0j8iA>P=BA8=GM8=pN>eTekcf`y1`MAei?wsqaVSigvh)@ z{dS{Yx_g+rv}tE+La%-{IP66;kL7(aLbgX=%FB&|ahk*;zT^z|$fl_+FSWkhtDpNc zCzU`zK^jaqn5%$*0f0yJ1`_ef7>rXTE{~&yf1sv?L+Lgpw2W+>+N&@886Ysgc)on# z0nhVk8C&@>M)vA+UbKEJ8*|PJb<70$2>OpX^y%(|rtDrl$ddgck^%1!Z%hmR-nDr@3~x?Y;W3FIqV|qnjX_fO;}5doy2ln#=Akq0TR+IM^h-WI!>DI+y%x=W+Tx z@Nu}vQcWprdEGOqpk*Tk_L93R`wL$GM)$3)clyS@=^Oh|=56ZF+eGRG>p;<$lItp}t95JLW=~31!X)#|Mb9qev1jtI;(f3OLaOC7@1R6-Tev@Y13F zUZ0HpBYl_psY;!=OHEY(7NrrTCh@(vLA{z3=9J-lub&PbBf?hSF7Ms2sKgr2!9(OyjeQMvd zMg7wj_2s10&XYaPBVq=>_!U9{eVHHhXMQlKRi&;5 zO5&1}o@z8%Nq^L6T7kr?g`2_Gwg{2cljAPUNO;V;n{Ky)FmqpBQ! z2^x^&WtBRpV;2>jRNSW`lL|85MF@v-_aY>!e+|(+d%5{_DS&r~)Tpd~iDFQrR;xX# z_j*8~gcQmFDFCc~r?x{+~xRsyFuYeL}L+=6ZY2Z}$D>yM(ci6UO!>jPIw< zORehugy~MLN0;Peu7!Il_f>wU%YCfN?bD6xr_U6p2D}@;3h_BjVw^L6Fh#94k%1H` P^_vpZK;+Mr9K-()Zb7UR literal 0 HcmV?d00001 diff --git a/docs/hel-892/sdpose-document-evidence/__pycache__/rebuild.cpython-311.pyc b/docs/hel-892/sdpose-document-evidence/__pycache__/rebuild.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4e16abb9b722911506132e7183775b01c784dd7 GIT binary patch literal 4633 zcmb6cTWk|o_KrP{XFQIb#C9MLS_cAcSQ3+vCs5dgBn_+x?Nl@Q{)cLBMBcoarF!P}xl%oes0 z7`I35VY~Sx!=(9igdOlCqg63y*cqe3RE!SOF<00XW5NuqafID`Rk)gW-a=syPXY7_ zH9URI+)HxXkl=j?yFDt)fMAV%%KW#v(qn@>A56rBpd>7a!gYZU^1`eb7ZouPKNd_% zf-Fc2LQq%`q?^HnGABq|l)=Qzyuc|z;Reeo(VHFLV*YJ}!LadoLSgZGdA!YG*w0;< zHXP>%r^luYa&qMSIm0oN5~I99b8I{j7dbX+yxP|_(AnSL*M0a%-+<6R%XJBz9LvLh zfSnP#XJ=-*dW62-&hGR8kVnNtQfQxHxobk456Kc2Do=*EL~QnEN({+~l*9><-Wt{ zt&z(hQ`VNXD*=ltW2>agk{KdnZ`dZ_ofe)UdCD4bWZ7_Ya{_lQl1M4Z z6l^^-I5lEWlOt2-E=-;pk*YvK!@;LwN!g%)>B&*DUyGIk;H5ro!aeMY&Xf6>GLN`P<5le((si*=$5V@X^uE|Ljvgpeed5!jKuY0xGXfuNFFKtM12<^KZ6p$)HZDSiK--q`tB&yxfHnO2A1 zfd0R+(o^kv^UJqbwQ)vkoY4V#Io-?U#x^{4OY`^r_ZnBmp7f{|h?Kp#{Q{vMbx z!`}~9`785_34p{aOHILEu+`EGLMuDomFFR}0ksnCbAf~uSXXY9lx83jS(~zh>rZyv zAwii71o+RV2?D37$M%PyZ~(kU#a;C5lmFlL2~{IpY(f7mdc==C%v-6QWhWnx%14@ z8Cp8>0(PJ)Prh>WB6f%qJj%KUMuGQxYR^5V)mmy`@;t|FFh z{?a<0=3P9q;Qh69z>-l*ZyV?#zo@`dax3*bm8lsmxD)e4g1DN zzr_Vhn@z%QZB&VIxI2_*giFH4O*2-N*q(Nn1y;JRT!#I6ZC1LT%eN9-LTT^t$mr?u z)6=KVjZXz%3;r=(|J;NN-FO({Ng15GETO^U``6c^BH~ost^}$B&8GST`^XScN~XOfQ`y0I<{Yc0!W?$@Z&e= z8@P6h$kteAg2Jicf4`neY&uER6o$Gwe;yNeVV`TNvq~RQM8w-t#uYA z?FGIPHlu{&BkjaWv>gpTBMznMq!=$1#_6H+gHu!HH-Kf-V_UU;XHU;oy)OsZID9EY z`Cw;vuvF3nQ*myNjb9b`w%w8sZ{x=R`@6IofZ>t^mXFNbR0P>9FAUdpNmPW0BHU0U zYzL_k16&#z&N)_|i;6Qw6;yOxJ-re(uR+fVH+b=?AS)8S8V%ayh}Rnq;1rXgS`-vq zbtR)vJ3)z;5TV4AuvCUUD#WFOc$p(9iBJN%4JVh9ByeO2UmH>ren;YyC|U4jJg$l* z_*4{FnY&b#b~k9yJYuSCxG=gUlxcHZ>*J%{YQHy)Z;;sH(h$7EO3L@Z4nIO!WmZV7 z4|abPT5srCYv|D$`t*iA&C{=Y`k_SH-SQE0kI~3L?)Ch|4F~TQ{+;Bye<#4!)2tcXID%9+{OWv+l zU+UFs`tpvAK=bV@4^FQNT5Gr7+N}k8^gz#g;N)81q!t*|1A}=oKfUPMpxvr>|J?}y zrLNKY*Qw4ms&m6#vvg)Twc7KfR&^iK+{bkHu_wId9@@0qXxH}$0C?jT_<=&6I@Nzx zt3I0>Eikp~Ow$_Eq%nJRW>0Rou)FymuD`oJa^G_oQLV#cf<-q-FkA39-5tJtcHO^! z&A(qga63+%->21cjQG zLe0TKo&U}&AG~5kmxXPNo&AFSa$*`=Vx*~;q&6_k?+x&wI`F1TYynpESp-sk7`*P8ZeD#~vRkih-4%+Ye9s$7875&J; ztdoH?GO)~RWRp%dsbtfJgUTP%9QEtu-ZgUXgYHj`uJWG;zIa>RH=*sD(DzNK(-*aU z7d7&dPF_;UOB*Duy2dr~oKBuo%iT;C1{H~5w~a*FY7J)ue>_DZhAR@8O)2=(D 100) + --> docs/hel-892/sdpose-document-evidence/build_definition.py:210:59 + | +208 | + ",原值按源保存;" +209 | + gap +210 | + "因此不能确认绘制范围、身体部位划分、阈值比较、尺寸单位及边界,不承诺检测人数、精度或效果。", + | ^^^^^^ +211 | [registry], +212 | "source_named_unconfirmed", + | + +E501 Line too long (103 > 100) + --> docs/hel-892/sdpose-document-evidence/build_definition.py:275:81 + | +273 | "分支选择", +274 | "只解释当前长边分支;不是scale dimensions的宽高/裁剪布局", +275 | "当前选择scale longer dimension,只生成resize_type.longer_size子控件。固定前端setter重建子项," + | ^^^ +276 | "以限定名加入并在主控件后插入;保存/恢复消费顺序有明确参考契约,但UE7.7.1与目标恢复未知," +277 | "不把此说明升级为可靠转换或生成prompt。", + | + +E501 Line too long (107 > 100) + --> docs/hel-892/sdpose-document-evidence/build_definition.py:410:91 + | +408 | "value": value, +409 | "json_type": type(value).__name__, +410 | "execution_note": f"源保存位置;mode={n['mode']},源声明core{n['properties']['ver']}。" + | ^^^^^^^ +411 | "官方固定版本只作参考,不证明目标安装/UE身份或实际效果;SDPose准确schema缺口保留,不产prompt。", +412 | } + | + +E501 Line too long (129 > 100) + --> docs/hel-892/sdpose-document-evidence/recompute.py:125:101 + | +123 | sdpose_fields_schema_unconfirmed=8, +124 | gap_scan_sha256=hashlib.sha256((OUT / "sdpose-gap-scan.json").read_bytes()).hexdigest(), +125 | gap_scan_recheck="Optional online check_sdpose_gap.py; offline checks stored hashes only, not entire archive rescan", + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +126 | ), +127 | ) + | + +Found 4 errors. diff --git a/docs/hel-892/sdpose-document-evidence/lint.txt b/docs/hel-892/sdpose-document-evidence/lint.txt new file mode 100644 index 00000000..1f5f344d --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/lint.txt @@ -0,0 +1 @@ +All checks passed! diff --git a/docs/hel-892/sdpose-document-evidence/node-check.txt b/docs/hel-892/sdpose-document-evidence/node-check.txt new file mode 100644 index 00000000..e69de29b diff --git a/docs/hel-892/sdpose-document-evidence/package-check.json b/docs/hel-892/sdpose-document-evidence/package-check.json new file mode 100644 index 00000000..95062514 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/package-check.json @@ -0,0 +1,23 @@ +[ + { + "file": "fixed_document.py", + "sha256": "45b54eae2840e5208697e6933331d07c232a1c0fd309df9ed57384608ad27c42", + "wheel": true, + "sdist": true, + "definitions": 15 + }, + { + "file": "source_reviews.json", + "sha256": "99aae4b77a8393e1227f41679c3d265916db16068d1bc2a4970013e7d13a6e75", + "wheel": true, + "sdist": true, + "definitions": 15 + }, + { + "file": "library.py", + "sha256": "b9cbfce28267642e6db3ebe9d591cf8dd260c7772a5a21a8d36cb98915eca13c", + "wheel": true, + "sdist": true, + "definitions": 15 + } +] diff --git a/docs/hel-892/sdpose-document-evidence/pins.json b/docs/hel-892/sdpose-document-evidence/pins.json new file mode 100644 index 00000000..5e6ec65c --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/pins.json @@ -0,0 +1,3 @@ +{ + "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json": "b551c868f57456de9ca37e8b3f622eab95c070947ab45fd1f7b4b26cbf077bd7" +} diff --git a/docs/hel-892/sdpose-document-evidence/rebuild.py b/docs/hel-892/sdpose-document-evidence/rebuild.py new file mode 100644 index 00000000..664588a8 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/rebuild.py @@ -0,0 +1,64 @@ +"""Add one reviewed definition; preserve every other review object exactly.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess + +from build_definition import OUT, PATHS, REPO, build, canonical + +BASE = "729188740379e8fc2e1cad1ca9abe4fbb25e7614" +RESOURCE = "calliope-backend/src/calliope/comfyui/source_reviews.json" + + +def build_all(): + previous = json.loads(subprocess.check_output(["git", "show", f"{BASE}:{RESOURCE}"], cwd=REPO)) + reviews = json.loads(json.dumps(previous, ensure_ascii=False)) + for i, path in enumerate(PATHS): + block = build(i) + assert reviews[path]["source_sha"] == block["source_sha1"] + assert "fixed_version_document" not in previous[path] + reviews[path]["fixed_version_document"] = block + return reviews, previous + + +def main(): + current = json.loads((REPO / RESOURCE).read_bytes()) + reviews, previous = build_all() + (REPO / RESOURCE).write_text(json.dumps(reviews, ensure_ascii=False, indent=2) + "\n") + pins = {} + for i, path in enumerate(PATHS): + block = reviews[path]["fixed_version_document"] + pins[path] = hashlib.sha256(canonical(block)).hexdigest() + (OUT / f"definition-{i}.json").write_text( + json.dumps(block, ensure_ascii=False, indent=2) + "\n" + ) + # Explicit maintenance of the code-owned allowlist, never trust runtime caller digests. + module = REPO / "calliope-backend/src/calliope/comfyui/fixed_document.py" + text = module.read_text() + for path, digest in pins.items(): + old_block = current[path].get("fixed_version_document") + old_digest = hashlib.sha256(canonical(old_block)).hexdigest() if old_block else None + if old_digest and old_digest in text: + text = text.replace(old_digest, digest) + elif digest in text: + pass + else: + text = text.replace( + "DEFINITIONS = {", + "DEFINITIONS = {\n (\n" + + "".join( + " " + repr(path[i : i + 40]) + "\n" for i in range(0, len(path), 40) + ) + + " ): " + + repr(digest) + + ",", + ) + module.write_text(text) + (OUT / "pins.json").write_text(json.dumps(pins, ensure_ascii=False, indent=2) + "\n") + print("PASS one definition; other 155 reviews and old 14 blocks unchanged") + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/sdpose-document-evidence/recompute.py b/docs/hel-892/sdpose-document-evidence/recompute.py new file mode 100644 index 00000000..5ede8f7d --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/recompute.py @@ -0,0 +1,383 @@ +"""Actual 7291887 database upgrade, one-row protection/rollback, frozen boundaries and packages.""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import sqlite3 +import subprocess +import sys +import tarfile +import tempfile +import zipfile +from pathlib import Path + +from build_definition import OUT, PATHS, REPO, canonical +from rebuild import BASE, RESOURCE, build_all + +sys.path.insert(0, str(REPO / "calliope-backend")) + + +def write(name, value): + (OUT / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + + +def require_packages(): + dist = REPO / "calliope-backend/dist" + w = sorted(dist.glob("*.whl")) + s = sorted(dist.glob("*.tar.gz")) + if not w or not s: + raise SystemExit( + ( + "缺少wheel/sdist包产物,请先在仓库根执行:" + "uv build --project calliop" + "e-backend --offline" + ) + ) + return w[-1], s[-1] + + +def main(): + from calliope.comfyui.fixed_document import DEFINITIONS + from calliope.comfyui.library import rollback_batch + from scripts.audit_library_documents import audit + + wheels, sdists = require_packages() + reference = OUT.parent / "sdpose-reference" + identities = json.loads((reference / "identity.json").read_bytes()) + source_records = json.loads((reference / "sources.json").read_bytes())["sources"] + for e in source_records: + assert hashlib.sha256((reference / e["local_file"]).read_bytes()).hexdigest() == e["sha256"] + assert len(e["commit"]) == 40 and e["commit"] in e["url"] + for e in identities: + tag = (reference / (e["repo"] + "-tag.json")).read_bytes() + commit = (reference / (e["repo"] + "-commit.json")).read_bytes() + assert hashlib.sha256(tag).hexdigest() == e["tag_sha256"] + assert hashlib.sha256(commit).hexdigest() == e["commit_record_sha256"] + assert json.loads(tag)["object"] == { + "sha": e["commit"], + "type": "commit", + "url": e["commit_url"], + } + assert json.loads(commit)["sha"] == e["commit"] + write( + "source-check.json", + dict( + fixed_originals=len(source_records), + tags_to_full_commits=identities, + checked_sha256=True, + imported_upstream=False, + ), + ) + + scan = json.loads((OUT / "sdpose-gap-scan.json").read_bytes()) + core = next(e for e in identities if e["repo"] == "core0150") + assert scan["commit"] == core["commit"] + assert scan["python_files_scanned"] == len(scan["files"]) == 516 + assert scan["matches"] == [] and all(not e["contains_sdpose"] for e in scan["files"]) + scanned = {e["file"]: e["sha256"] for e in scan["files"]} + for e in source_records: + if e["id"] == "core0150" and e["file"].endswith(".py"): + assert scanned[e["file"]] == e["sha256"] + graph_raw = (REPO / PATHS[0]).read_bytes() + graph = json.loads(graph_raw) + nodes = graph["nodes"] + assert len(nodes) == 9 and len(graph["links"]) == 10 + assert all(n["mode"] == 0 for n in nodes) and "definitions" not in graph + assert ( + sum(len(n.get("widgets_values") or []) for n in nodes if n["type"] != "MarkdownNote") == 18 + ) + assert "widgets_values" not in nodes[2] and nodes[2].get("widgets_values") is None + write( + "source-graph.json", + dict( + source_path=PATHS[0], + raw_sha256=hashlib.sha256(graph_raw).hexdigest(), + canonical_sha256=hashlib.sha256(canonical(graph)).hexdigest(), + nodes=[ + dict( + id=n["id"], + type=n["type"], + mode=n["mode"], + widgets_key_present="widgets_values" in n, + widgets_values=n.get("widgets_values"), + cnr_id=n["properties"].get("cnr_id"), + ver=n["properties"].get("ver"), + ue=n["properties"]["ue_properties"], + ) + for n in nodes + ], + links=graph["links"], + no_subgraphs=True, + extra_sha256=hashlib.sha256(canonical(graph["extra"])).hexdigest(), + embedded_prompt_sha256=hashlib.sha256(canonical(graph["extra"]["prompt"])).hexdigest(), + embedded_prompt_classes=sorted( + {n["class_type"] for n in graph["extra"]["prompt"].values()} + ), + fork_declaration=graph["extra"]["comfy_fork_version"], + frontend_declaration=graph["extra"]["frontendVersion"], + saved_fields=18, + notes=1, + sdpose_fields_schema_unconfirmed=8, + gap_scan_sha256=hashlib.sha256((OUT / "sdpose-gap-scan.json").read_bytes()).hexdigest(), + gap_scan_recheck=( + "Optional online check_sdpose_gap.py; offline checks stored hashes only, " + "not entire archive rescan" + ), + ), + ) + + rebuilt, previous = build_all() + assert rebuilt == json.loads((REPO / RESOURCE).read_bytes()) + old_blocks = { + p: r["fixed_version_document"] for p, r in previous.items() if "fixed_version_document" in r + } + assert len(old_blocks) == 14 + assert all(rebuilt[p]["fixed_version_document"] == b for p, b in old_blocks.items()) + write( + "review-delta.json", + dict( + base=BASE, + changed_paths=PATHS, + other_reviews_unchanged=len(previous) - 1, + old_blocks_unchanged=14, + old_saved=376, + old_notes=13, + new_saved=18, + new_notes=1, + total_documents=15, + total_saved=394, + total_notes=14, + ), + ) + for p, d in DEFINITIONS.items(): + assert hashlib.sha256(canonical(rebuilt[p]["fixed_version_document"])).hexdigest() == d + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + old = work / "old" + old.mkdir() + data = subprocess.check_output(["git", "archive", BASE, "calliope-backend/src"], cwd=REPO) + with tarfile.open(fileobj=io.BytesIO(data)) as a: + a.extractall(old, filter="data") + db = work / "library.db" + + def run(name, historical=False): + out = work / name + env = { + **os.environ, + "PYTHONPATH": str((old if historical else REPO) / "calliope-backend/src"), + } + subprocess.run( + [ + sys.executable, + "-m", + "calliope.comfyui.library_cli", + "import", + "--root", + str(REPO / "example_ComfyUI_workflows"), + "--db", + str(db), + "--source-commit", + BASE, + "--companions", + str(REPO / "docs/hel-892/supplied-api/manifest.json"), + "--output-dir", + str(out), + ], + cwd=REPO, + env=env, + check=True, + stdout=subprocess.DEVNULL, + ) + return json.loads((out / "import_report.json").read_bytes()), out + + def rows(): + with sqlite3.connect(db) as c: + c.row_factory = sqlite3.Row + return { + r["source_repo_path"]: dict(r) for r in c.execute("SELECT * FROM workflows") + } + + first, _ = run("historical", True) + before = rows() + assert first["counts"] == {"imported": 155, "user_excluded": 1} + assert all("fixed_version" not in json.loads(before[p]["doc_json"]) for p in PATHS) + assert all( + json.loads(before[p]["doc_json"])["fixed_version"]["matched"] + for p in DEFINITIONS + if p not in PATHS + ) + original = db + protected = [] + + def protect(name): + nonlocal db + db = work / (name + ".db") + with sqlite3.connect(original) as src, sqlite3.connect(db) as dst: + src.backup(dst) + for p in PATHS: + dst.execute( + "UPDATE workflows SET description=? WHERE source_repo_path=?", + (name, p), + ) + snapshot = rows() + r, _ = run(name) + assert r["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1} + assert rows() == snapshot and all(len(snapshot[p]) == 29 for p in PATHS) + protected.append(dict(phase=name, counts=r["counts"], whole_rows=1, columns=29)) + db = original + + protect("user-before") + upgrade, exported = run("upgrade") + after = rows() + assert upgrade["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1} + for p, row in after.items(): + if p not in PATHS: + assert row == before[p] + continue + assert len(row) == 29 + assert all( + row[k] == before[p][k] + for k in row.keys() - {"doc_json", "batch_id", "imported_at", "library_fingerprint"} + ) + d = json.loads(row["doc_json"]) + assert d["fixed_version"]["matched"] + old_doc = json.loads(before[p]["doc_json"]) + without = dict(d) + fixed = without.pop("fixed_version") + assert without["steps"] == old_doc["steps"][:-3] + fixed["steps"] + without["steps"] = old_doc["steps"] + assert without.pop("source_review_sha") != old_doc.pop("source_review_sha") + assert without == old_doc + write("actual-" + Path(p).stem + ".json", d) + repeat, _ = run("repeat") + assert repeat["counts"] == {"skipped": 155, "user_excluded": 1} + with sqlite3.connect(db) as c: + c.row_factory = sqlite3.Row + r = rollback_batch(c, upgrade["batch_id"]) + assert len(r["files"]) == 1 and all(f["result"] == "restored" for f in r["files"]) + assert rows() == before + redo, _ = run("redo") + assert redo["counts"] == upgrade["counts"] + protect("user-after") + db = work / "fresh.db" + fresh, exported = run("fresh") + fresh_repeat, _ = run("fresh-repeat") + assert fresh["counts"] == first["counts"] and fresh_repeat["counts"] == repeat["counts"] + assert fresh["states"] == {"pending_check": 16, "needs_conversion": 139} + companion = 0 + for row in rows().values(): + d = json.loads(row["doc_json"]) + companion += sum(p.get("value_origin") == "supplied_api_companion" for p in d["params"]) + assert ( + not row["is_enabled"] + and row["doc_completed_at"] is None + and row["exec_verified_at"] is None + ) + assert not d["status"]["doc_done"] and not d["status"]["exec_verified"] + assert d["dependencies"]["check_state"] == "unchecked" + report = audit(REPO, exported) + assert ( + report["named_values_preserved"] == 1217 + and report["unnamed_widget_nodes"] == 3660 + and companion == 294 + ) + assert report["full_documents_completed"] == report["real_executions"] == 0 + write("audit-summary.json", {k: v for k, v in report.items() if k != "files"}) + write( + "import-protection.json", + dict( + base=BASE, + first=first["counts"], + upgrade=upgrade["counts"], + repeat=repeat["counts"], + restored_rows=1, + untouched_whole_rows=154, + eligibility_unchanged=True, + redo=redo["counts"], + user_protection=protected, + fresh=fresh["counts"], + fresh_repeat=fresh_repeat["counts"], + states=fresh["states"], + source_named_fields=1217, + positional_widgets=3660, + companion_values=companion, + new_saved=18, + new_notes=1, + old_saved=376, + old_notes=13, + overviews=15, + all_disabled=True, + doc_done=0, + executed=0, + ), + ) + old_reviews = json.loads( + subprocess.check_output(["git", "show", f"{BASE}:{RESOURCE}"], cwd=REPO) + ) + current = json.loads((REPO / RESOURCE).read_bytes()) + for p in PATHS: + current[p].pop("fixed_version_document") + assert current == old_reviews + boundaries = json.loads( + (REPO / "docs/hel-892/h3-document-evidence/unchanged-boundaries.json").read_bytes() + ) + paths = ( + [f["path"] for f in boundaries["files"]] + + boundaries["frozen_conversion_and_audits"] + + ["calliope-backend/src/calliope/comfyui/library.py"] + ) + kept = [] + for p in paths: + raw = (REPO / p).read_bytes() + assert raw == subprocess.check_output(["git", "show", f"{BASE}:{p}"], cwd=REPO) + kept.append(dict(path=p, sha256=hashlib.sha256(raw).hexdigest())) + ui = "calliope-web/src/lib/components/WorkflowDocumentDrawer.svelte" + drawer_bytes = (REPO / ui).read_bytes() + assert drawer_bytes == subprocess.check_output(["git", "show", f"{BASE}:{ui}"], cwd=REPO) + + write( + "boundaries.json", + dict( + base=BASE, + files=kept, + originals=163, + old_fourteen_blocks_unchanged=True, + drawer_css_unchanged=True, + drawer_whole_file_unchanged=True, + drawer_sha256=hashlib.sha256(drawer_bytes).hexdigest(), + conversion_rerun=False, + profiles_28_candidates_9_diffs_6="unchanged", + ), + ) + packages = [] + with zipfile.ZipFile(wheels) as w, tarfile.open(sdists) as s: + for name in ["fixed_document.py", "source_reviews.json", "library.py"]: + raw = (REPO / "calliope-backend/src/calliope/comfyui" / name).read_bytes() + assert w.read("calliope/comfyui/" + name) == raw + member = next(n for n in s.getnames() if n.endswith("/src/calliope/comfyui/" + name)) + assert s.extractfile(member).read() == raw + packages.append( + dict( + file=name, + sha256=hashlib.sha256(raw).hexdigest(), + wheel=True, + sdist=True, + definitions=15, + ) + ) + write("package-check.json", packages) + print( + ( + "PASS actual 7291887 upgrade1/skip154, " + "repeat155, rollback1, edits1/29cols, f" + "resh155, 1217/3660/294, 15 definitions" + ", frozen boundaries, wheel/sdist" + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/sdpose-document-evidence/recompute.txt b/docs/hel-892/sdpose-document-evidence/recompute.txt new file mode 100644 index 00000000..22187663 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/recompute.txt @@ -0,0 +1 @@ +PASS actual 7291887 upgrade1/skip154, repeat155, rollback1, edits1/29cols, fresh155, 1217/3660/294, 15 definitions, frozen boundaries, wheel/sdist diff --git a/docs/hel-892/sdpose-document-evidence/render_report.py b/docs/hel-892/sdpose-document-evidence/render_report.py new file mode 100644 index 00000000..ba3f1d67 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/render_report.py @@ -0,0 +1,111 @@ +"""Readable complete Chinese definitions and fixed source index from delivered data.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +OUT = Path(__file__).resolve().parent + + +def main(): + lines = [ + "# SDPose视频骨架图固定参考中文说明", + "", + "18新保存位置+1新注释;旧14图376保存位置+13注释逐对象不变。15图394位置+14注释展示,155定稿0、实跑0、新增转换0。", + "", + "复用SQLite来源库→正常GET详情→现有说明抽屉;仅新增source_reviews说明块和显式受信摘要,不改变转换/执行链。", + "", + ] + index = [] + for i in range(1): + b = json.loads((OUT / f"definition-{i}.json").read_bytes()) + lines += [ + "## " + Path(b["source_path"]).stem, + "", + b["user_overview"], + "", + b["notice"], + "", + "源路径:`" + b["source_path"] + "`", + "", + "SHA1:" + b["source_sha1"], + "", + "原字节SHA256:" + b["source_sha256"], + "", + "规范全图SHA256:" + b["canonical_sha256"], + "", + *[v + "\n" for v in b["versions"]], + "### 具体连线与处理条件", + "", + *[v + "\n" for v in b["flow"]], + "### 使用与核对", + "", + *[v + "\n" for v in b["steps"]], + "### 逐保存位置说明", + "", + ] + for j, f in enumerate(b["fields"], 1): + lines += [ + f"#### {j}. 节点{f['node_id']} · {f['label']}({f['field']})", + "", + f["effect"], + "", + "```json", + json.dumps(f["value"], ensure_ascii=False, indent=2), + "```", + "", + f"类:{f['class_type']};JSON类型:{f['json_type']};角色:{f['role']}。", + "", + "源位置:`" + f["pointer"] + "`", + "", + "定义默认:" + f["schema_default"] + ";单位:" + f["unit"], + "", + "范围/条件:" + f["limits"], + "", + f["execution_note"], + "", + "依据:", + ] + for k in f["evidence"]: + e = b["sources"][k] + lines += [ + f"- [{k}] {e['claim']};{e['file']} {e['lines'][0]}~{e['lines'][1]}行;" + f"commit {e['commit']};SHA256 {e['sha256']};{e['url']}" + ] + lines += [""] + lines += ["### 零保存节点与源注释", ""] + for z in b["zero_saved_nodes"]: + lines += [z["node_id"] + " " + z["class_type"] + ":" + z["effect"], ""] + for n in b["comments"]: + lines += [ + "节点" + n["node_id"] + ",位置`" + n["pointer"] + "`", + "", + n["meaning"], + "", + "```text", + n["text"], + "```", + "", + ] + lines += ["### 固定原件索引", ""] + for k, e in enumerate(b["sources"]): + data = (OUT / e["local_file"]).read_bytes() + assert hashlib.sha256(data).hexdigest() == e["sha256"] + lines += [ + f"{k}. {e['claim']};{e['file']} 第{e['lines'][0]}~{e['lines'][1]}行;" + f"提交{e['commit']};SHA256 {e['sha256']};{e['url']}", + "", + ] + index.append(dict(document=b["source_path"], **e)) + (OUT.parent / "SDPose视频骨架图固定参考中文说明.md").write_text( + "\n".join(lines).rstrip() + "\n" + ) + (OUT / "fixed-source-index.json").write_text( + json.dumps(index, ensure_ascii=False, indent=2) + "\n" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/sdpose-document-evidence/repeat.py b/docs/hel-892/sdpose-document-evidence/repeat.py new file mode 100644 index 00000000..3ebe9ad8 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/repeat.py @@ -0,0 +1,50 @@ +"""Repeat every deterministic audit and compare reviewed resource/package byte identities.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +import sys + +from build_definition import OUT, REPO, canonical +from rebuild import RESOURCE, build_all + + +def main(): + a, overview = build_all() + b, again = build_all() + assert a == b and overview == again + assert a == json.loads((REPO / RESOURCE).read_bytes()) + names = [ + "audit-summary.json", + "review-delta.json", + "import-protection.json", + "boundaries.json", + "package-check.json", + "source-check.json", + "source-graph.json", + ] + subprocess.run([sys.executable, str(OUT / "recompute.py")], cwd=REPO, check=True) + before = {p: hashlib.sha256((OUT / p).read_bytes()).hexdigest() for p in names} + subprocess.run([sys.executable, str(OUT / "recompute.py")], cwd=REPO, check=True) + assert before == {p: hashlib.sha256((OUT / p).read_bytes()).hexdigest() for p in names} + (OUT / "repeatability.json").write_text( + json.dumps( + dict( + definitions=15, + repeated_build_equal=True, + repeated_audits_equal=True, + resource_sha256=hashlib.sha256(canonical(a)).hexdigest(), + artifacts=before, + ), + ensure_ascii=False, + indent=2, + ) + + "\n" + ) + print("PASS repeated 15 definitions and upgrade/audit/package recomputation: zero difference") + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/sdpose-document-evidence/repeatability.json b/docs/hel-892/sdpose-document-evidence/repeatability.json new file mode 100644 index 00000000..63a9d0b8 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/repeatability.json @@ -0,0 +1,15 @@ +{ + "definitions": 15, + "repeated_build_equal": true, + "repeated_audits_equal": true, + "resource_sha256": "53d6768d83d271488fff8ad6787574cfc7669cee6a71e739e5f10ca88d6b01f1", + "artifacts": { + "audit-summary.json": "b79c3f138241cc4c82f8530637349ec411fc8bd92de0668a07e2a88c4a2cbb7a", + "review-delta.json": "f538e36f8089699aa829e2b9876e0a865282c5a7bb27f5332ebf060b3656db7c", + "import-protection.json": "e7765811ff574084478c57c072c6011f71908d082fceb0f644755bd91013541c", + "boundaries.json": "4f0dacaba3fb1cb43aeb5a14cf6694c7b3093a4e1f614e951dcfe788a1cdaf58", + "package-check.json": "38f29e69f5349c51f217d9d53a2a4402e8366fac3b8ee4462e3eb2b75b666f60", + "source-check.json": "6119daf0edfe44c9a183b396ae4ff898dd8423527dcc477971ee1a15916317ba", + "source-graph.json": "b1be4622bfdadbbe4bd7f4ce5061417e92ffec8749a66dd4fff24ea8667859a2" + } +} diff --git a/docs/hel-892/sdpose-document-evidence/repeatability.txt b/docs/hel-892/sdpose-document-evidence/repeatability.txt new file mode 100644 index 00000000..a7e3c9fc --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/repeatability.txt @@ -0,0 +1,3 @@ +PASS actual 7291887 upgrade1/skip154, repeat155, rollback1, edits1/29cols, fresh155, 1217/3660/294, 15 definitions, frozen boundaries, wheel/sdist +PASS actual 7291887 upgrade1/skip154, repeat155, rollback1, edits1/29cols, fresh155, 1217/3660/294, 15 definitions, frozen boundaries, wheel/sdist +PASS repeated 15 definitions and upgrade/audit/package recomputation: zero difference diff --git a/docs/hel-892/sdpose-document-evidence/review-delta.json b/docs/hel-892/sdpose-document-evidence/review-delta.json new file mode 100644 index 00000000..ab3c7811 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/review-delta.json @@ -0,0 +1,15 @@ +{ + "base": "729188740379e8fc2e1cad1ca9abe4fbb25e7614", + "changed_paths": [ + "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json" + ], + "other_reviews_unchanged": 155, + "old_blocks_unchanged": 14, + "old_saved": 376, + "old_notes": 13, + "new_saved": 18, + "new_notes": 1, + "total_documents": 15, + "total_saved": 394, + "total_notes": 14 +} diff --git a/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.json b/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.json new file mode 100644 index 00000000..2c260fe7 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.json @@ -0,0 +1,2591 @@ +{ + "source": "https://api.github.com/repos/Comfy-Org/ComfyUI/tarball/b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "archive_sha256": "13b3be6c8fba62c2eae9421a1feafca5410fd3a1b6dcd9b8ef263cdf2cd97713", + "python_files_scanned": 516, + "matches": [], + "files": [ + { + "file": ".ci/update_windows/update.py", + "sha256": "95af41facaec54aee4db35127c1d3070cd860f90f07f063997ba57b7cc436468", + "contains_sdpose": false + }, + { + "file": "alembic_db/env.py", + "sha256": "1b8d83698b12e982913702e7eeb65d35d9d95fcd3030d506f469ebb11b739847", + "contains_sdpose": false + }, + { + "file": "alembic_db/versions/0001_assets.py", + "sha256": "08f403013fb7ec36de5522ee648c20f4c5f47f2a0a6b0cc338bb6bd4cc61a12e", + "contains_sdpose": false + }, + { + "file": "api_server/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "api_server/routes/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "api_server/routes/internal/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "api_server/routes/internal/internal_routes.py", + "sha256": "2c1735cee6b4801c0ebf53c75c7a2e3d2dd618e1fa4e172f141e7c81485dd9cb", + "contains_sdpose": false + }, + { + "file": "api_server/services/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "api_server/services/terminal_service.py", + "sha256": "1c0d2f19846f028368b48f97e4d8dfc5bfe55e97b9870c82e5975dfcd978c541", + "contains_sdpose": false + }, + { + "file": "api_server/utils/file_operations.py", + "sha256": "eb30b1276eb3e95c9e412a4738ba6b518838793064ae2c26b2dbbdae100404de", + "contains_sdpose": false + }, + { + "file": "app/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "app/app_settings.py", + "sha256": "81b82d52c16ebe37368984c49cfbefc232173f013bbe2a65c012d2b147ab8d24", + "contains_sdpose": false + }, + { + "file": "app/assets/api/routes.py", + "sha256": "40e9e6ca553c443c8a07c3c9db6433de14b9355363574bbfc58fcdb85d127cb2", + "contains_sdpose": false + }, + { + "file": "app/assets/api/schemas_in.py", + "sha256": "05ef50afb053914984302e1c04cbc4c1958e407f34b43253042c4d87b06fdeed", + "contains_sdpose": false + }, + { + "file": "app/assets/api/schemas_out.py", + "sha256": "e0565c98b7d4743b4af3ad169fcbde09b342ac0c093c01118dc55b1e6e1635b0", + "contains_sdpose": false + }, + { + "file": "app/assets/database/bulk_ops.py", + "sha256": "6fed1704f6b83929d62f91515b81eb536fca71eaf8ac5a581be23ee877249420", + "contains_sdpose": false + }, + { + "file": "app/assets/database/models.py", + "sha256": "75b19bb5dac3db789f0ce149fae916e3d6ef7118037dbe607a4ff7cec8e4bffa", + "contains_sdpose": false + }, + { + "file": "app/assets/database/queries.py", + "sha256": "ab94a188c8e52bf544d41a7b69b9f72aa1a2fa97b01b397bb8512c4754847c3c", + "contains_sdpose": false + }, + { + "file": "app/assets/database/tags.py", + "sha256": "584afc8c62bb7b2d1bf708e2afc0db617246e0b1e84c3392540b8d8fb3756b17", + "contains_sdpose": false + }, + { + "file": "app/assets/hashing.py", + "sha256": "4afeeb0aeef238d60662939ef4098f3dc6b90c085395d49bc6fe87c9459d5995", + "contains_sdpose": false + }, + { + "file": "app/assets/helpers.py", + "sha256": "14a2754c623f22a1cab21ae1be689eb32f62cca920e65a4dd0742fb4a370a2e9", + "contains_sdpose": false + }, + { + "file": "app/assets/manager.py", + "sha256": "8c14eaa9719e3bd11ad4a1d9125b87f4fbcd3dc2abf1bbabc44f3263528ece7b", + "contains_sdpose": false + }, + { + "file": "app/assets/scanner.py", + "sha256": "94a276c1dec3be6aabd7b16555e0234945e01594be8684985df8f445a77292b5", + "contains_sdpose": false + }, + { + "file": "app/custom_node_manager.py", + "sha256": "d6612239c8dbe1e195438f5157dbb97af4543ac018d42f8876783cf7d0ef879b", + "contains_sdpose": false + }, + { + "file": "app/database/db.py", + "sha256": "6c04bacfb9d5c465fc6ceb1712f21c7987f061fd3671113ed4ac82d04f08d731", + "contains_sdpose": false + }, + { + "file": "app/database/models.py", + "sha256": "3d35eb5f996c696f583c627688d44cec9a5a99d2c9241af6e9d0f374b2732cc9", + "contains_sdpose": false + }, + { + "file": "app/frontend_management.py", + "sha256": "c3b3f4c67bb792ef667837654b74420f05ad8e3756e9415264fa6ec42784d1d9", + "contains_sdpose": false + }, + { + "file": "app/logger.py", + "sha256": "50e3dac8a05417b20bfd3b52ea0a7d0bcf1370094b2c6f0ac5988e487f5e7508", + "contains_sdpose": false + }, + { + "file": "app/model_manager.py", + "sha256": "b373e88c32a4a51f660c56a37bf7a163407bec6df2b8beeffe68ff4846163931", + "contains_sdpose": false + }, + { + "file": "app/node_replace_manager.py", + "sha256": "5103b53b29ce317d743d1db2d696a0352a91603896c44c3c24a3892e2cfe4935", + "contains_sdpose": false + }, + { + "file": "app/subgraph_manager.py", + "sha256": "2f35e747b0112d397d66c52b466e2d649d62175a5414ea8a6810783db040ecf0", + "contains_sdpose": false + }, + { + "file": "app/user_manager.py", + "sha256": "d86f677580cee23d70e513eab43bc1f1f7e411ed4a1d9ec5bded4641d188bb58", + "contains_sdpose": false + }, + { + "file": "blueprints/.glsl/update_blueprints.py", + "sha256": "295ee85281d09daddc6189a2eab5d884fc8208845f9eff2576d87e6a55c1605e", + "contains_sdpose": false + }, + { + "file": "comfy/audio_encoders/audio_encoders.py", + "sha256": "de67701a160747d011cafe1040778ae214ce8fea774e0ac7d38bd81eda01ae0d", + "contains_sdpose": false + }, + { + "file": "comfy/audio_encoders/wav2vec2.py", + "sha256": "32494297021e54e42845276255a026ce8ab62be5d54f6d40cecfb042c8b238e7", + "contains_sdpose": false + }, + { + "file": "comfy/audio_encoders/whisper.py", + "sha256": "f0e214e79fdfa9926fbc863038fe3e0455caa61f486a1b37a3039ca7253dea22", + "contains_sdpose": false + }, + { + "file": "comfy/cldm/cldm.py", + "sha256": "8d189e4d12a40fa13b9355804cc5091c71f2493f71d2deefcd108b6c49ad8e5d", + "contains_sdpose": false + }, + { + "file": "comfy/cldm/control_types.py", + "sha256": "5f36dc8bbfae9fbde48e822c210a9fe2bd571b547b7e33f8d15ce6892abc40c8", + "contains_sdpose": false + }, + { + "file": "comfy/cldm/dit_embedder.py", + "sha256": "b369b4ac62b85378554ffd985ccd537af08b1c5de2aa0243c081d4545f561160", + "contains_sdpose": false + }, + { + "file": "comfy/cldm/mmdit.py", + "sha256": "5c2b2165f0e69e81a7d2c0556b12f43fd87bbe86157eb19142badc621afe6415", + "contains_sdpose": false + }, + { + "file": "comfy/cli_args.py", + "sha256": "fcf9f687080a2a277ab1c1e1e5a6567252f0e8412f6f78e18397a9091dec638d", + "contains_sdpose": false + }, + { + "file": "comfy/clip_model.py", + "sha256": "08be993d86c3b494b58305fb868638b4b525bbe40abead89e9c94da021716845", + "contains_sdpose": false + }, + { + "file": "comfy/clip_vision.py", + "sha256": "bebc60b1295cb0a87ba35bdd093d07e662e366c1cb9f7a9a16b36467631b943b", + "contains_sdpose": false + }, + { + "file": "comfy/comfy_types/__init__.py", + "sha256": "da3601f9bf71f36070985bd835df311a06e1c40dbcc86afd13e63cd84ed3054b", + "contains_sdpose": false + }, + { + "file": "comfy/comfy_types/examples/example_nodes.py", + "sha256": "5192aa34ed909eb0d50a57c0fb47e7af011524962d09443172970fc1974d568b", + "contains_sdpose": false + }, + { + "file": "comfy/comfy_types/node_typing.py", + "sha256": "d2b9f72641064cb7a12954c3c1818e509d81676a44ede155b18e68e0d29e5601", + "contains_sdpose": false + }, + { + "file": "comfy/conds.py", + "sha256": "be2e5766726d9cf3a886b610a986a548f1c05f74d788f328c022ca0c56b7b9b0", + "contains_sdpose": false + }, + { + "file": "comfy/context_windows.py", + "sha256": "bb6da5b6b070e7984dd826dbfead53dfed4b7ea1140ab84fab36b350abb112df", + "contains_sdpose": false + }, + { + "file": "comfy/controlnet.py", + "sha256": "a7867eda256029f49f22e5315eb3a15ee13b60bb06438bb4044a50018413933e", + "contains_sdpose": false + }, + { + "file": "comfy/diffusers_convert.py", + "sha256": "8dc4e2b4de8dce831de48d766460e9b98c178b25b0737154f135253046a22c54", + "contains_sdpose": false + }, + { + "file": "comfy/diffusers_load.py", + "sha256": "25af9c4032d11ed63fc974f83e937e562736a358b7eaf176c88edfbfea4c8a3d", + "contains_sdpose": false + }, + { + "file": "comfy/extra_samplers/uni_pc.py", + "sha256": "62a3bc207d60d10fc2700459c2090961ffa9f1199f1f1213ade0e4b97be6b04c", + "contains_sdpose": false + }, + { + "file": "comfy/float.py", + "sha256": "cb41b8258603108185d61d06def13ba6de4b879b59fa1817700678cfbaa2b291", + "contains_sdpose": false + }, + { + "file": "comfy/gligen.py", + "sha256": "87c4297809a1a0a7727e3623cef0930463080dfedc068eb97c5e19bc6e155d0c", + "contains_sdpose": false + }, + { + "file": "comfy/hooks.py", + "sha256": "fe25f401b6ed1d28c03375010668fc61262b3434f043b9025429d099bf499ce1", + "contains_sdpose": false + }, + { + "file": "comfy/image_encoders/dino2.py", + "sha256": "8a00699aa819298c0d2872f763107b5e47f41f84e46f02f8934af90fdcf80d75", + "contains_sdpose": false + }, + { + "file": "comfy/k_diffusion/deis.py", + "sha256": "8d4e5057a062b77ef2e33af8208a2d6a3c3fbb431315a4c37689a307d66bc807", + "contains_sdpose": false + }, + { + "file": "comfy/k_diffusion/sa_solver.py", + "sha256": "84f54b743f6491ea8e0a8ff21db88579016e374c9b7a05b3d84c3ac4454af461", + "contains_sdpose": false + }, + { + "file": "comfy/k_diffusion/sampling.py", + "sha256": "288372feaf015569460eeb85bf8622487f39f998d1ca1e7100bab6240b2b0242", + "contains_sdpose": false + }, + { + "file": "comfy/k_diffusion/utils.py", + "sha256": "fc30630d8a0e4520b2e864c8f84deea3231c9b04d3f1404fec93fc425f629272", + "contains_sdpose": false + }, + { + "file": "comfy/latent_formats.py", + "sha256": "2a00faccd3ef266f39d65d4cda6146707917dbcc67faaa94384359555dd81197", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/ace_step15.py", + "sha256": "bde413c0680f828a89d051fad9ea1c1e73b9f875dcb8426da6aa243a9bf4517e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/attention.py", + "sha256": "7d50970bd668e25b8d09f9fb8e70d0b0b2b852d3ad236af89832efd9ced25d8f", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/lyric_encoder.py", + "sha256": "f6506034c513af1fc0790b62dce1769583d464a4be8f0ef8eabfbd1e0e86a103", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/model.py", + "sha256": "4a4487c566fa5118d16ee8d91bd0ffff523f89513fe2ff2968c5dd18b55a3708", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/vae/autoencoder_dc.py", + "sha256": "6a3f8fde53ff086b38fcf39ed2cc6cd6b5ccac04d253793a7df1d0110e69fb47", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/vae/music_dcae_pipeline.py", + "sha256": "21c2740c2c06544a7cb91ce526e248a2b4d9a85068612dee80a12f79b66ea608", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/vae/music_log_mel.py", + "sha256": "81f34c4e5b69ce0f5c2cc338840b1a0bc45c76505c0c84a332c9691778565fe1", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/ace/vae/music_vocoder.py", + "sha256": "8e36c57b90456110756264cd9a81898dbec98992f4c5a3e6487682f234626f37", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/anima/model.py", + "sha256": "af8cf8bca4709b69f82e59fb24b3a893065c677951fe568f0fbf3306c6053a7f", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/audio/autoencoder.py", + "sha256": "4e89cd715a5fba03404ef0417acf27607b541cd0f4c63cc3a7988e2570d9abe8", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/audio/dit.py", + "sha256": "1812d326ef06401fdfb26d82f6b2af2e684b79e1603223046f513ad21ccacf3d", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/audio/embedders.py", + "sha256": "876e59ac8fac94aa44aae3461fa6f70f9f280fb53b6c297ec0031f23bedf86fd", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/aura/mmdit.py", + "sha256": "0104396eda01a9f78e8aa5b9d15470fc551aa8b0e05137d264f3515fd1739db1", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/common.py", + "sha256": "a89d6aff5ae6fc5362bb2c312a41d673c931ee992a874b3d7a76b3d496038d49", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/controlnet.py", + "sha256": "d3e73da50ea4abee4d25aec6b015b3390235fad507c336db336e16ce041047b6", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/stage_a.py", + "sha256": "c7abbb219dd269f8b6c79ea39bd9ad47836463aa412066a207e4550c0bd61b4e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/stage_b.py", + "sha256": "b37db6fb8022a1af93b919afbf3728189ab00c519ed67771ed07ee06b89ce292", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/stage_c.py", + "sha256": "be52f2650be0643c8358cf29c4d20ba8432c84147bc3d5d46526007f1de11e68", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cascade/stage_c_coder.py", + "sha256": "158834cc63866e3d39364b62c92c12897f1f1692df61b07e9cf44fd14a210cb8", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/chroma/layers.py", + "sha256": "1d08fdde7b1a9ea98b6ce9a79bcd4394e5df9a0bb3872a458f79cb11bcfec25f", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/chroma/model.py", + "sha256": "e8bdf9b0f080c71a5d215a11d5a1344af8ef220b6251466c124e261ccddbfb0e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/chroma_radiance/layers.py", + "sha256": "5fb5db77eb257e40ba4f1a02674bcee96a864dd3779abdf061c66b00f4ef7684", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/chroma_radiance/model.py", + "sha256": "872bf2613d90b075a5147c493396d0f23a4181b0f668262f7db07f7fa0cb85b5", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/common_dit.py", + "sha256": "5e2459be4a47073a17e6b806f2b93962b4df1cdcaa2ac1890c9573bf942edf82", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/blocks.py", + "sha256": "085f29f34564c6f6d7063e131ac71adf9a826dbad5f27ca71d4430d9de8db46b", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/cosmos_tokenizer/layers3d.py", + "sha256": "c4829d538352aa750518f8c1a08e636925cf15067f02aa28eae5aa87d5c26805", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/cosmos_tokenizer/patching.py", + "sha256": "fc616c155fcf610a8436ca567f971d1bbe57e84a6eba7dfc5146a8b5c624802d", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/cosmos_tokenizer/utils.py", + "sha256": "1ad10120d40c9bf16a0377c14ae69827fc803f449f67add26fa799adcaa723e4", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/model.py", + "sha256": "70e1cf6ddc1e47a370cd86dcdd6e9e4f5ad078cbe352cad4457ba5407bdc66c2", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/position_embedding.py", + "sha256": "ab27e03b9af1ecafba7062ef9e63d6092f71fa12c872e43ad8107df7b27b7fa0", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/predict2.py", + "sha256": "9b093ded2eb22fc981eabcbd55286779b3f70912b2703e41299d32ebe89e8603", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/cosmos/vae.py", + "sha256": "3a61205726e35fb1d7235d75a470ae118f32e564d49f1c38b7575884f74f6734", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/flux/controlnet.py", + "sha256": "a96fb5494200b424cfb3f26d754b58f5e0f6d9bd126c3fd4ca9499934aab1742", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/flux/layers.py", + "sha256": "c1a122e4f13c931a314304771a4dc9bd68fa56609147755844254dd8bc005970", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/flux/math.py", + "sha256": "b50cadb6b1a9c08d1808a61d005997d5506fbdae29f765a1cc8eab4e73433183", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/flux/model.py", + "sha256": "012ae9d9e91b6de21f6db3b139011187a719979e0e6c51ba5a43857e275a26bf", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/flux/redux.py", + "sha256": "3b7abf43e15fc7b9613a64e701635f943351fa47f5036d87427ea672f93c7952", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/joint_model/asymm_models_joint.py", + "sha256": "59137d17f39231ca7b3db318d863a49f8d47857ba73e7db6993e1f1f62609dbe", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/joint_model/layers.py", + "sha256": "bb0ae6cc4dee093547688f667e307bc37d83697d7342dc944f20499682321c95", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/joint_model/rope_mixed.py", + "sha256": "c5289a2c591f34180fbef7dd709f9a83d5f40a34437250ac2d873883c6925de8", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/joint_model/temporal_rope.py", + "sha256": "1217d5d66c5ab329a0cead747ddd6362e579391b89dda599ce3b789f0e6752f9", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/joint_model/utils.py", + "sha256": "1aaa9f12fcdb6b0889d20bcb28a5447dc9a2639d39f3c217fb210d4584be76cd", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/genmo/vae/model.py", + "sha256": "31969951bb82ca2a074dbcfd4f68a71699b973c7233b55908fb209b939b950ce", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hidream/model.py", + "sha256": "8b8f8a2b776a7f6bae998f9bd4d024eebf9aaa975a9aee34eaa9e68ed874f20e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan3d/model.py", + "sha256": "a3772417ab78adf948b748f12c3fc056aab708ce8987c5ace0acb2e38c3822f2", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan3d/vae.py", + "sha256": "a7105097141ea8ca7bee4f5f0ae0b2386c9b55794421df325986a08789baa0b9", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan3dv2_1/hunyuandit.py", + "sha256": "ade250dc9d5b3e64265bf082981b2491f471d430c98e3e96e4a50ba59c267415", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan_video/model.py", + "sha256": "08d7d536baf000f6bd3f4e9426ab92911249293af6535f65865aabc05a73ec27", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan_video/upsampler.py", + "sha256": "f667649504185a70023cd6f51033d904d08da6455bc198d613a7e1faa802ce75", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan_video/vae.py", + "sha256": "1798354ab2c572a5496ab599eb42ca6db53c21ec497ac5cd76c77c902d589a78", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hunyuan_video/vae_refiner.py", + "sha256": "8fd6c7dc5878e68037192d824fa2185e4e95be89772fb95a309f87ff3a591302", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hydit/attn_layers.py", + "sha256": "667b14aff9a834392e424845c0002c5c24d62d6a89cf29f26ea0cf0fd2a2d8ea", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hydit/controlnet.py", + "sha256": "9032da47faac4f9c6720a038ee253bac29037d53918e0ce51e8b8e90269e5402", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hydit/models.py", + "sha256": "6eae0dc6cfd470f6780aea14a5937d64fc4c79f42695ad5a1a27d04878631ee2", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hydit/poolers.py", + "sha256": "6cdc7f171c65a9676fcdccc24598feda7fc991e3eef2c3fe8d183965f9c0d4ae", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/hydit/posemb_layers.py", + "sha256": "3a3bc020e6f54cee869ff453d1c7650257093e775486d2559c7e6c8d3a7879f5", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/kandinsky5/model.py", + "sha256": "b15df50678b81907069126d4a8112e4a966122447c11766658e380845ee77efc", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/av_model.py", + "sha256": "6e7afdebbe5c07af7e743514c1df615fd5eb8923f6f31f55b1af0da2a0bb8611", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/embeddings_connector.py", + "sha256": "4ba32dceef633a93f1ad4b3f12ddf81540a8362018fce8cabb5ade17d2e8122a", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/latent_upsampler.py", + "sha256": "04d36045252d475daf4dfa058e77b5327616595e66012da8c81fce254e962207", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/model.py", + "sha256": "096b8771b196e7b26b871145a9466f50644189ce2e800ce3a3b7f1847bca62d8", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/symmetric_patchifier.py", + "sha256": "e2d9b8de7a5cc003e74eaba6d0b8303b596df80e59a431eda2d3593ec06c2633", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/audio_vae.py", + "sha256": "d09d57c77ff61e0250d80b235232ad0fa3a15ce61d7018baa4a270fc836dd4ac", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/causal_audio_autoencoder.py", + "sha256": "79fece24a7eaa95594ac0040e8fdd22d72e9b512ec992b2332763e3ac51f31ac", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/causal_conv3d.py", + "sha256": "51c282bec3e91a3ad555e3256cc9b3467cf045317b1d8d5e776a526cf9ea21a4", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/causal_video_autoencoder.py", + "sha256": "fa180e5ebe51eb54b419c250ffe50e36f61d6cd3359b09e090b5686b169b2198", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/conv_nd_factory.py", + "sha256": "8433bd731dd379223d58a4fd84518ae9a618e1b067771878c8f2d51339c9a99a", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/dual_conv3d.py", + "sha256": "2683701b800960aac74766f03cb4bc7a3cb10b80e881422e63cf5d6f5896b2c9", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vae/pixel_norm.py", + "sha256": "37163441070d3ea85bcccf9a603bc1f19a4ee8e9da2afadfa8bba7a1db6e96da", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lightricks/vocoders/vocoder.py", + "sha256": "7d9a92f70205cfbb3b7ff2bf0f8aec8789913646fb07936c6ad108437e562ad3", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lumina/controlnet.py", + "sha256": "8330e0f92d70b23b4f6d4fa0661e240fac2cf211ff70d897f99ffebfd9f1d541", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/lumina/model.py", + "sha256": "a22f2e9e4d4cb30f09063809eaec45763af24eda121ae955f5e04f26e1849ced", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/activations.py", + "sha256": "59994f9372c5dd2996a9617d648c7684a89075aedd1d093c0281538e40e38faf", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/alias_free_torch.py", + "sha256": "c9f316a443b00bed4c2d50fbd23a4d7b2f7d16656a2a7642744f216f12e2ae8d", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/autoencoder.py", + "sha256": "4d4409dadcaac71f34a7eb3199543b4f6029efe09344dbd3b99a8c07a3f814a5", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/bigvgan.py", + "sha256": "cc5b4947bde63cc9bedb8689003dce11f9f82ed682bc4a23fb90235a2208eb9e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/distributions.py", + "sha256": "3ae3040d1e43ecfff4ea9daa7807fa345e28cf93ae5e34d29436d49bb11df772", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/vae.py", + "sha256": "44b6f466317bf8a566642a4bbf6a30af4943aa52a343cdff66ce802207eea554", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/mmaudio/vae/vae_modules.py", + "sha256": "7b2453fefae854da384c70f780c6cb3290f607f0d45eb3a6f191faeba2704b78", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/models/autoencoder.py", + "sha256": "6427c354d3962c0cd4d29299a02c774c80f07481d13c2e28f024208a40886cfd", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/attention.py", + "sha256": "3f3eca8146b0e7051693149ac91f29ddf94a620ab8525797879d0834e1853f50", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/mmdit.py", + "sha256": "d48ab3b4ec1634cffa8db055395d9c8a739af9b882795f43e3b04bdd4dc514b6", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/model.py", + "sha256": "73f7f53eb7db4d3b04e1520597a78f437b5329873c601d061fc54cba4bd0de7a", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/openaimodel.py", + "sha256": "bc5473d49bffb246bfa8aaba070333e9e75faf505057f70db461e9cb15a8377e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/upscaling.py", + "sha256": "396721fe4d6c8b825f06264aa8b62ec52b399908e8c51d519d67a4d072699084", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/diffusionmodules/util.py", + "sha256": "18db468ff259fda6737c0aee17a9d007d08b0067945e9164fd5d0221926a671e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/distributions/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/distributions/distributions.py", + "sha256": "3ae3040d1e43ecfff4ea9daa7807fa345e28cf93ae5e34d29436d49bb11df772", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/ema.py", + "sha256": "6185e8296e3ed8adf6fe857b09761cc469240e400a3f0f291917b5ffb8169e4c", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/encoders/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/encoders/noise_aug_modules.py", + "sha256": "a8592cddf9514e27b93031d60437875cf9e89a6d03c2ff668cdf656d63f6a118", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/sub_quadratic_attention.py", + "sha256": "75ac1407c65cebfea9bee8f0a9958fea6051ea49e737916fe33463f07acaa32e", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/modules/temporal_ae.py", + "sha256": "f39314a670256eeed4a6b558eb29f1340569a0b0e4d42b2fe887271839ab822d", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/omnigen/omnigen2.py", + "sha256": "fffd7b9ba0d75a1a5ce2cac9d8e2040bcfa72d3d1d7aab0225240d03eedaec51", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/pixart/blocks.py", + "sha256": "82d610edcde7a7a52bccdbeb5b2312e9ff20ff530eacf91e29592be1a02cc281", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/pixart/pixartms.py", + "sha256": "a3b24e4e3c3c4d6a31ec9835d8ea269c0742551afe3b16cef2a8c44390c82661", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/qwen_image/controlnet.py", + "sha256": "807f9932af334410e8491f79bbb7d327dba654f28f4d01e5cedf0435218c7afd", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/qwen_image/model.py", + "sha256": "f56ec99c19ea7ff79347cfcdbc48c4eb73b1b118adf40b85e29dd94724137c27", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/util.py", + "sha256": "17a2619515f23ee1ed29ce86552abaf03cb0ab819cf6a629d396524ef3da69bd", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/wan/model.py", + "sha256": "c2433c7e7dcaf165fac178412728fc512d6018f2a0504b7c5d031fc24a747ac6", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/wan/model_animate.py", + "sha256": "291c35a2b327aa68454d458681b35ba69746dcce84185d6b2337b27182324449", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/wan/model_multitalk.py", + "sha256": "a467f5e4b3d8b88bd996ef95dae7074453a4dead2d17671c15cc457757cd2ee8", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/wan/vae.py", + "sha256": "500c33177204197f29131056ad399620be67dc41e088e7a98dc8a9ee4fc22a1c", + "contains_sdpose": false + }, + { + "file": "comfy/ldm/wan/vae2_2.py", + "sha256": "951acd5ef15de85a923ca471659acf02adb281a13ce754bdf7ff0d4c547214a5", + "contains_sdpose": false + }, + { + "file": "comfy/lora.py", + "sha256": "03487abeb8e0eca6b44e635ead530d9b60829d8cfa68df9327a6d4f82cdde5e1", + "contains_sdpose": false + }, + { + "file": "comfy/lora_convert.py", + "sha256": "0790e993706b6e5c255fd4000f8f48abed80e318274da5264681eb799df25d0b", + "contains_sdpose": false + }, + { + "file": "comfy/memory_management.py", + "sha256": "673983119e53a2bf675b052c93b947cc0dd45f1c85b38509605d7336df4d07c9", + "contains_sdpose": false + }, + { + "file": "comfy/model_base.py", + "sha256": "2644ce5da75142fa70525c10e6704b60447f67ad06f5fbcf4e9ea5d19f0ff721", + "contains_sdpose": false + }, + { + "file": "comfy/model_detection.py", + "sha256": "97b7c37a4863f0feeee1fa280f72149b46bb75b4b7c9aafd4503acbf40d0eb65", + "contains_sdpose": false + }, + { + "file": "comfy/model_management.py", + "sha256": "1be9ae7c97151ef516badacf8d4609a70952ae712dcfc283d859bf17e07e18d8", + "contains_sdpose": false + }, + { + "file": "comfy/model_patcher.py", + "sha256": "3ac24fe832450fdad344a1c0948189619e6fffd675718cd1dfef6e2ec98329b6", + "contains_sdpose": false + }, + { + "file": "comfy/model_sampling.py", + "sha256": "127dd382157084b35d7500c83552bb40c0b9287ed09096ee699dd3695aa7c04a", + "contains_sdpose": false + }, + { + "file": "comfy/nested_tensor.py", + "sha256": "fa663325d09ec898c1bd05506a301fb1dd0c7d71580a57c2db87d843b7e49373", + "contains_sdpose": false + }, + { + "file": "comfy/ops.py", + "sha256": "65e258ebee22cb357000f71f3fa041e853296fa7f160ef72bc4c3b44b94fb5fc", + "contains_sdpose": false + }, + { + "file": "comfy/options.py", + "sha256": "a9d0bb41f5b8d393efc264e83e5f3003ce52c87aca585c0e8ab97bbaea87c8bb", + "contains_sdpose": false + }, + { + "file": "comfy/patcher_extension.py", + "sha256": "954df9bf0805a9018f78a1cc40a4bece91021bb7c5b66e305895d69a8ffe740d", + "contains_sdpose": false + }, + { + "file": "comfy/pinned_memory.py", + "sha256": "4b72ff8cf533a06252544cc1312e112aed21d4e34a9e90bb669f55f8d855f049", + "contains_sdpose": false + }, + { + "file": "comfy/pixel_space_convert.py", + "sha256": "60cc5e4ea109da1e384ca3121121098b0f295e012dec6ca1c73779c2ed9d8cbf", + "contains_sdpose": false + }, + { + "file": "comfy/quant_ops.py", + "sha256": "1fcf48c70a8e60e720026e9ed16325e553f1e5beda4c986a9598eb620627f00e", + "contains_sdpose": false + }, + { + "file": "comfy/rmsnorm.py", + "sha256": "ae72e451ef087e25b77f9f46e5339c08a579ece1f751656ee52b191e4d8438d4", + "contains_sdpose": false + }, + { + "file": "comfy/sample.py", + "sha256": "7123f89ac74e6bef191b8686aa71d11d6f6041b8689dce6a1757e8dcd4cc11c3", + "contains_sdpose": false + }, + { + "file": "comfy/sampler_helpers.py", + "sha256": "5d5196a4b009267d76fdbb12240edf53b2492336f45dd1d0fcc61efde602967a", + "contains_sdpose": false + }, + { + "file": "comfy/samplers.py", + "sha256": "fd6cbfa24850937d204c5428cec78f8708595c1ea7417a159925baaaf2a235cf", + "contains_sdpose": false + }, + { + "file": "comfy/sd.py", + "sha256": "9b3fa8b961c9a246503e787a58b6196f7ddbb6e1088ea3b54ebcaff3be27c2f8", + "contains_sdpose": false + }, + { + "file": "comfy/sd1_clip.py", + "sha256": "c1556cf11cc98f9345f31e5c702ea6f278f911ec485cb99dd56939fc1b3d0bc8", + "contains_sdpose": false + }, + { + "file": "comfy/sdxl_clip.py", + "sha256": "dd3c01e1c302876612897c0051baa6e108751e36abcba7327490b25a571f97fd", + "contains_sdpose": false + }, + { + "file": "comfy/supported_models.py", + "sha256": "9158e8ee5c438565af65f4586354a33ea2c9a82e90d3440c893a1e02ad2995fa", + "contains_sdpose": false + }, + { + "file": "comfy/supported_models_base.py", + "sha256": "a42dc13d789ede0dcb140fc0a4ab36bb57d820be0aa2b931c274863ec7666596", + "contains_sdpose": false + }, + { + "file": "comfy/t2i_adapter/adapter.py", + "sha256": "efc52cc85f941e11b509c0339e8950a6680d031b09bec36736d8834b9ccfa1af", + "contains_sdpose": false + }, + { + "file": "comfy/taesd/taehv.py", + "sha256": "8175fefa6b4580ca0eb2f1cc58adde60a1ee85090f642e645161c79f100e22aa", + "contains_sdpose": false + }, + { + "file": "comfy/taesd/taesd.py", + "sha256": "86d1edb6e5bb3d003a6802aafdc4754c4e73bad53241cf8c180081f561f52361", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/ace.py", + "sha256": "f200d0a8579b43e4e9994bdba7298063c5fc8aa5f06fe0c377f704341a5f4bb4", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/ace15.py", + "sha256": "958576c3ed996fc5e8d1ac9a3c8317d96e7c684093c096e410931caed51cd142", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/ace_text_cleaners.py", + "sha256": "798e1d7d2e29a0a98a1d0bac53a058d5c0c90346f660b3d1aee0622ade85a9c3", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/anima.py", + "sha256": "7eef5186d57c7f6d4b23ecdebb454ae9b64def8117d0e7a57b0b537de64c69c5", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/aura_t5.py", + "sha256": "d20edaa3fea38bb65359941882546c42ba1142ba70fe9933d766aeddac9c4ab3", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/bert.py", + "sha256": "3f1f32353da95790285a10f452959a871aa949aab15a89b646a95abc6165955c", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/cosmos.py", + "sha256": "98c09ef00e0b0953bfae891ca2df97c3d70fdbfbacb1165168fe74eaff230524", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/flux.py", + "sha256": "b843d69b3dce064ca929a7176d84fce38c1ec0851eb1d8971b0345c25e3adb2d", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/genmo.py", + "sha256": "dfbf5c44111595ecfcb531a7b6e6d8e32a6c629d176fa90a932865a57dbbd84b", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/hidream.py", + "sha256": "fa4c0e7c438254a12fe877d9e1db1b13723b473ddab8f43bf5e2cf2b56ad6d75", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/hunyuan_image.py", + "sha256": "ab462b226963fc4aa56ef8956195227a8f7e07622353353ef7e5a8ee20a84b9f", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/hunyuan_video.py", + "sha256": "5e9001d75b3eaaed8bb145be1b1b2a39d012140c11a45078b21beed2ddabae4e", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/hydit.py", + "sha256": "3a56925c2ef403e888b2bd2187aaa5c0fdbf16ad16c88c282da095603873e748", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/jina_clip_2.py", + "sha256": "d5f8f32dc9ebcdc55956bc6249f115c78483555bdd895b82814376d06a6fb3d1", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/kandinsky5.py", + "sha256": "1de8b4f8744946ce52914c03b8e10da1b897a720672401b91f8ddb5897e201f8", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/llama.py", + "sha256": "303b6efc6f1107f2f81385e6d9e9cb4b09509a8e73203b6b36b85af3dac3ba9f", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/long_clipl.py", + "sha256": "ec23dfced81defe857d88d3cb4536c07ffe8f9c7ab03e9506589e87b73b81508", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/lt.py", + "sha256": "3f065951ee4fbdbce11a273e4f55a1db8864e393eb8d6b2bc81e7b1e93272736", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/lumina2.py", + "sha256": "928eec6fc0b06f3d8b0ecfb1985178771720a871a0ce095c84659956a6587bb1", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/newbie.py", + "sha256": "444a1bed8e47d27a1b5672e488689f8adb92879198326b99fc1ca03180d52ac4", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/omnigen2.py", + "sha256": "ef76972277b8b2141172ea2e53685bdeb26f2ff383c679946f10ff3396067c92", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/ovis.py", + "sha256": "80749123bfa24b2947fef548101a17cd73085e6743b07dd1cb3f30490f45b65f", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/pixart_t5.py", + "sha256": "9645107e3fcaafb8adf74b74f7444bc7cf4c9e8b05cdcb7651d65b1798d3d8ac", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/qwen_image.py", + "sha256": "9eab4371988f5b5e55260aba00e3984996d8efd4851569cc7e54b0e39811c1a9", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/qwen_vl.py", + "sha256": "a640420d310ba2acc29e2fa9a11fde72fc5de87541c3bc6c3cb293cc37ef89b2", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/sa_t5.py", + "sha256": "ec3913c5fd9a5d209d8f21ee031a61f30c30f9b1c9d6e7c96124429a699a7421", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/sd2_clip.py", + "sha256": "f271a816164925da14895a742a323cd3149d651a8600c916d6ee71080fde4f6e", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/sd3_clip.py", + "sha256": "61bde2b4a428779469a01f342a9195d115f2a207c7a3d2c0d6c0a5715fdc03ed", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/spiece_tokenizer.py", + "sha256": "300de9904c109171b2270524a35c372e6b8c145b88b3f9d242613d45c2bb559f", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/t5.py", + "sha256": "797f11b69256dffa8d9a6d236fe1e05d0c250c84d231a5993accde0ff44238bc", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/wan.py", + "sha256": "e9a6ca356790c76f7a36550842fc8a93c8c584cd175d69615eaddb7b4cd276bc", + "contains_sdpose": false + }, + { + "file": "comfy/text_encoders/z_image.py", + "sha256": "c6d1d15054ec8f6b1b5cddb759f5e637aa64dd9ffeaa937e266f03e035550aed", + "contains_sdpose": false + }, + { + "file": "comfy/utils.py", + "sha256": "feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/__init__.py", + "sha256": "d9fe388a6bd3b93212a5e04b8921759841e2cf88939cfcc3a7bf59e16505edd0", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/base.py", + "sha256": "484f0d83a96e700f80c793e4bcc6a897d633233e51a59191d91da5e59da345c7", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/boft.py", + "sha256": "2850e0b4c2295cd87445415e287061fa3bfd69e88bd0aeb3eb16064864bd078d", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/bypass.py", + "sha256": "618c286c5f74e823318f41774e02cfcfa02d74ee9d51320ec0aa2694cd74aa8e", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/glora.py", + "sha256": "31cdd03f5b0beaa0df055512560128930f4f26b219ba57602d21abb086425b09", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/loha.py", + "sha256": "579ca1e33e0d244e0d7eedd30fb727913341f8e7bfbd74b51221f567612286d5", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/lokr.py", + "sha256": "b4763cc32215a47e4d906cfa6cbad9cf893f6a1329ada2225fda81fd99fcfeb4", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/lora.py", + "sha256": "e506062b4eb189be4c36f88270e0fd4dcce038c79a98f7163604ed6b44efe4b5", + "contains_sdpose": false + }, + { + "file": "comfy/weight_adapter/oft.py", + "sha256": "88be3c32f610478bc6900a10009eaadf6fe2af973ed4861731e4f21e1afacf89", + "contains_sdpose": false + }, + { + "file": "comfy/windows.py", + "sha256": "7d8c2188a52fb7761740706c7e77c937f34e3f3bb81e1c7c7cae162ec76795d0", + "contains_sdpose": false + }, + { + "file": "comfy_api/feature_flags.py", + "sha256": "66d39871bf03aaf0916022d1fbfe867de54b92a9633864c0e7483660062f38d7", + "contains_sdpose": false + }, + { + "file": "comfy_api/generate_api_stubs.py", + "sha256": "dedd55dd7d8aa54c65e98130e2bf763bf28e5245dc958cc4aa84d5f09c356fb0", + "contains_sdpose": false + }, + { + "file": "comfy_api/input/__init__.py", + "sha256": "2abb56f7ad62d2fa794182e50e2d1609f75226e1e0a5ea5e8de4ec1779ecc7bc", + "contains_sdpose": false + }, + { + "file": "comfy_api/input/basic_types.py", + "sha256": "c91648aa1bde3cc53be02edd4e941ee3695f9c0323df37aba8d8b80b1db59feb", + "contains_sdpose": false + }, + { + "file": "comfy_api/input/video_types.py", + "sha256": "76ef537120fdab8077412ff1cb3c5739f3748dd818fa6bbc07829af5001b20d7", + "contains_sdpose": false + }, + { + "file": "comfy_api/input_impl/__init__.py", + "sha256": "6cfebda2a205d94112f9a1105b07bafaf2038d83ffd630ab7875f6bfa5896209", + "contains_sdpose": false + }, + { + "file": "comfy_api/input_impl/video_types.py", + "sha256": "27c2f86c4c5407f93d7dfe3b38c78eab968c0c38fb6617c21c7e531912c9ee6d", + "contains_sdpose": false + }, + { + "file": "comfy_api/internal/__init__.py", + "sha256": "50786f7e2ebc910ed9becddf066e92d7924b7f6080189651067bbcd839e8a410", + "contains_sdpose": false + }, + { + "file": "comfy_api/internal/api_registry.py", + "sha256": "af85d1a93c400e21a43aa7b9ce71968e373e36f5e1560c07d1b7493b8b96e898", + "contains_sdpose": false + }, + { + "file": "comfy_api/internal/async_to_sync.py", + "sha256": "3507b0fbe2b9dea365d4f8b4a891e791714f7b27b17c6d055a3116f2d965aa4c", + "contains_sdpose": false + }, + { + "file": "comfy_api/internal/singleton.py", + "sha256": "b3cac979c6c4c8f58a49658b25ebb91b347e0c5ecb74b3f4f4f2ab606da227b5", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/__init__.py", + "sha256": "cab4e83cfdc8ba5c1d09e4ad59c4129f5a53dbfe8d3d8698d25994e1b0d39737", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_input/__init__.py", + "sha256": "2ce34537b981cdb0b8643795e3387cbc291a3a971a834d7fc2d0c49680bdddc5", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_input/basic_types.py", + "sha256": "99251ecb404c881f28a413d4c0829fdf5345a1897dfac76ed6199863601098b1", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_input/video_types.py", + "sha256": "6a4cdb3085ed8a4289e63168536e9a530c95aad94c7e2de1eddf8738af11f5a7", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_input_impl/__init__.py", + "sha256": "9aa2f9fef661ae1016edf8fb650c805c3e40c01d82597717f125b253507ec72c", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_input_impl/video_types.py", + "sha256": "df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_io.py", + "sha256": "babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_io_public.py", + "sha256": "c805d754d61aba1ea72ed2d9d5c371de35be9affa5305d35426fb298fcb7c046", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_ui.py", + "sha256": "c3ff901299ffb58e3aceb6ab672254d21e2e9822e346786c0ed3bba56b93d67f", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_ui_public.py", + "sha256": "7104ffcac91481c1d05e9417904c93afe6a126590e06e587c140e2f3d4039431", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_util/__init__.py", + "sha256": "a00432018a3aa989a98d94470c657bfef2a89031fe1e844c19a616636291ba0a", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_util/geometry_types.py", + "sha256": "635d028ba1d0766f03ff4000bfa3f5bb3aa3cca30c45dbe495bf5625f1955636", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_util/image_types.py", + "sha256": "1704789d3bbb5570eb7dae16537a20aa88b63cd551dd54b5ee91781732efc606", + "contains_sdpose": false + }, + { + "file": "comfy_api/latest/_util/video_types.py", + "sha256": "b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02", + "contains_sdpose": false + }, + { + "file": "comfy_api/torch_helpers/__init__.py", + "sha256": "41f6e44e920c989823e5b073bc283267ed12ca8eebad2bd1f18e4c9deb551d95", + "contains_sdpose": false + }, + { + "file": "comfy_api/torch_helpers/torch_compile.py", + "sha256": "e370434c6eeae612e50fec47207faad6c2a181d5a1b836fe7e41bfb10eb11452", + "contains_sdpose": false + }, + { + "file": "comfy_api/util.py", + "sha256": "453521345c5667dcec73af1428a7ea6bfde2da465037c5c196447cada20a6df7", + "contains_sdpose": false + }, + { + "file": "comfy_api/util/__init__.py", + "sha256": "9bc0e255f67dd12b90505435f13ea20d75b8f6a632a0acd7a378524e17dccc28", + "contains_sdpose": false + }, + { + "file": "comfy_api/util/video_types.py", + "sha256": "24257c6644e1a1ff2b0607c9bfb2d9d6def185ebd4052f24058f872fa5c01cd5", + "contains_sdpose": false + }, + { + "file": "comfy_api/v0_0_1/__init__.py", + "sha256": "453b9e1201848282aed093055234670b5a873f282389affc4ca5aceeff3b5e97", + "contains_sdpose": false + }, + { + "file": "comfy_api/v0_0_2/__init__.py", + "sha256": "2f2037752244ce0ae0629b2380da528bfe9b7896c785be2c37bc586cebab4e4b", + "contains_sdpose": false + }, + { + "file": "comfy_api/version_list.py", + "sha256": "e2f89c64de13af56fb33a7aa20710174e84236fe017cdc8da7f40fa76093e73e", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/__init__.py", + "sha256": "759ec9868ae35507e98ea694939ea5bce19d4d29307cf1e73ce6418df94fd74c", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/bfl.py", + "sha256": "67d7c254169395475cf33ea1a5abc57235dfb54883a99be4b0599d732eff2e32", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/bria.py", + "sha256": "f97c6b9e09de8600a1c13043e3d7f1a51d63ff9abcba37d1371c1964dab7a9fc", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/bytedance.py", + "sha256": "b3a0429200268a1387e96ff5cb347dbfba5dc23389c0c75e87aac54ef54d7346", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/elevenlabs.py", + "sha256": "46a4376cadf34f8d192c9b23cd8261e61adca31961ca98ae4b2a9d5912552545", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/gemini.py", + "sha256": "8549344ec9ced05b4757bc04875bb88ab9fecc9887eb7df83ae2b02ad1c5462c", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/grok.py", + "sha256": "db97ef824c6ee6002ccbaa3692aca9f9023eb24096efbedef548b0da7abbda28", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/hitpaw.py", + "sha256": "df2e5bc200512990cdac52fe7ef947cbb9d9a1be322b27e2a84c6d7ff6fceb60", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/hunyuan3d.py", + "sha256": "38c1bc3ce433cfa8ec1fa2c0e1baa8a6e7469306266c65dbca874f2c5e865c41", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/ideogram.py", + "sha256": "c09e2bf2821920a89dafdb08c090de4993a3c4947f77fb14edffaecb97ecbfa3", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/kling.py", + "sha256": "12dc8d00843af35ce632b420840360c2ddd02072564b6e003670eb24264c7ce6", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/luma.py", + "sha256": "37d30be76abe43e2cb0b64dfddf4743f3633655818082f8e2ac8feeca445dd4f", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/magnific.py", + "sha256": "ba86587c4590507ee80324eeffe5e3bba7b354c1c8cb72d3a141d3c8b3647dec", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/meshy.py", + "sha256": "bdb1b817eac3da71ab00e11bc9f2b751f35898461efd951424de7b248b77fdd5", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/minimax.py", + "sha256": "30b06dee64de0444a8432248b14edeb8b15065d7574732edb4d20db5f2ebdfc9", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/moonvalley.py", + "sha256": "46676f4d7b6e1359694d4f2ed3e058723cbe67f477291df5c8ad22f537c92999", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/openai.py", + "sha256": "6c4701c905e8d85221d491101d33f145e043eb3a9a0330bf9d2e0c13cdb513ac", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/pixverse.py", + "sha256": "65283c394fc513f8b8197fcca00b14fdec7cbc4509ebcebb757d31026f4f7f59", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/recraft.py", + "sha256": "d79053616cf73098c0586dc8cc5640aec8c02af7275091afb15bc1dd2dd85ef7", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/rodin.py", + "sha256": "ae6858b492f3bee4002f550eda696e90713c35c8f2adf7b07652b910c82e6664", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/runway.py", + "sha256": "0cf8031b207c5860eb42eed387c0c0c5db429ed09a44f6ca7d4a70f99e9c8d69", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/stability.py", + "sha256": "4cdc8f1296c89f19de222fe25cced4b7eb56fd13ff5521c04c3633d165fa421f", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/topaz.py", + "sha256": "543bf30fec53424aedd7a37d8546ae110fe35119b1d7fe88ba68a5297d10fed0", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/tripo.py", + "sha256": "065d45fbafaea74e7dd99d7239ee29e7f9590e78c215017f4b37f1720f25ec9f", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/veo.py", + "sha256": "5f6fdbf413254f290dd0b08e73624fced09818c1646a09132d0d87ac945dbe30", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/vidu.py", + "sha256": "d7e5441a01a76765c6cd8d664fdeb889a56b912b8f31c0d0524ed7fbd49f46da", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/apis/wavespeed.py", + "sha256": "0df5d2558af088b8ff76d2ec877e3a004416b6ae29077729c272cfa64dd8216a", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_bfl.py", + "sha256": "fa2849b8f9d0b8d8f6b5f5143df3b6a0f9d3aa8d06ca064d7f135e4c7d1ee054", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_bria.py", + "sha256": "7cae0925f69813c84df8cbe4d1a1e1baeb6a6391df16542bdfd060488c756e2f", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_bytedance.py", + "sha256": "981de43a108d2ef7cca9ece091e02657c5bd5fd4df7e0400bd5eed4d92498aba", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_elevenlabs.py", + "sha256": "a82a26fb41beb3e34b9a1cae946d511b729b26c8a9e1513e10c2463b9eb2f3f0", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_gemini.py", + "sha256": "fe0498c3a55bd146cb6f1ce945074faef293fa2aa95e3ea3ec7bed896dab3501", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_grok.py", + "sha256": "007b9b73123b300a9474e073f7f4374c7151995cc6e73b3c38d398957878a7db", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_hitpaw.py", + "sha256": "480aae6f3e5730c73f02734ce11f0cb709471a5e74a6ae56a7edef514194d91e", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_hunyuan3d.py", + "sha256": "78e7cbc84bd4aea3b3e8066cb7cca6d81a25982382e2d3da82a36e042446c865", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_ideogram.py", + "sha256": "5868e3455a79dcecbccd4f00c88779d63343153d1f49938ac311e744fc9ca1b4", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_kling.py", + "sha256": "af33fbc192ea0f41ed292aaf53a53d80681c21aa319a68001099d6402d5d463b", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_ltxv.py", + "sha256": "1d625d4ebf73ad48c1c825aa76d134e64463b6d37970d6487999af51212bb863", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_luma.py", + "sha256": "25d616212498c4beeb7f4afab192bc85ef853c7154fafa4c898940b168249b00", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_magnific.py", + "sha256": "02aa7c7208119c0a8f5b390b120241ea69cc74af4a153287f6faba6413e68a65", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_meshy.py", + "sha256": "6cf084a6cd390c4da54f74777d95448ee84e63d50485bbb589d3734b43ac5cc5", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_minimax.py", + "sha256": "be0abac3c8db7b212144bcc105b249b8f1d5537533f20af3a2bef2cf87022e63", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_moonvalley.py", + "sha256": "c0378e424a70576a53b78b24122a9e0ca88f2e8a128767f1cceff270f69380ba", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_openai.py", + "sha256": "ac6430dabddcc9afabc17bf44dafc92fe6fd4b6d95f976e72181da7a3c90aec6", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_pixverse.py", + "sha256": "29c78894f0770ec1ff77bdbe0fefbc59e6b912ef0ec10a664d1c891bf993e699", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_recraft.py", + "sha256": "3591ea4a1a51f700bc6dde06701e2f831c2f9250d9256f4ea8fca2055a2c44de", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_rodin.py", + "sha256": "965a78c0b35975b36e587b244df88374ef0cabbee16049b51669da217bf7f003", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_runway.py", + "sha256": "cf7232ed14ba9085e1062ed97a86d422c13dbe1de0d814a14fa8f826e5898114", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_sora.py", + "sha256": "a13b17fe8090cd8b9922173e5e4cca8c2e608ce4b530333f7cafb631346333f9", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_stability.py", + "sha256": "e7d0f84468d13e408df581af8e598178416755868ff949b0fafdc7aebf5bcde6", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_topaz.py", + "sha256": "358b3a74e59f0c4b5b2b1037563f12efeb42be0993b571b0a297275b6ea8db37", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_tripo.py", + "sha256": "384397be8123708d0b6501894dba64a0b636bff6bc20f8add0ca5c1819f21e3c", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_veo2.py", + "sha256": "70a54b3aed4020dfb4be581e5a9381f013bd01dfbdf4e63b52d4231ae3761645", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_vidu.py", + "sha256": "f1c39370fa698358cbc2bf0ce642c92b6bead6f4cbeeb4659b8afcacd68382e8", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_wan.py", + "sha256": "4ea2022e622e2b4bcd1918e2ddcc969ffcacf55f02b3b7f5d90341db362aee82", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/nodes_wavespeed.py", + "sha256": "788a3b603d2fb0b1903f64e12a79f6e460619d3de5b2dbd28241f8bc8dc2550f", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/__init__.py", + "sha256": "1b1334a57c2e96b674f908fb1069abf0ad434e34193d464cc41490d4675fc1b7", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/_helpers.py", + "sha256": "3c120ba89656f713d1db190843039023cd247236c0536fcd7e3f6ddbba13f132", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/client.py", + "sha256": "88e10f4edd49782078ac050b453c96271c14632730317cd3d4a5d50a67dd5881", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/common_exceptions.py", + "sha256": "110910ae364e25d95cd3885d1433703cca3d574dc388a16863173372caa16a0b", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/conversions.py", + "sha256": "3e75935a92040b73a97f49a5bd78c207fa1bbe189bf5b2d8fcaa8e967655f3aa", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/download_helpers.py", + "sha256": "094a9ea17d02cc4481ea2b920298d3ec33cf09ea47205b001a5b30e708838495", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/request_logger.py", + "sha256": "57b4666ff1811264800931f90a19a4cff2dead597c056137b8d716c0c1feda85", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/upload_helpers.py", + "sha256": "1f0516d291e1916517993a30fd205be5c8ae37d6c1ea37b51980a0e2069adc84", + "contains_sdpose": false + }, + { + "file": "comfy_api_nodes/util/validation_utils.py", + "sha256": "77554cc809f651f54943f73e6391b8899b3a52779d949edfc08166d8fdf86c66", + "contains_sdpose": false + }, + { + "file": "comfy_config/config_parser.py", + "sha256": "83029c05dd6dc960a07db4012bbb0d16aa170ee02090e1f68457c651511f0db6", + "contains_sdpose": false + }, + { + "file": "comfy_config/types.py", + "sha256": "54af7087783882b4eafded50f92ba89aa2cce177befa026ff90d93d630907665", + "contains_sdpose": false + }, + { + "file": "comfy_execution/caching.py", + "sha256": "a16b6cc1e0907b425ab620ebe84ce70f585410536bbfb75c9715ac2c038557d3", + "contains_sdpose": false + }, + { + "file": "comfy_execution/graph.py", + "sha256": "d92ec5087c138c681e833b3dec8c61d37f3b4098aa7ab9bb84cdf6988ceb9414", + "contains_sdpose": false + }, + { + "file": "comfy_execution/graph_utils.py", + "sha256": "dabb3f75952a1398891ed87ad853d4ea9c929f322ce6997d4ea916adbc2f209d", + "contains_sdpose": false + }, + { + "file": "comfy_execution/jobs.py", + "sha256": "c6c8fb05c68f4c2eaf833e8310fd62c768fb0abc1edc8c376cd7a8778f2f1610", + "contains_sdpose": false + }, + { + "file": "comfy_execution/progress.py", + "sha256": "5f498c795be879213bff2344d62605fcf0cfc550eb8fd26e3532c75e99393131", + "contains_sdpose": false + }, + { + "file": "comfy_execution/utils.py", + "sha256": "f80e6020f8f60754ebf15f194670c12ba57a46458b0c185694d8198e428f7be4", + "contains_sdpose": false + }, + { + "file": "comfy_execution/validation.py", + "sha256": "9a8ef75b7c53fc6a2d5dcdd75cabe63d47d4f527257b4de2a1138990f76709ae", + "contains_sdpose": false + }, + { + "file": "comfy_extras/chainner_models/model_loading.py", + "sha256": "77a335bd0a09350d313d814c46bd030fa22c4766244a93fb659be39e7fc9c4a2", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_ace.py", + "sha256": "059133d7b5ea8e2d2edd06df01cd5e611ab0000367fa21902026f52de1362e8e", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_advanced_samplers.py", + "sha256": "6431678bb0ec742625dfaf16e828b28f7617aa13c16961c96179fb8c79948c73", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_align_your_steps.py", + "sha256": "c78c0ec0c8e407cda18ad5ae9f9eb7d456d6e204df857f3e9f8e8ebd8a21ee91", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_apg.py", + "sha256": "d0584e329425cc960478597dc4530c27f4b778ffacb943e522a21a07c78c0f63", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_attention_multiply.py", + "sha256": "bf17050a2146c27b21d933ddbd2003234490b9e47ff557adac1c2c64c42434a4", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_audio.py", + "sha256": "3b126494a63be63fb90707aea819d2f492dbdcb06e1dc4f964a3036aead394ed", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_audio_encoder.py", + "sha256": "97cc72dd876f20d43fdff75aea52566d1728b668a76fbd348c8ad4078a6b6cb9", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_camera_trajectory.py", + "sha256": "88f78ce7dd65f9f2e8eacce8bb6e25f685528e9bb4fd45affc8337352420fd20", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_canny.py", + "sha256": "b7b6921ccc650b0c3ed708bc33366e7351b2002e14070acbfae8c6596ab842e0", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_cfg.py", + "sha256": "d48ad5d3a84c1080e53550d4b259b2843e85d1b77502aef5026691ba6649ab40", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_chroma_radiance.py", + "sha256": "680884cf1fddd3a835f616ec9899672452d94c6176acaab2d01391e7f88d95ca", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_clip_sdxl.py", + "sha256": "f78dba317dc2a7b43801d32217709e5f60af63088a9993658409db4267d5d3ae", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_color.py", + "sha256": "c04d77ae66c0481b81cbf27314272851bfeff1930c8a713d04fecf6c692c743b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_compositing.py", + "sha256": "3ef9f03b3a8aedb173f9bd96c063d5a1c1ce95be1b06984b226738892db36aeb", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_cond.py", + "sha256": "9672e44bc739bf5b0ce400dad25ae1ff6e32e6bf5ee29dae66048459f8bf6d44", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_context_windows.py", + "sha256": "c96b7fadd984806d41b22ce00f92d032b5892cec94cab45cd6253ae545110d1e", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_controlnet.py", + "sha256": "d807ba4b48753d46c13c77e27e944b68f4a68f92350d14fa0c2946462974a1c6", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_cosmos.py", + "sha256": "3beb089416e722270f6d1a2c8212008b5e600edc92e75540fe372815bc44c9b9", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_custom_sampler.py", + "sha256": "7e06b75ee557082508a3493cdddac9c131acd80c002c7e79fb8592c78f84dc5c", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_dataset.py", + "sha256": "ec26df2e49cefa07c396925cc135b8a93a9150331eb42e1dd5d3b11dc396faaf", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_differential_diffusion.py", + "sha256": "56ee7c6eb70a11bb64cd73d56dbec1ec11eca0b6800aba30e9a4d5cc1f55798d", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_easycache.py", + "sha256": "a4345ef9841d6b1c94be367b4efae030d7873baa33933d067199591b6da5da30", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_edit_model.py", + "sha256": "e8d03a4ca5f7b8025f565d0fa7b4f0119693f2f35837db2a4114361537f78da3", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_eps.py", + "sha256": "f1b04fb532598697c7b567c4ed4e466f6ae887999490bfba66065a5a7ece9c1f", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_flux.py", + "sha256": "17d1cf5772c4e0ef83fbe114fc410d22b4ddd96efcf6bbe5c27382a348e28fb0", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_freelunch.py", + "sha256": "a2f79257fdfb7590df14846d7372d2281b72720a44e427993c356de7166342b0", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_fresca.py", + "sha256": "6985a670faf68c3ff9f056398159e743d6ef313980058c3f5d63bfd7c2a74fde", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_gits.py", + "sha256": "5119d2e7b60275aaf58c9693149496018de89d298e4ee5c36ffe5fc335e14c6c", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_glsl.py", + "sha256": "f0933c5a87001952a3293b6472beb54456eb32c7f69903818c8e4b220059e5ab", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hidream.py", + "sha256": "1d2cc590c282db3e848a4d59951cadbeffcb971ef4e1fb760e7fd2de17766d9a", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hooks.py", + "sha256": "5cae284b705e12b1789a7c4d7dd50fdcd6aa21f6a6d0b7001f57c9a7323e6a50", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hunyuan.py", + "sha256": "cff4f6b68902048ac55fd7dff37fb294a09b299a2817f23acc039911931ce1e3", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hunyuan3d.py", + "sha256": "6239e51d4dbc5de2dbe8bdc14b20ad472a6ab6db424c936709910fae1b66b8a0", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hypernetwork.py", + "sha256": "f91cd2ebea4e38d83b89aa6dba7ab2d7b7dd78b08491d8e0ddb4d79e5e91ffc7", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_hypertile.py", + "sha256": "860457f0f5ec9053bc07457d10726b17d4561c02e7d4143c79cb03b8946eba29", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_image_compare.py", + "sha256": "6f2cca3d36290994d23b28cfbc7dbf9a9a6acd143ecf71798cae672717718ae1", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_images.py", + "sha256": "d61b9ea369fd3b1c94d0d9e26235e4b27f6413fb9837a4f32d0b416a38446c5b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_ip2p.py", + "sha256": "72b4992b1418e8112e0501816495fa10c4c1c0dc2d287a316a8a1769fb326554", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_kandinsky5.py", + "sha256": "e1eb4cba5e95de5b3d8fb69fdc128f449230b73d0a9fce4777ad8bdd5fc213c0", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_latent.py", + "sha256": "7afac8daa225e5dfd0e526e47545d1f929847ba2f4d1b6b9f5dac93585f05e6c", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_load_3d.py", + "sha256": "3707b88a58c33b169d182a763b7bbd16012bd3f96beb6105494ca76b52e1a584", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_logic.py", + "sha256": "fc6d8f56346aa637266ccd2da4c8a942d6bfcf5c1d9dd66f761d08a2fd0afd4b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lora_debug.py", + "sha256": "614d58ec5166e493c0d5a3dee525c434fff1c892f770c8f22cab87d86ed9f01b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lora_extract.py", + "sha256": "0b256573c6d37cd689fd66ab8d36a1dc7ae9452fdbb3d71333aa91ae5646ff57", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lotus.py", + "sha256": "8a408ede6fd1b83e913bfce585394ae2c17c748bd6d80f596a603f020253a903", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lt.py", + "sha256": "11778c5764a05966697e713e37081367f7b82506e57ae04a72ee501555a4d410", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lt_audio.py", + "sha256": "97f57848980915d9d8b41ca49ba4ce00407e48346ba4bda8da196f633b194191", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lt_upsampler.py", + "sha256": "b2d5e0599007dcfa8cf243e1facfd7a74a049895dae923859404a304297524e8", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_lumina2.py", + "sha256": "d6a19484ff4e92bd57129380f88a37b10eb9336914ea64ba09be86a88d81bac3", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_mahiro.py", + "sha256": "d66cd577cda5d8b09f869860da5b159baf3488c7269cb71432987d62167283e6", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_mask.py", + "sha256": "504946dc000194a6cd827cc355693195ec9c59f53b46563547aa2bfcf5aac9b5", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_mochi.py", + "sha256": "70f2abd2f6f02249b70a2f24682189d902bfd4eee6ec062aac71f54af22e5d32", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_model_advanced.py", + "sha256": "22633697285c450292a75f73ad123cc0e559f045d5c41d5e5a4053baa006fda2", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_model_downscale.py", + "sha256": "378507298838f6ca381e714a99b1c441428b4af443433c7d4eaaef4dabaac0c4", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_model_merging.py", + "sha256": "236f6ac8cdf35798c8f42e64b989b7ff2be609e77b280dcb1c0d6c4c4c12ada3", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_model_merging_model_specific.py", + "sha256": "c5e7f3b7d9735ea6a8f52f513f30846868bead443d77d01643a586268d635473", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_model_patch.py", + "sha256": "916f0f8ce816ced96e08a2365262ed6c86c0fe49dba0a99cccddbf22b0fe3465", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_morphology.py", + "sha256": "913d84e358b3a726f3b0901d8129c42c1907f984805c8da2adea7a900915cf9a", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_nag.py", + "sha256": "239608d6afa81adad93c0c670216c44217a875df7119e42db6645fb03c8dd25c", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_nop.py", + "sha256": "24aa9d23da794653c6e9084bea1696ed78c794335985d4c76be7be3b00949019", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_optimalsteps.py", + "sha256": "4825d82e67eae07bb7774280db9a2c00d3545e30036a5ad7715860e5d2983050", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_pag.py", + "sha256": "aa810f29eb718dcd772963a62fdb2dc7c3352db9dd77b06f0009b1afafc2ed4d", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_perpneg.py", + "sha256": "1efcafeb5a59e70ee7fde83fdb2cbad81e428b85f64a68b3c2a1c8683ec198d5", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_photomaker.py", + "sha256": "cfadf65f87a94cc2b7a8427c7f5f26125bbb402a647919056b73f4527be8633d", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_pixart.py", + "sha256": "17aa8bae15b3648c7bc9497bb314cd44897abcce63557a9b0ad6cb74e581e28e", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_post_processing.py", + "sha256": "220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_preview_any.py", + "sha256": "f8c526dbc4ec512f88a067524865f59eb24db636858f37d601e848885b2d0751", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_primitive.py", + "sha256": "3d89e428cb9259cee76f53932d9e6d53de8053cee98696072863190337b60a1b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_qwen.py", + "sha256": "4069f973a0c54357b734a387b00e62d4c62d161bb2b312f3ceb38de37c81342c", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_rebatch.py", + "sha256": "99d68e6aa9bb25b38fbe815a8b375b8157d2cd2ae571771d9d1ded089d87c66a", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_replacements.py", + "sha256": "f9f79a62cc770ed7cb802d454e99306c94342e546281f36b46d6e7da8ccc6543", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_rope.py", + "sha256": "e7b9f88d785198bb3b647adc24e6d514817ab39a0e498c4e805ca014e1366bac", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_sag.py", + "sha256": "aeca7698ee4c01af5f08d8c9481018e7f1b3c4fede297a69e1773ec8796e1b4b", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_sd3.py", + "sha256": "feb7e2b1b0de0fe3f76259dbd07181da4798ed4cb474783a4e333f1d4a4e7e90", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_sdupscale.py", + "sha256": "234e7183d43f89a6a12437d2db834d19d351a9501436296473d1b5a37564efcb", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_slg.py", + "sha256": "3042fb89646636eea114df5fa0090bdd8de26231bcd30bbfec304041e9ee1213", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_stable3d.py", + "sha256": "4e90a32e091f3363fb5ff1fc28bf117d1cc1acaf8e98962d8b2a92dd7f83ad59", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_stable_cascade.py", + "sha256": "78b60c70d106675f79935b0180a11b6c20d55c3ff897438d8cba3f3d08dca45f", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_string.py", + "sha256": "d6230ad4429a9f6b28fd9b84e318f3f3b3ec1cfd83e4f58eb3bb67f3ed5afcca", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_tcfg.py", + "sha256": "d5ff403cc129654eaeef0c7f90e5128e423b370323ad739b3f1f0d7f54242c12", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_textgen.py", + "sha256": "f73a48b2c8f0fbc9d46890f153897df4850017efb5f740f65435d4945fb87432", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_tomesd.py", + "sha256": "8788278a89618e67cfea1ecc19259e221c4e3942720d60224bdbc8c51cf26f80", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_toolkit.py", + "sha256": "6874d3d787ad285084d19f4bdf6e99c7d8d2a1e6795c4ca3ddaa29226d3c6d9d", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_torch_compile.py", + "sha256": "952b9a5577ab69cb42cc05436ca9529abfe2b3c028f2b286041d016076d05296", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_train.py", + "sha256": "6a2cad99f06bbb7d6110fb041d43f4713c024c532bf8f00eee4c4eae368e73b1", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_upscale_model.py", + "sha256": "a9312b53eff007d6fdfcc775f192539f6a53ae49ac8ed584229eb60a41f3a1af", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_video.py", + "sha256": "f1471c85dc93b5f8fbff0b5cd9665f4a81324b08e1c26c4d1229424683ddf959", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_video_model.py", + "sha256": "f63bec3e23925c0f972d1a6168b8f69e0c0ed7bd6608350cd22995b4b7ce1431", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_wan.py", + "sha256": "c78ca094495331cb9720999204cd62d0c707136339fdc70dd2046c59dd3ea9d5", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_wanmove.py", + "sha256": "02d90f09e6d22da249232e93f1a41686e165cee31c01fc0b39e4b2d88f968e77", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_webcam.py", + "sha256": "2ae1486e5820ba791cfcbc8839e90a3cf18b93a74f343fde3af7fc9a1b53816d", + "contains_sdpose": false + }, + { + "file": "comfy_extras/nodes_zimage.py", + "sha256": "1f4c82ecb33f7a283e2930ec9e79da364f8bd83f545f4e1c035e7147017cb196", + "contains_sdpose": false + }, + { + "file": "comfyui_version.py", + "sha256": "a5492fb262e41b93031594db800811a2b51b01fab5f03dda05310e78d378be5b", + "contains_sdpose": false + }, + { + "file": "cuda_malloc.py", + "sha256": "72987a4b841dbc1d22f138b68431b33b7a72793b107611e23b12d079714c25d1", + "contains_sdpose": false + }, + { + "file": "custom_nodes/websocket_image_save.py", + "sha256": "aaf447f75cd9e1391c0e76d6f9f6ea58c9770897e5bdbe8cb3ab5505829cef28", + "contains_sdpose": false + }, + { + "file": "execution.py", + "sha256": "08d452334b526b7a7b81b34e0c074b057815bdc9bfd864db0960ec0b9f17e2cd", + "contains_sdpose": false + }, + { + "file": "folder_paths.py", + "sha256": "da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112", + "contains_sdpose": false + }, + { + "file": "hook_breaker_ac10a0.py", + "sha256": "c8e343fd04e0bbe09c01ba758bf4225eef25976b8832b0d620491ab68357d563", + "contains_sdpose": false + }, + { + "file": "latent_preview.py", + "sha256": "963b44f86459d643906563eca3eb2b12e100274fa8f7f8f6e4f73cc21698c177", + "contains_sdpose": false + }, + { + "file": "main.py", + "sha256": "0708a86871c7a06ba3f83a1f739df3952db69bb7fadb9b9956803b474a7eb8fe", + "contains_sdpose": false + }, + { + "file": "middleware/__init__.py", + "sha256": "ed114348e2e135931a60478dc65c56aad2af8e7046b3de86274538ed3a964d70", + "contains_sdpose": false + }, + { + "file": "middleware/cache_middleware.py", + "sha256": "2e5bb5784fb2368460e1ae1e84a8a0af9b7638c9baec89e9272ca28b725157f0", + "contains_sdpose": false + }, + { + "file": "new_updater.py", + "sha256": "721b67b9df99c53eccaa1d976f3de23d6cb09f6ae39c87837522e8a64e192db9", + "contains_sdpose": false + }, + { + "file": "node_helpers.py", + "sha256": "5ee43a50f57b84c64781f1bcfeb717d17ee2d07038d5d7d75eb788898fb72de0", + "contains_sdpose": false + }, + { + "file": "nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4", + "contains_sdpose": false + }, + { + "file": "protocol.py", + "sha256": "169848a2606aa7623db97df4a25c68c81f180801c80abbc343d2a5bc23ef99ed", + "contains_sdpose": false + }, + { + "file": "script_examples/basic_api_example.py", + "sha256": "8bf77cd877f989445ca317efab08ae72c36071a2839bf1f0fc992e5907b005ec", + "contains_sdpose": false + }, + { + "file": "script_examples/websockets_api_example.py", + "sha256": "4a72a56f184092ee828b120e7920162f0499bfe11510d881d8df7fc2506e3532", + "contains_sdpose": false + }, + { + "file": "script_examples/websockets_api_example_ws_images.py", + "sha256": "dbe13a8da988d3dc6a85502e6e2be9ea1dff6b7c62c5378213bd17d6a4358213", + "contains_sdpose": false + }, + { + "file": "server.py", + "sha256": "3e261b8e88536bf5e48c0dd6f1cd3717f00653ed4e7b5fcd8e71cc2f35b71dce", + "contains_sdpose": false + }, + { + "file": "tests-unit/app_test/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests-unit/app_test/custom_node_manager_test.py", + "sha256": "52f71463d3d2215b862248a259a5ff47b4bbecf18f2efff53ce7824325bf36be", + "contains_sdpose": false + }, + { + "file": "tests-unit/app_test/frontend_manager_test.py", + "sha256": "a6a0a69a458c5a42b87e77ecea432565da291a2fe20e2187bfa7dcba248ed205", + "contains_sdpose": false + }, + { + "file": "tests-unit/app_test/model_manager_test.py", + "sha256": "e56ff9053a9821fd1c249dc509a42599dc1a5814aefe986ea2ff44fa38ff8381", + "contains_sdpose": false + }, + { + "file": "tests-unit/app_test/user_manager_system_user_test.py", + "sha256": "97418da1aac848b2881d86d9d4906cd02d710e9c410dd16fc84bdceb0b02255a", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/conftest.py", + "sha256": "657aec90e49ef294ca5b84491126ce5774dc1434626870a2724d96d29af101cc", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_assets_missing_sync.py", + "sha256": "ec766f4cddd362e79d1f2c6191bffbee705b75da06c1d1c2170cd6627208984b", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_crud.py", + "sha256": "c50ba3523e8f8f059ddb05a7debbcbe0897f9f5831c774e0705507d68a83b934", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_downloads.py", + "sha256": "f9145b56db92da568ce3783bdb89ad7942f315ed0a8882f242f9794daa2df582", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_list_filter.py", + "sha256": "6c4da376f6089148caa4d27f8eeadda664abda552977b8f17849e941751e5cdc", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_metadata_filters.py", + "sha256": "c15903ddccdf5ff4f0691753a5587014b99447b3380ff67f0640c31b85fce52b", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_prune_orphaned_assets.py", + "sha256": "9f186d0bd8a096cf74569ba4b29b403cd876d9113a04d4d5934e56b963f33cb1", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_tags.py", + "sha256": "3174e32825e5faa66a7afe66a7738f42ff34e90315e7869acbec2fe2ed3a87b5", + "contains_sdpose": false + }, + { + "file": "tests-unit/assets_test/test_uploads.py", + "sha256": "5e78f5e053c25604626061f8af9d09c528fae64218ac9d76af6c94ce3723ac87", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_api_test/input_impl_test.py", + "sha256": "5dff5e03365cebac4a8261bf3f4e00f2a0ae21ed14e4c2fa3b2995d54b51a9c2", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_api_test/video_types_test.py", + "sha256": "3934cf232c3faa281f64d64a6ef1d5f5b74f0a78e5aa48ec8af7c6a3154f9fc8", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_extras_test/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_extras_test/image_stitch_test.py", + "sha256": "f093f81daa5e0d96f22b7c6d049eabaabe4e5b81e0a654168a0d32d5d0abefb4", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_quant/test_mixed_precision.py", + "sha256": "1c349ae9ec5c041e2fdc25dbca122001c23444893c719eb65bd2072517b497be", + "contains_sdpose": false + }, + { + "file": "tests-unit/comfy_test/folder_path_test.py", + "sha256": "a60e306bf996673f758275aaf74b0a12fd2cd57ead7a9b9eea33defc252f5b3b", + "contains_sdpose": false + }, + { + "file": "tests-unit/execution_test/preview_method_override_test.py", + "sha256": "3f32b2423c1b6039c4467c8282502f53413734362d43c8b653d13a5f592c2189", + "contains_sdpose": false + }, + { + "file": "tests-unit/execution_test/validate_node_input_test.py", + "sha256": "20ebb9ac03e6764fdf56ea9c767e9b2612b047934498d8e7a77b434d77ae36f2", + "contains_sdpose": false + }, + { + "file": "tests-unit/feature_flags_test.py", + "sha256": "f489c0c5c10fcf1da8f37c4aa20cbf8f1c7ee58cc085111784d4076ddf12f487", + "contains_sdpose": false + }, + { + "file": "tests-unit/folder_paths_test/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests-unit/folder_paths_test/filter_by_content_types_test.py", + "sha256": "01779009773e055e1f50dc133939605fb0c09137fe09ccc5ffb87c6e5291a051", + "contains_sdpose": false + }, + { + "file": "tests-unit/folder_paths_test/misc_test.py", + "sha256": "15dfb4de4da88001abd590e575ab030447a353b8563642a50bf138e0c16a7b79", + "contains_sdpose": false + }, + { + "file": "tests-unit/folder_paths_test/system_user_test.py", + "sha256": "332b498f03cbe92899a15cb984429147e96be8b377921e0da94f07892d4d38be", + "contains_sdpose": false + }, + { + "file": "tests-unit/prompt_server_test/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests-unit/prompt_server_test/system_user_endpoint_test.py", + "sha256": "473a8eaa6b3ac38de370397c2fe89a83af32567f99967aea6775de7b11d926d7", + "contains_sdpose": false + }, + { + "file": "tests-unit/prompt_server_test/user_manager_test.py", + "sha256": "7746f47cc014aded98925912ee4062a9e71bc2fccff811f9b28584dd7e2526a8", + "contains_sdpose": false + }, + { + "file": "tests-unit/server/utils/file_operations_test.py", + "sha256": "bb72acd56711584ea4662ad6a731e664e5d0c5083f39cba905775959b50d2f15", + "contains_sdpose": false + }, + { + "file": "tests-unit/server_test/test_cache_control.py", + "sha256": "aa143f40be881973cd586f6045e7f1825511d283659cbf74a9d251cf927a63c6", + "contains_sdpose": false + }, + { + "file": "tests-unit/utils/extra_config_test.py", + "sha256": "fcaefb3a97947c0d9714a277f4163b48fe730f5ea8a951c5326ed91153d0fa39", + "contains_sdpose": false + }, + { + "file": "tests-unit/utils/json_util_test.py", + "sha256": "a186a15d30482c61824be48d99680d9c0d7d3dfc9600c105510e91573b858b76", + "contains_sdpose": false + }, + { + "file": "tests-unit/websocket_feature_flags_test.py", + "sha256": "f797760a3918e0956eb7a78700d3065002383ac3adc83ce73de0d1e367ecbfbf", + "contains_sdpose": false + }, + { + "file": "tests/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests/compare/conftest.py", + "sha256": "332aabadec90c6f1ad0cd0767251c7eb155fe600966c1019b6a8205b069f2964", + "contains_sdpose": false + }, + { + "file": "tests/compare/test_quality.py", + "sha256": "6798c6ec373fb636a728b0d1a1351de795336370804104789d4988321a5d413c", + "contains_sdpose": false + }, + { + "file": "tests/conftest.py", + "sha256": "86e9a6a6c37b59cb7ed4e3726c172ff940df61813b14ffd6e13c5df09db958ed", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_async_nodes.py", + "sha256": "7e76f033588dc3b53c240078b9a5b93a7fe2e41e7be1952caa603e2102e9957b", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_execution.py", + "sha256": "5f2925ae77ce643f7ced0491046b7bfb5db73a7d8a3bd0142f70825b8b0b5dc6", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_jobs.py", + "sha256": "c23148831f064193b89e371fd2eb6dcac1a578b75aaf6d72248e1d32aaef82c3", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_preview_method.py", + "sha256": "48856870ca35c638a09fbac60d57a8dd09db076e25207534735de1105dca8185", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_progress_isolation.py", + "sha256": "e4d118a925ce2fffdb7600bffbd6cb3b3e9386112e4687615cdc7d2a685bde32", + "contains_sdpose": false + }, + { + "file": "tests/execution/test_public_api.py", + "sha256": "851fc8f8b1d2bbac625c183a0063b0a490e489a87f4dc27c409df4bcc7c608f5", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/__init__.py", + "sha256": "a98f3b4e78e0a2e11473b9119c40c7d9b2bcbf9f25daba36d405377ca55a4208", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/api_test_nodes.py", + "sha256": "3191a18dcffef787e4748141e654bafe71cf289928c1038828c17946198e7ff6", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/async_test_nodes.py", + "sha256": "2792e3eea8d4669bb2e9f20ce0a510f73d5c01bac3862e638aada01f3863336d", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/conditions.py", + "sha256": "b350b905fe2fcda0044645018aded95eb1531775513d19b860c04ed6a49146b3", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/flow_control.py", + "sha256": "72b840c06716ee4b18603e6ee4575657368c4480e8514fd136a1711b5da3c20d", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/specific_tests.py", + "sha256": "434ebdc1cb3eb367bd14d8c83b8df5fafc31052906f8fe78a133b67ee3ca1499", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/stubs.py", + "sha256": "c1ad69dbb15e23e2647a1fb29eebcc97c00272c2d0c12e915a212781e080bcfe", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/tools.py", + "sha256": "ba8eb98fcecd9ea88ddb5428e0cbd74c7b3be59ed74c116fc2f42f04b0c0498e", + "contains_sdpose": false + }, + { + "file": "tests/execution/testing_nodes/testing-pack/util.py", + "sha256": "961ccd3ae62660008956fe743599a471a3525e16086cf3bcb7fbd2a2b1a2807b", + "contains_sdpose": false + }, + { + "file": "tests/inference/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "tests/inference/test_inference.py", + "sha256": "f8d80d9e6dc4ea416c010c3a892aa12cfd9ec4508732e74e0a472df2776fcd6f", + "contains_sdpose": false + }, + { + "file": "utils/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "contains_sdpose": false + }, + { + "file": "utils/extra_config.py", + "sha256": "ebb923e58956587acf5196e3a76ae3c576196f2f498e5933ce9416fca1ddaf9e", + "contains_sdpose": false + }, + { + "file": "utils/install_util.py", + "sha256": "16b29124ec4954d419da71760af8c06e5cd19cef02665096ee52a06e7dd1a888", + "contains_sdpose": false + }, + { + "file": "utils/json_util.py", + "sha256": "3aea39b1998b534bbbea434f243e447995f755a40020c4a62efd6e8960fb53ba", + "contains_sdpose": false + } + ], + "limitations": "仅本固定官方commit的Python文本搜索;不证明分叉、插件或目标安装状态。", + "imported_or_executed": false +} diff --git a/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.txt b/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.txt new file mode 100644 index 00000000..aa85a746 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.txt @@ -0,0 +1 @@ +PASS fixed core0.15.0 516 Python files: no case-insensitive SDPose text; no execution diff --git a/docs/hel-892/sdpose-document-evidence/source-check.json b/docs/hel-892/sdpose-document-evidence/source-check.json new file mode 100644 index 00000000..9f0fd92b --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/source-check.json @@ -0,0 +1,40 @@ +{ + "fixed_originals": 19, + "tags_to_full_commits": [ + { + "repo": "core0150", + "upstream": "ComfyUI", + "tag": "v0.15.0", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.15.0", + "tag_sha256": "f3c7ba4af6144b4be77d359a64191999032e106b58800208683051f1e703f59d", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "commit_record_sha256": "e2ba46fdda05c083b72f05a40d4f62d034cc772a0579e3f03a74152988244d3a", + "installed_or_executed": false + }, + { + "repo": "core0151", + "upstream": "ComfyUI", + "tag": "v0.15.1", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.15.1", + "tag_sha256": "9a8b752179bf5aac26a5f9c79e9cfc190042019390009c5761e8c9d1b13e282c", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "commit_record_sha256": "df64c3da930aebd32514b259f7b610bdd5a0cde3ebec46e2481e4e27d5f0ce4b", + "installed_or_executed": false + }, + { + "repo": "frontend", + "upstream": "ComfyUI_frontend", + "tag": "v1.39.19", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/ref/tags/v1.39.19", + "tag_sha256": "dbdd4d0ae2a418a58198a20be9606992af165501135c34b2c459b11fdb8641a1", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "commit_record_sha256": "ed59717c9b6ea008d633fad905ecb4e01d02b34094b2d4c781b930b2bd5837db", + "installed_or_executed": false + } + ], + "checked_sha256": true, + "imported_upstream": false +} diff --git a/docs/hel-892/sdpose-document-evidence/source-graph.json b/docs/hel-892/sdpose-document-evidence/source-graph.json new file mode 100644 index 00000000..85af80a6 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/source-graph.json @@ -0,0 +1,280 @@ +{ + "source_path": "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json", + "raw_sha256": "4586c72d8a906d4a956fb7d62307b81e57e4e345324c7e73f63103e56bfffd14", + "canonical_sha256": "dae110f5eb678ef378c44b3c8dc980297676008410dc82b3d55d78542394bcad", + "nodes": [ + { + "id": 686, + "type": "SDPoseDrawKeypoints", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + true, + true, + true, + true, + 4, + 2, + 0.5 + ], + "cnr_id": "comfy-core", + "ver": "0.15.0", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 684, + "type": "SDPoseKeypointExtractor", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + 16 + ], + "cnr_id": "comfy-core", + "ver": "0.15.0", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 685, + "type": "GetVideoComponents", + "mode": 0, + "widgets_key_present": false, + "widgets_values": null, + "cnr_id": "comfy-core", + "ver": "0.15.1", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 680, + "type": "SaveVideo", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + "video/ComfyUI", + "auto", + "auto" + ], + "cnr_id": "comfy-core", + "ver": "0.15.1", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 676, + "type": "MarkdownNote", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + "## Model Links (for Local Users)\n\n**checkpoints**\n\n- [sdpose_wholebody_fp16.safetensors](https://huggingface.co/Comfy-Org/SDPose/resolve/main/checkpoints/sdpose_wholebody_fp16.safetensors)\n\n\n## Model Storage Location\n\n```\n📂 ComfyUI/\n├── 📂 models/\n│ └── 📂 checkpoints/\n│ └── sdpose_wholebody_fp16.safetensors\n```\n\n## Report Issue\n\nNote: Please update ComfyUI first ([guide](https://docs.comfy.org/installation/update_comfyui)) and prepare required models. Desktop/Cloud will be updated after the stable release; nightly-supported models may not be included yet, please wait for the next stable release.\n\n- Cannot run / runtime errors: [ComfyUI/issues](https://github.com/Comfy-Org/ComfyUI/issues)\n- UI / frontend issues: [ComfyUI_frontend/issues](https://github.com/Comfy-Org/ComfyUI_frontend/issues)\n- Workflow issues: [workflow_templates/issues](https://github.com/Comfy-Org/workflow_templates/issues)\n" + ], + "cnr_id": null, + "ver": null, + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 682, + "type": "CheckpointLoaderSimple", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + "sdpose_wholebody_fp16.safetensors" + ], + "cnr_id": "comfy-core", + "ver": "0.15.0", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 679, + "type": "LoadVideo", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + "@小镜子(闺蜜的网课) 今天教大家如何在喜欢的人面前吃鸡蛋,好烫啊.mp4", + "image" + ], + "cnr_id": "comfy-core", + "ver": "0.15.1", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 683, + "type": "ResizeImageMaskNode", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + "scale longer dimension", + 1024, + "lanczos" + ], + "cnr_id": "comfy-core", + "ver": "0.15.0", + "ue": { + "widget_ue_connectable": {}, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + }, + { + "id": 681, + "type": "CreateVideo", + "mode": 0, + "widgets_key_present": true, + "widgets_values": [ + 30 + ], + "cnr_id": "comfy-core", + "ver": "0.15.1", + "ue": { + "widget_ue_connectable": { + "fps": true + }, + "version": "7.7.1", + "input_ue_unconnectable": {} + } + } + ], + "links": [ + [ + 1725, + 681, + 0, + 680, + 0, + "VIDEO" + ], + [ + 1732, + 682, + 0, + 684, + 0, + "MODEL" + ], + [ + 1733, + 682, + 2, + 684, + 1, + "VAE" + ], + [ + 1734, + 683, + 0, + 684, + 2, + "IMAGE" + ], + [ + 1735, + 684, + 0, + 686, + 0, + "POSE_KEYPOINT" + ], + [ + 1736, + 685, + 0, + 683, + 0, + "IMAGE" + ], + [ + 1737, + 679, + 0, + 685, + 0, + "VIDEO" + ], + [ + 1738, + 686, + 0, + 681, + 0, + "IMAGE" + ], + [ + 1739, + 685, + 1, + 681, + 1, + "AUDIO" + ], + [ + 1740, + 685, + 2, + 681, + 2, + "FLOAT" + ] + ], + "no_subgraphs": true, + "extra_sha256": "2fe0fdfafd58a8ef21809c72f41dbe0ca28337c4f05bdabbe1ffa49e517a338b", + "embedded_prompt_sha256": "724d6f2871eb47b3a3777bd79101062ee5b3b166ee43ce152a62da50e305be12", + "embedded_prompt_classes": [ + "CLIPTextEncode", + "CM_FloatToInt", + "CheckpointLoaderSimple", + "EmptyLTXVLatentVideo", + "FloatConstant", + "GuiderParameters", + "INTConstant", + "KSamplerSelect", + "LTXVAddGuide", + "LTXVAudioVAEDecode", + "LTXVAudioVAELoader", + "LTXVConcatAVLatent", + "LTXVConditioning", + "LTXVEmptyLatentAudio", + "LTXVGemmaCLIPModelLoader", + "LTXVScheduler", + "LTXVSeparateAVLatent", + "LTXVSequenceParallelMultiGPUPatcher", + "MultimodalGuider", + "PreviewAudio", + "RandomNoise", + "SamplerCustomAdvanced", + "VAEDecode", + "VHS_VideoCombine" + ], + "fork_declaration": "feature/av_inference@a6994ed1", + "frontend_declaration": "1.39.19", + "saved_fields": 18, + "notes": 1, + "sdpose_fields_schema_unconfirmed": 8, + "gap_scan_sha256": "0ff4c20ef3ade8cc830e13491b013534a4268b3037c4c76ce66a22527667b8c7", + "gap_scan_recheck": "Optional online check_sdpose_gap.py; offline checks stored hashes only, not entire archive rescan" +} diff --git a/docs/hel-892/sdpose-document-evidence/tested-files.json b/docs/hel-892/sdpose-document-evidence/tested-files.json new file mode 100644 index 00000000..94d4d034 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/tested-files.json @@ -0,0 +1,317 @@ +{ + "base": "729188740379e8fc2e1cad1ca9abe4fbb25e7614", + "files": [ + { + "path": "calliope-backend/src/calliope/comfyui/fixed_document.py", + "sha256": "45b54eae2840e5208697e6933331d07c232a1c0fd309df9ed57384608ad27c42" + }, + { + "path": "calliope-backend/src/calliope/comfyui/source_reviews.json", + "sha256": "99aae4b77a8393e1227f41679c3d265916db16068d1bc2a4970013e7d13a6e75" + }, + { + "path": "calliope-backend/tests/test_background_fixed_document.py", + "sha256": "3ca51da766d39ecd6767db9fe3c3ceea57a054f3087202a6c421ee4c8a82cd44" + }, + { + "path": "calliope-backend/tests/test_controlnet_fixed_document.py", + "sha256": "d8672ec57d06f8bcad027bece0c06d9af274537e83408c0d48be4f8875487d95" + }, + { + "path": "calliope-backend/tests/test_gemma_fixed_document.py", + "sha256": "de6163bddf34557ebf373fd1dc5b99a6ba67f27d19daca44efe4cdf9eec8393e" + }, + { + "path": "calliope-backend/tests/test_grid_fixed_document.py", + "sha256": "d7ad803d7a1a2f53e64b8464fa6f61af48d66df9568259c070d5e3811edc0339" + }, + { + "path": "calliope-backend/tests/test_qwen_edit_fixed_document.py", + "sha256": "3baee2ab4e5197538601c3f947fd0b53108f8f15b72c59a89be561ff21c6d697" + }, + { + "path": "calliope-backend/tests/test_sdpose_fixed_document.py", + "sha256": "9f5de880a7eab8fbdfcdddd7647b0d6ee2163eccd8a0b45fcbecc22316df0723" + }, + { + "path": "docs/hel-892/SDPose视频骨架图固定参考中文说明.md", + "sha256": "05520339f1ecced225d860e631fe53f07b78756b14ae41c0dac4f26fcf50a0aa" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-310.pyc", + "sha256": "d9fab74fa4164d0ee3797756b9b8b181d138714b79a90785e4644312c4a54625" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/__pycache__/build_definition.cpython-311.pyc", + "sha256": "08fc38a7bf3b8e7962d1c276e59800203d8e0ea35d36eb9bc0b5ce4b260667ce" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/__pycache__/rebuild.cpython-311.pyc", + "sha256": "003d73b6de46fa98eaae8083c1b5c48630ad94854c9cd9f948406b0cab2ef2fe" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/actual-sdpose_视频人物姿势骨架提取.json", + "sha256": "d1a1ae40abef173e979f4c385911c73d6ebba77f3982bec8089b9e20baa8d236" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/audit-summary.json", + "sha256": "b79c3f138241cc4c82f8530637349ec411fc8bd92de0668a07e2a88c4a2cbb7a" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/boundaries.json", + "sha256": "4f0dacaba3fb1cb43aeb5a14cf6694c7b3093a4e1f614e951dcfe788a1cdaf58" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/browser-counts.json", + "sha256": "f139497419025d2cd7a9bb1161c70844410efd8174f4bbcf12b29007bcbda574" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/browser-results.json", + "sha256": "f0f10d2bc49da0e1bc8d51c657e7001a3bb1d80e48b822a45dbbf1f43b8beb7b" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/browser.txt", + "sha256": "1eed1ab8c999e8304512874947bf331e6461831983652629829507114bc48c24" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/build.txt", + "sha256": "c00444fef525c4c1ed8a45e13530a1c95be11554e0ee19ff95f40e5dab717cee" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/build_definition.py", + "sha256": "5f9e52c2b25112c5ba1e7f0227c8d97918695b41f1ca2052683bbdb9de8c7040" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/check-exits.json", + "sha256": "5b119f5301e0688e8b365b423b6201261d49d9ef06de927250c4d10ca316cfaf" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/check_sdpose_gap.py", + "sha256": "91b3c13c8be48e782c05bfe88681cba07b8b5e5a13f8107ac608289b3e968997" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/definition-0.json", + "sha256": "11e9843b118aed1093132fbf4f2a600c02b28fbd2c1588ef51796c1e8227e145" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/fetch_sources.py", + "sha256": "5c6d1ca3ca9421f34b85a5632e74ba00b71230d7427cac56748618b36ffc4d86" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/fixed-source-index.json", + "sha256": "bd29a55b6d8f633bae5db47372d87420b7094d8c3aab50d7018c33e952d0d658" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/format.txt", + "sha256": "d41ae50829b47e318b0787bc39d2a2ea2d52b518cfc7900d2efd569e6d26ab88" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/import-protection.json", + "sha256": "e7765811ff574084478c57c072c6011f71908d082fceb0f644755bd91013541c" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/lint-development-failure.txt", + "sha256": "c9d1325c2f7d6b33e75f33ced31dea4c1a5b9822ba8a1431d9699d1bd8f6f2e3" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/lint.txt", + "sha256": "82b3e6a6c090a57601d22943bd23fca9218d1031dbe5a7b754092f9a156b4f18" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/node-check.txt", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/package-check.json", + "sha256": "38f29e69f5349c51f217d9d53a2a4402e8366fac3b8ee4462e3eb2b75b666f60" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/pins.json", + "sha256": "d20fd17267832d929374ffb0eb3d9845e91b96d8916c97c00263d7cf1e4c4408" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/rebuild.py", + "sha256": "c2ee396f52874d0917b40af5a770c29c07f528a6f8352414285debbea3d64261" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/recompute.py", + "sha256": "766913b0a6e6771322eeececde4b43fd1ffe9234c5d22451a0e7345481e935e2" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/recompute.txt", + "sha256": "dc1d32dee1b68ddd27108496a93e8bd59bd1e3b6fe323b1092b3f25f969d04ad" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/render_report.py", + "sha256": "5414ce78f5107501a3ce5f31f65a0f6833d048adeae25b53a33cb4b8132cbc37" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/repeat.py", + "sha256": "0208be10735a21904a7238d473527efa600c7d8fa7949adb002bb7f83deb15b0" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/repeatability.json", + "sha256": "c6121ca431a1feed39e623ac5ee59989624cc684a4f8d865d5f7c95ae6d53658" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/repeatability.txt", + "sha256": "a6200f95843551248244d0d90380858ad1fcffb8703cd2ecb607f02370f5f8d5" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/review-delta.json", + "sha256": "f538e36f8089699aa829e2b9876e0a865282c5a7bb27f5332ebf060b3656db7c" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.json", + "sha256": "0ff4c20ef3ade8cc830e13491b013534a4268b3037c4c76ce66a22527667b8c7" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/sdpose-gap-scan.txt", + "sha256": "f90ea3e6a607f6da702333d3b9f3aa9257e9f616f4a70481c99b25d423e77337" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/source-check.json", + "sha256": "6119daf0edfe44c9a183b396ae4ff898dd8423527dcc477971ee1a15916317ba" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/source-graph.json", + "sha256": "b1be4622bfdadbbe4bd7f4ce5061417e92ffec8749a66dd4fff24ea8667859a2" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/tests-added-development-failure.txt", + "sha256": "796ec5481e179c93abee0077faf0bcf6644c2b22e9a967a9a8599b2c659209a1" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/tests-new-development-failure.txt", + "sha256": "1721b5fd83ce6f0b11d559cc7dfa063d69fad3a6c9131f115bbbc6cc87a4a0d9" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/tests-new.txt", + "sha256": "6b43c0f86a42418044cdbe6e65db827a08eb86ee3f59952190f29cb4621d628c" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/tests.txt", + "sha256": "696e9405fd6777922adbe3baa1d4e41c6f37fbd75fabc67059da89475975e422" + }, + { + "path": "docs/hel-892/sdpose-document-evidence/validation-commands.txt", + "sha256": "c7404acf7a5e01e5835091e91ca1a862c2677ebfb35fb1dd7430cc9c8ea13570" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150-commit.json", + "sha256": "e2ba46fdda05c083b72f05a40d4f62d034cc772a0579e3f03a74152988244d3a" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150-tag.json", + "sha256": "f3c7ba4af6144b4be77d359a64191999032e106b58800208683051f1e703f59d" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150__comfy__utils.py", + "sha256": "feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150__comfy_api__latest___io.py", + "sha256": "babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150__comfy_extras__nodes_post_processing.py", + "sha256": "220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4" + }, + { + "path": "docs/hel-892/sdpose-reference/core0150__nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151-commit.json", + "sha256": "df64c3da930aebd32514b259f7b610bdd5a0cde3ebec46e2481e4e27d5f0ce4b" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151-tag.json", + "sha256": "9a8b752179bf5aac26a5f9c79e9cfc190042019390009c5761e8c9d1b13e282c" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input__video_types.py", + "sha256": "6a4cdb3085ed8a4289e63168536e9a530c95aad94c7e2de1eddf8738af11f5a7" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py", + "sha256": "df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util____init__.py", + "sha256": "a00432018a3aa989a98d94470c657bfef2a89031fe1e844c19a616636291ba0a" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util__video_types.py", + "sha256": "b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__comfy_extras__nodes_video.py", + "sha256": "1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575" + }, + { + "path": "docs/hel-892/sdpose-reference/core0151__folder_paths.py", + "sha256": "da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend-commit.json", + "sha256": "ed59717c9b6ea008d633fad905ecb4e01d02b34094b2d4c781b930b2bd5837db" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend-tag.json", + "sha256": "dbdd4d0ae2a418a58198a20be9606992af165501135c34b2c459b11fdb8641a1" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts", + "sha256": "f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__extensions__core__noteNode.ts", + "sha256": "1014f719e3d67d9c5183a5e8631d4c2d6581dfe67083f32eb23774ec3074bef2" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__widgets__BaseWidget.ts", + "sha256": "0835d3d10d5bc8fcdd86bb1a35e4cf53a82681d6087f9da2a900882bf0ddac3f" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts", + "sha256": "77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d" + }, + { + "path": "docs/hel-892/sdpose-reference/frontend__src__utils__executionUtil.ts", + "sha256": "b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6" + }, + { + "path": "docs/hel-892/sdpose-reference/identity.json", + "sha256": "fd3b2ed9686dd1888bef70c87c5ab914c86c7068d8a8ef4a008c30987b82f3cf" + }, + { + "path": "docs/hel-892/sdpose-reference/sources.json", + "sha256": "2ee26844b472dcc0d1c3bff8d6874effd6e12e38d518b5baa864f7c90b196b7c" + }, + { + "path": "e2e/run-sdpose-document.py", + "sha256": "eb506d53d4a0899cea8b117b3c965d23f833ed9925e2e7706cb2cc198b2a17d5" + }, + { + "path": "e2e/sdpose-document.mjs", + "sha256": "904af01b4ef1a2fe09c1a3a1232b2bbe97e2ad76304401142751f99960c1669f" + } + ] +} diff --git a/docs/hel-892/sdpose-document-evidence/tests-added-development-failure.txt b/docs/hel-892/sdpose-document-evidence/tests-added-development-failure.txt new file mode 100644 index 00000000..f8d01681 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/tests-added-development-failure.txt @@ -0,0 +1,78 @@ +........................................................................ [ 2%] +........................................................................ [ 5%] +...............................................F........................ [ 8%] +........................................................................ [ 11%] +........................................................................ [ 14%] +........................................................................ [ 17%] +........................................................................ [ 20%] +........................................................................ [ 23%] +........................................................................ [ 26%] +........................................................................ [ 29%] +........................................................................ [ 32%] +........................................................................ [ 35%] +........................................................................ [ 38%] +........................................................................ [ 41%] +........................................................................ [ 44%] +........................................................................ [ 47%] +........................................................................ [ 50%] +........................................................................ [ 53%] +........................................................................ [ 56%] +........................................................................ [ 59%] +........................................................................ [ 62%] +........................................................................ [ 65%] +........................................................................ [ 68%] +........................................................................ [ 71%] +........................................................................ [ 73%] +........................................................................ [ 76%] +........................................................................ [ 79%] +........................................................................ [ 82%] +........................................................................ [ 85%] +........................................................................ [ 88%] +........................................................................ [ 91%] +........................................................................ [ 94%] +........................................................................ [ 97%] +......................................................... [100%] +=================================== FAILURES =================================== +________________ test_missing_packages_give_chinese_build_hint _________________ + +tmp_path = PosixPath('/tmp/multica-task-3507053905/pytest-of-xiaomo/pytest-1/test_missing_packages_give_chi0') + + def test_missing_packages_give_chinese_build_hint(tmp_path): + import runpy + +> namespace = runpy.run_path(str(OUT / "recompute.py")) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +calliope-backend/tests/test_sdpose_fixed_document.py:251: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +:291: in run_path + ??? +:98: in _run_module_code + ??? +:88: in _run_code + ??? +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + + """Actual 7291887 database upgrade, one-row protection/rollback, frozen boundaries and packages.""" + + from __future__ import annotations + + import hashlib + import io + import json + import os + import sqlite3 + import subprocess + import sys + import tarfile + import tempfile + import zipfile + from pathlib import Path + +> from build_definition import OUT, PATHS, REPO, canonical +E ModuleNotFoundError: No module named 'build_definition' + +docs/hel-892/sdpose-document-evidence/recompute.py:17: ModuleNotFoundError +=========================== short test summary info ============================ +FAILED calliope-backend/tests/test_sdpose_fixed_document.py::test_missing_packages_give_chinese_build_hint +1 failed, 2432 passed, 1 warning in 15.62s diff --git a/docs/hel-892/sdpose-document-evidence/tests-new-development-failure.txt b/docs/hel-892/sdpose-document-evidence/tests-new-development-failure.txt new file mode 100644 index 00000000..4496035e --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/tests-new-development-failure.txt @@ -0,0 +1,72 @@ +........................................................................ [ 37%] +........................................................................ [ 75%] +...........................................F.. [100%] +=================================== FAILURES =================================== +_________ test_exact_topology_nulls_conditions_and_reference_identity __________ + + def test_exact_topology_nulls_conditions_and_reference_identity(): + assert BLOCK["source_sha256"] == hashlib.sha256(RAW).hexdigest() + assert BLOCK["canonical_sha256"] == hashlib.sha256(canonical(SOURCE)).hexdigest() + assert len(SOURCE["nodes"]) == 9 and len(SOURCE["links"]) == 10 + assert [e[0] for e in SOURCE["links"]] == [ + 1725, + 1732, + 1733, + 1734, + 1735, + 1736, + 1737, + 1738, + 1739, + 1740, + ] + assert SOURCE["links"][-2:] == [ + [1739, 685, 1, 681, 1, "AUDIO"], + [1740, 685, 2, 681, 2, "FLOAT"], + ] + assert all(n["mode"] == 0 for n in SOURCE["nodes"]) + assert len(BLOCK["fields"]) == 18 and len(BLOCK["comments"]) == 1 + assert sum(f["role"] == "source_named_unconfirmed" for f in BLOCK["fields"]) == 8 + assert sum(f["role"] == "linked_saved" for f in BLOCK["fields"]) == 1 + for n in BLOCK["comments"]: + assert pointer(SOURCE, n["pointer"]) == n["text"] + assert "widgets_values" not in SOURCE["nodes"][2] + assert SOURCE["nodes"][2].get("widgets_values") is None + assert BLOCK["zero_saved_nodes"][0]["node_id"] == "685" + fields = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]} + assert fields["681", "fps"]["value"] == 30 and fields["681", "fps"]["json_type"] == "int" + assert fields["683", "resize_type.longer_size"]["value"] == 1024 + assert [f["value"] for f in BLOCK["fields"] if f["node_id"] == "686"] == [ + True, + True, + True, + True, + 4, + 2, + 0.5, + ] + assert {e["commit"] for e in BLOCK["sources"]} == { + "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + } +> assert all( + t in "".join(BLOCK["flow"]) + for t in [ + "外线覆盖", + "未知", + "不同流程缓存", + "未找到", + "UE7.7.1", + "没有widgets_values键", + "bboxes", + "不产prompt", + ] + ) +E assert False +E + where False = all(. at 0x7f73e3c8ff10>) + +calliope-backend/tests/test_sdpose_fixed_document.py:218: AssertionError +=========================== short test summary info ============================ +FAILED calliope-backend/tests/test_sdpose_fixed_document.py::test_exact_topology_nulls_conditions_and_reference_identity +1 failed, 189 passed, 1 warning in 0.39s diff --git a/docs/hel-892/sdpose-document-evidence/tests-new.txt b/docs/hel-892/sdpose-document-evidence/tests-new.txt new file mode 100644 index 00000000..b0def255 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/tests-new.txt @@ -0,0 +1,4 @@ +........................................................................ [ 37%] +........................................................................ [ 75%] +................................................ [100%] +192 passed, 1 warning in 0.39s diff --git a/docs/hel-892/sdpose-document-evidence/tests.txt b/docs/hel-892/sdpose-document-evidence/tests.txt new file mode 100644 index 00000000..43b0f260 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/tests.txt @@ -0,0 +1,35 @@ +........................................................................ [ 2%] +........................................................................ [ 5%] +........................................................................ [ 8%] +........................................................................ [ 11%] +........................................................................ [ 14%] +........................................................................ [ 17%] +........................................................................ [ 20%] +........................................................................ [ 23%] +........................................................................ [ 26%] +........................................................................ [ 29%] +........................................................................ [ 32%] +........................................................................ [ 35%] +........................................................................ [ 38%] +........................................................................ [ 41%] +........................................................................ [ 44%] +........................................................................ [ 47%] +........................................................................ [ 50%] +........................................................................ [ 53%] +........................................................................ [ 56%] +........................................................................ [ 59%] +........................................................................ [ 62%] +........................................................................ [ 65%] +........................................................................ [ 68%] +........................................................................ [ 71%] +........................................................................ [ 73%] +........................................................................ [ 76%] +........................................................................ [ 79%] +........................................................................ [ 82%] +........................................................................ [ 85%] +........................................................................ [ 88%] +........................................................................ [ 91%] +........................................................................ [ 94%] +........................................................................ [ 97%] +......................................................... [100%] +2433 passed, 1 warning in 15.36s diff --git a/docs/hel-892/sdpose-document-evidence/validation-commands.txt b/docs/hel-892/sdpose-document-evidence/validation-commands.txt new file mode 100644 index 00000000..8b302f92 --- /dev/null +++ b/docs/hel-892/sdpose-document-evidence/validation-commands.txt @@ -0,0 +1,21 @@ +# 仓库根,Python3.11/锁定既有依赖,无新依赖 +uv sync --project calliope-backend --frozen --extra dev --python 3.11 --offline +npm ci --prefix calliope-web --ignore-scripts --offline +python3 docs/hel-892/sdpose-document-evidence/rebuild.py +uv run --project calliope-backend --offline ruff check --config calliope-backend/pyproject.toml docs/hel-892/sdpose-document-evidence/build_definition.py docs/hel-892/sdpose-document-evidence/check_sdpose_gap.py docs/hel-892/sdpose-document-evidence/fetch_sources.py docs/hel-892/sdpose-document-evidence/rebuild.py docs/hel-892/sdpose-document-evidence/recompute.py docs/hel-892/sdpose-document-evidence/render_report.py docs/hel-892/sdpose-document-evidence/repeat.py calliope-backend/src/calliope/comfyui/fixed_document.py calliope-backend/tests/test_sdpose_fixed_document.py calliope-backend/tests/test_gemma_fixed_document.py calliope-backend/tests/test_grid_fixed_document.py calliope-backend/tests/test_background_fixed_document.py calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py e2e/run-sdpose-document.py +uv run --project calliope-backend --offline ruff format --config calliope-backend/pyproject.toml --check docs/hel-892/sdpose-document-evidence/build_definition.py docs/hel-892/sdpose-document-evidence/check_sdpose_gap.py docs/hel-892/sdpose-document-evidence/fetch_sources.py docs/hel-892/sdpose-document-evidence/rebuild.py docs/hel-892/sdpose-document-evidence/recompute.py docs/hel-892/sdpose-document-evidence/render_report.py docs/hel-892/sdpose-document-evidence/repeat.py calliope-backend/src/calliope/comfyui/fixed_document.py calliope-backend/tests/test_sdpose_fixed_document.py calliope-backend/tests/test_gemma_fixed_document.py calliope-backend/tests/test_grid_fixed_document.py calliope-backend/tests/test_background_fixed_document.py calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py e2e/run-sdpose-document.py +node --check e2e/sdpose-document.mjs +uv run --project calliope-backend --offline pytest calliope-backend/tests/test_sdpose_fixed_document.py -q --disable-warnings +uv run --project calliope-backend --offline python docs/hel-892/sdpose-document-evidence/recompute.py +uv build --project calliope-backend --offline +uv run --project calliope-backend --offline python docs/hel-892/sdpose-document-evidence/repeat.py +python3 docs/hel-892/sdpose-document-evidence/render_report.py +# 全量受影响套件见tests.txt,未跑全后台或冻结转换组,不把旧证据混入本批。 +# 本地双屏浏览入口e2e/run-sdpose-document.py;系统浏览器及Playwright可由环境变量指定。 +# 可选官方文本缺口再核check_sdpose_gap.py(只读官方固定commit,不访问目标机),离线复算只核保存索引/原件哈希。 + +# 受影响后台总套件(不与新专项重复相加) +uv run --project calliope-backend --offline pytest calliope-backend/tests/test_sdpose_fixed_document.py calliope-backend/tests/test_gemma_fixed_document.py calliope-backend/tests/test_grid_fixed_document.py calliope-backend/tests/test_background_fixed_document.py calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_qwen_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py calliope-backend/tests/test_asr_fixed_document.py calliope-backend/tests/test_media_fixed_document.py calliope-backend/tests/test_audio_fixed_document.py calliope-backend/tests/test_fixed_document.py calliope-backend/tests/test_workflow_library.py calliope-backend/tests/test_supplied_companions.py calliope-backend/tests/test_delivery_scope.py calliope-backend/tests/test_case04_saved_reference.py -q --disable-warnings +node --check e2e/sdpose-document.mjs +# 本次浏览的实际命令(浏览器和模块安装属于运行环境既有工具) +LD_LIBRARY_PATH=/home/xiaomo/chromium-libs/root/usr/lib/x86_64-linux-gnu:/home/xiaomo/browserlibs/root/usr/lib/x86_64-linux-gnu PLAYWRIGHT_MODULE=/home/xiaomo/.npm-global/lib/node_modules/playwright/index.mjs BROWSER_EXECUTABLE=/home/xiaomo/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome uv run --project calliope-backend --offline python e2e/run-sdpose-document.py diff --git a/docs/hel-892/sdpose-reference/core0150-commit.json b/docs/hel-892/sdpose-reference/core0150-commit.json new file mode 100644 index 00000000..b7d9a2a6 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150-commit.json @@ -0,0 +1 @@ +{"sha":"b874bd2b8c324d58cfc37bff0754dd16815a8f3c","node_id":"C_kwDOIygeJtoAKGI4NzRiZDJiOGMzMjRkNThjZmMzN2JmZjA3NTRkZDE2ODE1YThmM2M","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/b874bd2b8c324d58cfc37bff0754dd16815a8f3c","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/b874bd2b8c324d58cfc37bff0754dd16815a8f3c","author":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-02-24T17:37:16Z"},"committer":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-02-24T17:42:15Z"},"tree":{"sha":"7b8179ffb38c06974fcd9f5c127b3e943893c6f5","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/trees/7b8179ffb38c06974fcd9f5c127b3e943893c6f5"},"message":"ComfyUI v0.15.0","parents":[{"sha":"0aa02453bbe7d2fac332e829ade1f13a1cf53820","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/0aa02453bbe7d2fac332e829ade1f13a1cf53820","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/0aa02453bbe7d2fac332e829ade1f13a1cf53820"}],"verification":{"verified":false,"reason":"unsigned","signature":null,"payload":null,"verified_at":null}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/core0150-tag.json b/docs/hel-892/sdpose-reference/core0150-tag.json new file mode 100644 index 00000000..7365b2fd --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150-tag.json @@ -0,0 +1 @@ +{"ref":"refs/tags/v0.15.0","node_id":"REF_kwDOIygeJrFyZWZzL3RhZ3MvdjAuMTUuMA","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/refs/tags/v0.15.0","object":{"sha":"b874bd2b8c324d58cfc37bff0754dd16815a8f3c","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/b874bd2b8c324d58cfc37bff0754dd16815a8f3c"}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/core0150__LICENSE b/docs/hel-892/sdpose-reference/core0150__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/sdpose-reference/core0150__comfy__utils.py b/docs/hel-892/sdpose-reference/core0150__comfy__utils.py new file mode 100644 index 00000000..5fe66ecd --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150__comfy__utils.py @@ -0,0 +1,1428 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + + +import torch +import math +import struct +import comfy.memory_management +import safetensors.torch +import numpy as np +from PIL import Image +import logging +import itertools +from torch.nn.functional import interpolate +from tqdm.auto import trange +from einops import rearrange +from comfy.cli_args import args, enables_dynamic_vram +import json +import time +import mmap +import warnings + +MMAP_TORCH_FILES = args.mmap_torch_files +DISABLE_MMAP = args.disable_mmap + + +if True: # ckpt/pt file whitelist for safe loading of old sd files + class ModelCheckpoint: + pass + ModelCheckpoint.__module__ = "pytorch_lightning.callbacks.model_checkpoint" + + def scalar(*args, **kwargs): + return None + scalar.__module__ = "numpy.core.multiarray" + + from numpy import dtype + from numpy.dtypes import Float64DType + + def encode(*args, **kwargs): # no longer necessary on newer torch + return None + encode.__module__ = "_codecs" + + torch.serialization.add_safe_globals([ModelCheckpoint, scalar, dtype, Float64DType, encode]) + logging.info("Checkpoint files will always be loaded safely.") + + +# Current as of safetensors 0.7.0 +_TYPES = { + "F64": torch.float64, + "F32": torch.float32, + "F16": torch.float16, + "BF16": torch.bfloat16, + "I64": torch.int64, + "I32": torch.int32, + "I16": torch.int16, + "I8": torch.int8, + "U8": torch.uint8, + "BOOL": torch.bool, + "F8_E4M3": torch.float8_e4m3fn, + "F8_E5M2": torch.float8_e5m2, + "C64": torch.complex64, + + "U64": torch.uint64, + "U32": torch.uint32, + "U16": torch.uint16, +} + +def load_safetensors(ckpt): + f = open(ckpt, "rb") + mapping = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) + mv = memoryview(mapping) + + header_size = struct.unpack(" 0: + message = e.args[0] + if "HeaderTooLarge" in message: + raise ValueError("{}\n\nFile path: {}\n\nThe safetensors file is corrupt or invalid. Make sure this is actually a safetensors file and not a ckpt or pt or other filetype.".format(message, ckpt)) + if "MetadataIncompleteBuffer" in message: + raise ValueError("{}\n\nFile path: {}\n\nThe safetensors file is corrupt/incomplete. Check the file size and make sure you have copied/downloaded it correctly.".format(message, ckpt)) + raise e + else: + torch_args = {} + if MMAP_TORCH_FILES: + torch_args["mmap"] = True + + pl_sd = torch.load(ckpt, map_location=device, weights_only=True, **torch_args) + + if "state_dict" in pl_sd: + sd = pl_sd["state_dict"] + else: + if len(pl_sd) == 1: + key = list(pl_sd.keys())[0] + sd = pl_sd[key] + if not isinstance(sd, dict): + sd = pl_sd + else: + sd = pl_sd + return (sd, metadata) if return_metadata else sd + +def save_torch_file(sd, ckpt, metadata=None): + if metadata is not None: + safetensors.torch.save_file(sd, ckpt, metadata=metadata) + else: + safetensors.torch.save_file(sd, ckpt) + +def calculate_parameters(sd, prefix=""): + params = 0 + for k in sd.keys(): + if k.startswith(prefix): + w = sd[k] + params += w.nelement() + return params + +def weight_dtype(sd, prefix=""): + dtypes = {} + for k in sd.keys(): + if k.startswith(prefix): + w = sd[k] + dtypes[w.dtype] = dtypes.get(w.dtype, 0) + w.numel() + + if len(dtypes) == 0: + return None + + return max(dtypes, key=dtypes.get) + +def state_dict_key_replace(state_dict, keys_to_replace): + for x in keys_to_replace: + if x in state_dict: + state_dict[keys_to_replace[x]] = state_dict.pop(x) + return state_dict + +def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False): + if filter_keys: + out = {} + else: + out = state_dict + for rp in replace_prefix: + replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp):])), filter(lambda a: a.startswith(rp), state_dict.keys()))) + for x in replace: + w = state_dict.pop(x[0]) + out[x[1]] = w + return out + + +def transformers_convert(sd, prefix_from, prefix_to, number): + keys_to_replace = { + "{}positional_embedding": "{}embeddings.position_embedding.weight", + "{}token_embedding.weight": "{}embeddings.token_embedding.weight", + "{}ln_final.weight": "{}final_layer_norm.weight", + "{}ln_final.bias": "{}final_layer_norm.bias", + } + + for k in keys_to_replace: + x = k.format(prefix_from) + if x in sd: + sd[keys_to_replace[k].format(prefix_to)] = sd.pop(x) + + resblock_to_replace = { + "ln_1": "layer_norm1", + "ln_2": "layer_norm2", + "mlp.c_fc": "mlp.fc1", + "mlp.c_proj": "mlp.fc2", + "attn.out_proj": "self_attn.out_proj", + } + + for resblock in range(number): + for x in resblock_to_replace: + for y in ["weight", "bias"]: + k = "{}transformer.resblocks.{}.{}.{}".format(prefix_from, resblock, x, y) + k_to = "{}encoder.layers.{}.{}.{}".format(prefix_to, resblock, resblock_to_replace[x], y) + if k in sd: + sd[k_to] = sd.pop(k) + + for y in ["weight", "bias"]: + k_from = "{}transformer.resblocks.{}.attn.in_proj_{}".format(prefix_from, resblock, y) + if k_from in sd: + weights = sd.pop(k_from) + shape_from = weights.shape[0] // 3 + for x in range(3): + p = ["self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj"] + k_to = "{}encoder.layers.{}.{}.{}".format(prefix_to, resblock, p[x], y) + sd[k_to] = weights[shape_from*x:shape_from*(x + 1)] + + return sd + +def clip_text_transformers_convert(sd, prefix_from, prefix_to): + sd = transformers_convert(sd, prefix_from, "{}text_model.".format(prefix_to), 32) + + tp = "{}text_projection.weight".format(prefix_from) + if tp in sd: + sd["{}text_projection.weight".format(prefix_to)] = sd.pop(tp) + + tp = "{}text_projection".format(prefix_from) + if tp in sd: + sd["{}text_projection.weight".format(prefix_to)] = sd.pop(tp).transpose(0, 1).contiguous() + return sd + + +UNET_MAP_ATTENTIONS = { + "proj_in.weight", + "proj_in.bias", + "proj_out.weight", + "proj_out.bias", + "norm.weight", + "norm.bias", +} + +TRANSFORMER_BLOCKS = { + "norm1.weight", + "norm1.bias", + "norm2.weight", + "norm2.bias", + "norm3.weight", + "norm3.bias", + "attn1.to_q.weight", + "attn1.to_k.weight", + "attn1.to_v.weight", + "attn1.to_out.0.weight", + "attn1.to_out.0.bias", + "attn2.to_q.weight", + "attn2.to_k.weight", + "attn2.to_v.weight", + "attn2.to_out.0.weight", + "attn2.to_out.0.bias", + "ff.net.0.proj.weight", + "ff.net.0.proj.bias", + "ff.net.2.weight", + "ff.net.2.bias", +} + +UNET_MAP_RESNET = { + "in_layers.2.weight": "conv1.weight", + "in_layers.2.bias": "conv1.bias", + "emb_layers.1.weight": "time_emb_proj.weight", + "emb_layers.1.bias": "time_emb_proj.bias", + "out_layers.3.weight": "conv2.weight", + "out_layers.3.bias": "conv2.bias", + "skip_connection.weight": "conv_shortcut.weight", + "skip_connection.bias": "conv_shortcut.bias", + "in_layers.0.weight": "norm1.weight", + "in_layers.0.bias": "norm1.bias", + "out_layers.0.weight": "norm2.weight", + "out_layers.0.bias": "norm2.bias", +} + +UNET_MAP_BASIC = { + ("label_emb.0.0.weight", "class_embedding.linear_1.weight"), + ("label_emb.0.0.bias", "class_embedding.linear_1.bias"), + ("label_emb.0.2.weight", "class_embedding.linear_2.weight"), + ("label_emb.0.2.bias", "class_embedding.linear_2.bias"), + ("label_emb.0.0.weight", "add_embedding.linear_1.weight"), + ("label_emb.0.0.bias", "add_embedding.linear_1.bias"), + ("label_emb.0.2.weight", "add_embedding.linear_2.weight"), + ("label_emb.0.2.bias", "add_embedding.linear_2.bias"), + ("input_blocks.0.0.weight", "conv_in.weight"), + ("input_blocks.0.0.bias", "conv_in.bias"), + ("out.0.weight", "conv_norm_out.weight"), + ("out.0.bias", "conv_norm_out.bias"), + ("out.2.weight", "conv_out.weight"), + ("out.2.bias", "conv_out.bias"), + ("time_embed.0.weight", "time_embedding.linear_1.weight"), + ("time_embed.0.bias", "time_embedding.linear_1.bias"), + ("time_embed.2.weight", "time_embedding.linear_2.weight"), + ("time_embed.2.bias", "time_embedding.linear_2.bias") +} + +def unet_to_diffusers(unet_config): + if "num_res_blocks" not in unet_config: + return {} + num_res_blocks = unet_config["num_res_blocks"] + channel_mult = unet_config["channel_mult"] + transformer_depth = unet_config["transformer_depth"][:] + transformer_depth_output = unet_config["transformer_depth_output"][:] + num_blocks = len(channel_mult) + + transformers_mid = unet_config.get("transformer_depth_middle", None) + + diffusers_unet_map = {} + for x in range(num_blocks): + n = 1 + (num_res_blocks[x] + 1) * x + for i in range(num_res_blocks[x]): + for b in UNET_MAP_RESNET: + diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b) + num_transformers = transformer_depth.pop(0) + if num_transformers > 0: + for b in UNET_MAP_ATTENTIONS: + diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b) + for t in range(num_transformers): + for b in TRANSFORMER_BLOCKS: + diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b) + n += 1 + for k in ["weight", "bias"]: + diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k) + + i = 0 + for b in UNET_MAP_ATTENTIONS: + diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b) + for t in range(transformers_mid): + for b in TRANSFORMER_BLOCKS: + diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b) + + for i, n in enumerate([0, 2]): + for b in UNET_MAP_RESNET: + diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b) + + num_res_blocks = list(reversed(num_res_blocks)) + for x in range(num_blocks): + n = (num_res_blocks[x] + 1) * x + l = num_res_blocks[x] + 1 + for i in range(l): + c = 0 + for b in UNET_MAP_RESNET: + diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b) + c += 1 + num_transformers = transformer_depth_output.pop() + if num_transformers > 0: + c += 1 + for b in UNET_MAP_ATTENTIONS: + diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b) + for t in range(num_transformers): + for b in TRANSFORMER_BLOCKS: + diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b) + if i == l - 1: + for k in ["weight", "bias"]: + diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k) + n += 1 + + for k in UNET_MAP_BASIC: + diffusers_unet_map[k[1]] = k[0] + + return diffusers_unet_map + +def swap_scale_shift(weight): + shift, scale = weight.chunk(2, dim=0) + new_weight = torch.cat([scale, shift], dim=0) + return new_weight + +MMDIT_MAP_BASIC = { + ("context_embedder.bias", "context_embedder.bias"), + ("context_embedder.weight", "context_embedder.weight"), + ("t_embedder.mlp.0.bias", "time_text_embed.timestep_embedder.linear_1.bias"), + ("t_embedder.mlp.0.weight", "time_text_embed.timestep_embedder.linear_1.weight"), + ("t_embedder.mlp.2.bias", "time_text_embed.timestep_embedder.linear_2.bias"), + ("t_embedder.mlp.2.weight", "time_text_embed.timestep_embedder.linear_2.weight"), + ("x_embedder.proj.bias", "pos_embed.proj.bias"), + ("x_embedder.proj.weight", "pos_embed.proj.weight"), + ("y_embedder.mlp.0.bias", "time_text_embed.text_embedder.linear_1.bias"), + ("y_embedder.mlp.0.weight", "time_text_embed.text_embedder.linear_1.weight"), + ("y_embedder.mlp.2.bias", "time_text_embed.text_embedder.linear_2.bias"), + ("y_embedder.mlp.2.weight", "time_text_embed.text_embedder.linear_2.weight"), + ("pos_embed", "pos_embed.pos_embed"), + ("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift), + ("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift), + ("final_layer.linear.bias", "proj_out.bias"), + ("final_layer.linear.weight", "proj_out.weight"), +} + +MMDIT_MAP_BLOCK = { + ("context_block.adaLN_modulation.1.bias", "norm1_context.linear.bias"), + ("context_block.adaLN_modulation.1.weight", "norm1_context.linear.weight"), + ("context_block.attn.proj.bias", "attn.to_add_out.bias"), + ("context_block.attn.proj.weight", "attn.to_add_out.weight"), + ("context_block.mlp.fc1.bias", "ff_context.net.0.proj.bias"), + ("context_block.mlp.fc1.weight", "ff_context.net.0.proj.weight"), + ("context_block.mlp.fc2.bias", "ff_context.net.2.bias"), + ("context_block.mlp.fc2.weight", "ff_context.net.2.weight"), + ("context_block.attn.ln_q.weight", "attn.norm_added_q.weight"), + ("context_block.attn.ln_k.weight", "attn.norm_added_k.weight"), + ("x_block.adaLN_modulation.1.bias", "norm1.linear.bias"), + ("x_block.adaLN_modulation.1.weight", "norm1.linear.weight"), + ("x_block.attn.proj.bias", "attn.to_out.0.bias"), + ("x_block.attn.proj.weight", "attn.to_out.0.weight"), + ("x_block.attn.ln_q.weight", "attn.norm_q.weight"), + ("x_block.attn.ln_k.weight", "attn.norm_k.weight"), + ("x_block.attn2.proj.bias", "attn2.to_out.0.bias"), + ("x_block.attn2.proj.weight", "attn2.to_out.0.weight"), + ("x_block.attn2.ln_q.weight", "attn2.norm_q.weight"), + ("x_block.attn2.ln_k.weight", "attn2.norm_k.weight"), + ("x_block.mlp.fc1.bias", "ff.net.0.proj.bias"), + ("x_block.mlp.fc1.weight", "ff.net.0.proj.weight"), + ("x_block.mlp.fc2.bias", "ff.net.2.bias"), + ("x_block.mlp.fc2.weight", "ff.net.2.weight"), +} + +def mmdit_to_diffusers(mmdit_config, output_prefix=""): + key_map = {} + + depth = mmdit_config.get("depth", 0) + num_blocks = mmdit_config.get("num_blocks", depth) + for i in range(num_blocks): + block_from = "transformer_blocks.{}".format(i) + block_to = "{}joint_blocks.{}".format(output_prefix, i) + + offset = depth * 64 + + for end in ("weight", "bias"): + k = "{}.attn.".format(block_from) + qkv = "{}.x_block.attn.qkv.{}".format(block_to, end) + key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, offset)) + key_map["{}to_k.{}".format(k, end)] = (qkv, (0, offset, offset)) + key_map["{}to_v.{}".format(k, end)] = (qkv, (0, offset * 2, offset)) + + qkv = "{}.context_block.attn.qkv.{}".format(block_to, end) + key_map["{}add_q_proj.{}".format(k, end)] = (qkv, (0, 0, offset)) + key_map["{}add_k_proj.{}".format(k, end)] = (qkv, (0, offset, offset)) + key_map["{}add_v_proj.{}".format(k, end)] = (qkv, (0, offset * 2, offset)) + + k = "{}.attn2.".format(block_from) + qkv = "{}.x_block.attn2.qkv.{}".format(block_to, end) + key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, offset)) + key_map["{}to_k.{}".format(k, end)] = (qkv, (0, offset, offset)) + key_map["{}to_v.{}".format(k, end)] = (qkv, (0, offset * 2, offset)) + + for k in MMDIT_MAP_BLOCK: + key_map["{}.{}".format(block_from, k[1])] = "{}.{}".format(block_to, k[0]) + + map_basic = MMDIT_MAP_BASIC.copy() + map_basic.add(("joint_blocks.{}.context_block.adaLN_modulation.1.bias".format(depth - 1), "transformer_blocks.{}.norm1_context.linear.bias".format(depth - 1), swap_scale_shift)) + map_basic.add(("joint_blocks.{}.context_block.adaLN_modulation.1.weight".format(depth - 1), "transformer_blocks.{}.norm1_context.linear.weight".format(depth - 1), swap_scale_shift)) + + for k in map_basic: + if len(k) > 2: + key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2]) + else: + key_map[k[1]] = "{}{}".format(output_prefix, k[0]) + + return key_map + +PIXART_MAP_BASIC = { + ("csize_embedder.mlp.0.weight", "adaln_single.emb.resolution_embedder.linear_1.weight"), + ("csize_embedder.mlp.0.bias", "adaln_single.emb.resolution_embedder.linear_1.bias"), + ("csize_embedder.mlp.2.weight", "adaln_single.emb.resolution_embedder.linear_2.weight"), + ("csize_embedder.mlp.2.bias", "adaln_single.emb.resolution_embedder.linear_2.bias"), + ("ar_embedder.mlp.0.weight", "adaln_single.emb.aspect_ratio_embedder.linear_1.weight"), + ("ar_embedder.mlp.0.bias", "adaln_single.emb.aspect_ratio_embedder.linear_1.bias"), + ("ar_embedder.mlp.2.weight", "adaln_single.emb.aspect_ratio_embedder.linear_2.weight"), + ("ar_embedder.mlp.2.bias", "adaln_single.emb.aspect_ratio_embedder.linear_2.bias"), + ("x_embedder.proj.weight", "pos_embed.proj.weight"), + ("x_embedder.proj.bias", "pos_embed.proj.bias"), + ("y_embedder.y_embedding", "caption_projection.y_embedding"), + ("y_embedder.y_proj.fc1.weight", "caption_projection.linear_1.weight"), + ("y_embedder.y_proj.fc1.bias", "caption_projection.linear_1.bias"), + ("y_embedder.y_proj.fc2.weight", "caption_projection.linear_2.weight"), + ("y_embedder.y_proj.fc2.bias", "caption_projection.linear_2.bias"), + ("t_embedder.mlp.0.weight", "adaln_single.emb.timestep_embedder.linear_1.weight"), + ("t_embedder.mlp.0.bias", "adaln_single.emb.timestep_embedder.linear_1.bias"), + ("t_embedder.mlp.2.weight", "adaln_single.emb.timestep_embedder.linear_2.weight"), + ("t_embedder.mlp.2.bias", "adaln_single.emb.timestep_embedder.linear_2.bias"), + ("t_block.1.weight", "adaln_single.linear.weight"), + ("t_block.1.bias", "adaln_single.linear.bias"), + ("final_layer.linear.weight", "proj_out.weight"), + ("final_layer.linear.bias", "proj_out.bias"), + ("final_layer.scale_shift_table", "scale_shift_table"), +} + +PIXART_MAP_BLOCK = { + ("scale_shift_table", "scale_shift_table"), + ("attn.proj.weight", "attn1.to_out.0.weight"), + ("attn.proj.bias", "attn1.to_out.0.bias"), + ("mlp.fc1.weight", "ff.net.0.proj.weight"), + ("mlp.fc1.bias", "ff.net.0.proj.bias"), + ("mlp.fc2.weight", "ff.net.2.weight"), + ("mlp.fc2.bias", "ff.net.2.bias"), + ("cross_attn.proj.weight" ,"attn2.to_out.0.weight"), + ("cross_attn.proj.bias" ,"attn2.to_out.0.bias"), +} + +def pixart_to_diffusers(mmdit_config, output_prefix=""): + key_map = {} + + depth = mmdit_config.get("depth", 0) + offset = mmdit_config.get("hidden_size", 1152) + + for i in range(depth): + block_from = "transformer_blocks.{}".format(i) + block_to = "{}blocks.{}".format(output_prefix, i) + + for end in ("weight", "bias"): + s = "{}.attn1.".format(block_from) + qkv = "{}.attn.qkv.{}".format(block_to, end) + key_map["{}to_q.{}".format(s, end)] = (qkv, (0, 0, offset)) + key_map["{}to_k.{}".format(s, end)] = (qkv, (0, offset, offset)) + key_map["{}to_v.{}".format(s, end)] = (qkv, (0, offset * 2, offset)) + + s = "{}.attn2.".format(block_from) + q = "{}.cross_attn.q_linear.{}".format(block_to, end) + kv = "{}.cross_attn.kv_linear.{}".format(block_to, end) + + key_map["{}to_q.{}".format(s, end)] = q + key_map["{}to_k.{}".format(s, end)] = (kv, (0, 0, offset)) + key_map["{}to_v.{}".format(s, end)] = (kv, (0, offset, offset)) + + for k in PIXART_MAP_BLOCK: + key_map["{}.{}".format(block_from, k[1])] = "{}.{}".format(block_to, k[0]) + + for k in PIXART_MAP_BASIC: + key_map[k[1]] = "{}{}".format(output_prefix, k[0]) + + return key_map + +def auraflow_to_diffusers(mmdit_config, output_prefix=""): + n_double_layers = mmdit_config.get("n_double_layers", 0) + n_layers = mmdit_config.get("n_layers", 0) + + key_map = {} + for i in range(n_layers): + if i < n_double_layers: + index = i + prefix_from = "joint_transformer_blocks" + prefix_to = "{}double_layers".format(output_prefix) + block_map = { + "attn.to_q.weight": "attn.w2q.weight", + "attn.to_k.weight": "attn.w2k.weight", + "attn.to_v.weight": "attn.w2v.weight", + "attn.to_out.0.weight": "attn.w2o.weight", + "attn.add_q_proj.weight": "attn.w1q.weight", + "attn.add_k_proj.weight": "attn.w1k.weight", + "attn.add_v_proj.weight": "attn.w1v.weight", + "attn.to_add_out.weight": "attn.w1o.weight", + "ff.linear_1.weight": "mlpX.c_fc1.weight", + "ff.linear_2.weight": "mlpX.c_fc2.weight", + "ff.out_projection.weight": "mlpX.c_proj.weight", + "ff_context.linear_1.weight": "mlpC.c_fc1.weight", + "ff_context.linear_2.weight": "mlpC.c_fc2.weight", + "ff_context.out_projection.weight": "mlpC.c_proj.weight", + "norm1.linear.weight": "modX.1.weight", + "norm1_context.linear.weight": "modC.1.weight", + } + else: + index = i - n_double_layers + prefix_from = "single_transformer_blocks" + prefix_to = "{}single_layers".format(output_prefix) + + block_map = { + "attn.to_q.weight": "attn.w1q.weight", + "attn.to_k.weight": "attn.w1k.weight", + "attn.to_v.weight": "attn.w1v.weight", + "attn.to_out.0.weight": "attn.w1o.weight", + "norm1.linear.weight": "modCX.1.weight", + "ff.linear_1.weight": "mlp.c_fc1.weight", + "ff.linear_2.weight": "mlp.c_fc2.weight", + "ff.out_projection.weight": "mlp.c_proj.weight" + } + + for k in block_map: + key_map["{}.{}.{}".format(prefix_from, index, k)] = "{}.{}.{}".format(prefix_to, index, block_map[k]) + + MAP_BASIC = { + ("positional_encoding", "pos_embed.pos_embed"), + ("register_tokens", "register_tokens"), + ("t_embedder.mlp.0.weight", "time_step_proj.linear_1.weight"), + ("t_embedder.mlp.0.bias", "time_step_proj.linear_1.bias"), + ("t_embedder.mlp.2.weight", "time_step_proj.linear_2.weight"), + ("t_embedder.mlp.2.bias", "time_step_proj.linear_2.bias"), + ("cond_seq_linear.weight", "context_embedder.weight"), + ("init_x_linear.weight", "pos_embed.proj.weight"), + ("init_x_linear.bias", "pos_embed.proj.bias"), + ("final_linear.weight", "proj_out.weight"), + ("modF.1.weight", "norm_out.linear.weight", swap_scale_shift), + } + + for k in MAP_BASIC: + if len(k) > 2: + key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2]) + else: + key_map[k[1]] = "{}{}".format(output_prefix, k[0]) + + return key_map + +def flux_to_diffusers(mmdit_config, output_prefix=""): + n_double_layers = mmdit_config.get("depth", 0) + n_single_layers = mmdit_config.get("depth_single_blocks", 0) + hidden_size = mmdit_config.get("hidden_size", 0) + + key_map = {} + for index in range(n_double_layers): + prefix_from = "transformer_blocks.{}".format(index) + prefix_to = "{}double_blocks.{}".format(output_prefix, index) + + for end in ("weight", "bias"): + k = "{}.attn.".format(prefix_from) + qkv = "{}.img_attn.qkv.{}".format(prefix_to, end) + key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) + key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) + key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) + + k = "{}.attn.".format(prefix_from) + qkv = "{}.txt_attn.qkv.{}".format(prefix_to, end) + key_map["{}add_q_proj.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) + key_map["{}add_k_proj.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) + key_map["{}add_v_proj.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) + + block_map = { + "attn.to_out.0.weight": "img_attn.proj.weight", + "attn.to_out.0.bias": "img_attn.proj.bias", + "norm1.linear.weight": "img_mod.lin.weight", + "norm1.linear.bias": "img_mod.lin.bias", + "norm1_context.linear.weight": "txt_mod.lin.weight", + "norm1_context.linear.bias": "txt_mod.lin.bias", + "attn.to_add_out.weight": "txt_attn.proj.weight", + "attn.to_add_out.bias": "txt_attn.proj.bias", + "ff.net.0.proj.weight": "img_mlp.0.weight", + "ff.net.0.proj.bias": "img_mlp.0.bias", + "ff.net.2.weight": "img_mlp.2.weight", + "ff.net.2.bias": "img_mlp.2.bias", + "ff_context.net.0.proj.weight": "txt_mlp.0.weight", + "ff_context.net.0.proj.bias": "txt_mlp.0.bias", + "ff_context.net.2.weight": "txt_mlp.2.weight", + "ff_context.net.2.bias": "txt_mlp.2.bias", + "ff.linear_in.weight": "img_mlp.0.weight", # LyCoris LoKr + "ff.linear_in.bias": "img_mlp.0.bias", + "ff.linear_out.weight": "img_mlp.2.weight", + "ff.linear_out.bias": "img_mlp.2.bias", + "ff_context.linear_in.weight": "txt_mlp.0.weight", + "ff_context.linear_in.bias": "txt_mlp.0.bias", + "ff_context.linear_out.weight": "txt_mlp.2.weight", + "ff_context.linear_out.bias": "txt_mlp.2.bias", + "attn.norm_q.weight": "img_attn.norm.query_norm.weight", + "attn.norm_k.weight": "img_attn.norm.key_norm.weight", + "attn.norm_added_q.weight": "txt_attn.norm.query_norm.weight", + "attn.norm_added_k.weight": "txt_attn.norm.key_norm.weight", + } + + for k in block_map: + key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, block_map[k]) + + for index in range(n_single_layers): + prefix_from = "single_transformer_blocks.{}".format(index) + prefix_to = "{}single_blocks.{}".format(output_prefix, index) + + for end in ("weight", "bias"): + k = "{}.attn.".format(prefix_from) + qkv = "{}.linear1.{}".format(prefix_to, end) + key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) + key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) + key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) + key_map["{}.proj_mlp.{}".format(prefix_from, end)] = (qkv, (0, hidden_size * 3, hidden_size * 4)) + + block_map = { + "norm.linear.weight": "modulation.lin.weight", + "norm.linear.bias": "modulation.lin.bias", + "proj_out.weight": "linear2.weight", + "proj_out.bias": "linear2.bias", + "attn.norm_q.weight": "norm.query_norm.weight", + "attn.norm_k.weight": "norm.key_norm.weight", + "attn.to_qkv_mlp_proj.weight": "linear1.weight", # Flux 2 + "attn.to_out.weight": "linear2.weight", # Flux 2 + } + + for k in block_map: + key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, block_map[k]) + + MAP_BASIC = { + ("final_layer.linear.bias", "proj_out.bias"), + ("final_layer.linear.weight", "proj_out.weight"), + ("img_in.bias", "x_embedder.bias"), + ("img_in.weight", "x_embedder.weight"), + ("time_in.in_layer.bias", "time_text_embed.timestep_embedder.linear_1.bias"), + ("time_in.in_layer.weight", "time_text_embed.timestep_embedder.linear_1.weight"), + ("time_in.out_layer.bias", "time_text_embed.timestep_embedder.linear_2.bias"), + ("time_in.out_layer.weight", "time_text_embed.timestep_embedder.linear_2.weight"), + ("txt_in.bias", "context_embedder.bias"), + ("txt_in.weight", "context_embedder.weight"), + ("vector_in.in_layer.bias", "time_text_embed.text_embedder.linear_1.bias"), + ("vector_in.in_layer.weight", "time_text_embed.text_embedder.linear_1.weight"), + ("vector_in.out_layer.bias", "time_text_embed.text_embedder.linear_2.bias"), + ("vector_in.out_layer.weight", "time_text_embed.text_embedder.linear_2.weight"), + ("guidance_in.in_layer.bias", "time_text_embed.guidance_embedder.linear_1.bias"), + ("guidance_in.in_layer.weight", "time_text_embed.guidance_embedder.linear_1.weight"), + ("guidance_in.out_layer.bias", "time_text_embed.guidance_embedder.linear_2.bias"), + ("guidance_in.out_layer.weight", "time_text_embed.guidance_embedder.linear_2.weight"), + ("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift), + ("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift), + ("pos_embed_input.bias", "controlnet_x_embedder.bias"), + ("pos_embed_input.weight", "controlnet_x_embedder.weight"), + } + + for k in MAP_BASIC: + if len(k) > 2: + key_map[k[1]] = ("{}{}".format(output_prefix, k[0]), None, k[2]) + else: + key_map[k[1]] = "{}{}".format(output_prefix, k[0]) + + return key_map + +def z_image_to_diffusers(mmdit_config, output_prefix=""): + n_layers = mmdit_config.get("n_layers", 0) + hidden_size = mmdit_config.get("dim", 0) + n_context_refiner = mmdit_config.get("n_refiner_layers", 2) + n_noise_refiner = mmdit_config.get("n_refiner_layers", 2) + key_map = {} + + def add_block_keys(prefix_from, prefix_to, has_adaln=True): + for end in ("weight", "bias"): + k = "{}.attention.".format(prefix_from) + qkv = "{}.attention.qkv.{}".format(prefix_to, end) + key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) + key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) + key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) + + block_map = { + "attention.norm_q.weight": "attention.q_norm.weight", + "attention.norm_k.weight": "attention.k_norm.weight", + "attention.to_out.0.weight": "attention.out.weight", + "attention.to_out.0.bias": "attention.out.bias", + "attention_norm1.weight": "attention_norm1.weight", + "attention_norm2.weight": "attention_norm2.weight", + "feed_forward.w1.weight": "feed_forward.w1.weight", + "feed_forward.w2.weight": "feed_forward.w2.weight", + "feed_forward.w3.weight": "feed_forward.w3.weight", + "ffn_norm1.weight": "ffn_norm1.weight", + "ffn_norm2.weight": "ffn_norm2.weight", + } + if has_adaln: + block_map["adaLN_modulation.0.weight"] = "adaLN_modulation.0.weight" + block_map["adaLN_modulation.0.bias"] = "adaLN_modulation.0.bias" + for k, v in block_map.items(): + key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, v) + + for i in range(n_layers): + add_block_keys("layers.{}".format(i), "{}layers.{}".format(output_prefix, i)) + + for i in range(n_context_refiner): + add_block_keys("context_refiner.{}".format(i), "{}context_refiner.{}".format(output_prefix, i)) + + for i in range(n_noise_refiner): + add_block_keys("noise_refiner.{}".format(i), "{}noise_refiner.{}".format(output_prefix, i)) + + MAP_BASIC = [ + ("final_layer.linear.weight", "all_final_layer.2-1.linear.weight"), + ("final_layer.linear.bias", "all_final_layer.2-1.linear.bias"), + ("final_layer.adaLN_modulation.1.weight", "all_final_layer.2-1.adaLN_modulation.1.weight"), + ("final_layer.adaLN_modulation.1.bias", "all_final_layer.2-1.adaLN_modulation.1.bias"), + ("x_embedder.weight", "all_x_embedder.2-1.weight"), + ("x_embedder.bias", "all_x_embedder.2-1.bias"), + ("x_pad_token", "x_pad_token"), + ("cap_embedder.0.weight", "cap_embedder.0.weight"), + ("cap_embedder.1.weight", "cap_embedder.1.weight"), + ("cap_embedder.1.bias", "cap_embedder.1.bias"), + ("cap_pad_token", "cap_pad_token"), + ("t_embedder.mlp.0.weight", "t_embedder.mlp.0.weight"), + ("t_embedder.mlp.0.bias", "t_embedder.mlp.0.bias"), + ("t_embedder.mlp.2.weight", "t_embedder.mlp.2.weight"), + ("t_embedder.mlp.2.bias", "t_embedder.mlp.2.bias"), + ] + + for c, diffusers in MAP_BASIC: + key_map[diffusers] = "{}{}".format(output_prefix, c) + + return key_map + +def repeat_to_batch_size(tensor, batch_size, dim=0): + if tensor.shape[dim] > batch_size: + return tensor.narrow(dim, 0, batch_size) + elif tensor.shape[dim] < batch_size: + return tensor.repeat(dim * [1] + [math.ceil(batch_size / tensor.shape[dim])] + [1] * (len(tensor.shape) - 1 - dim)).narrow(dim, 0, batch_size) + return tensor + +def resize_to_batch_size(tensor, batch_size): + in_batch_size = tensor.shape[0] + if in_batch_size == batch_size: + return tensor + + if batch_size <= 1: + return tensor[:batch_size] + + output = torch.empty([batch_size] + list(tensor.shape)[1:], dtype=tensor.dtype, device=tensor.device) + if batch_size < in_batch_size: + scale = (in_batch_size - 1) / (batch_size - 1) + for i in range(batch_size): + output[i] = tensor[min(round(i * scale), in_batch_size - 1)] + else: + scale = in_batch_size / batch_size + for i in range(batch_size): + output[i] = tensor[min(math.floor((i + 0.5) * scale), in_batch_size - 1)] + + return output + +def resize_list_to_batch_size(l, batch_size): + in_batch_size = len(l) + if in_batch_size == batch_size or in_batch_size == 0: + return l + + if batch_size <= 1: + return l[:batch_size] + + output = [] + if batch_size < in_batch_size: + scale = (in_batch_size - 1) / (batch_size - 1) + for i in range(batch_size): + output.append(l[min(round(i * scale), in_batch_size - 1)]) + else: + scale = in_batch_size / batch_size + for i in range(batch_size): + output.append(l[min(math.floor((i + 0.5) * scale), in_batch_size - 1)]) + + return output + +def convert_sd_to(state_dict, dtype): + keys = list(state_dict.keys()) + for k in keys: + state_dict[k] = state_dict[k].to(dtype) + return state_dict + +def safetensors_header(safetensors_path, max_size=100*1024*1024): + with open(safetensors_path, "rb") as f: + header = f.read(8) + length_of_header = struct.unpack(' max_size: + return None + return f.read(length_of_header) + +ATTR_UNSET={} + +def set_attr(obj, attr, value): + attrs = attr.split(".") + for name in attrs[:-1]: + obj = getattr(obj, name) + prev = getattr(obj, attrs[-1], ATTR_UNSET) + if value is ATTR_UNSET: + delattr(obj, attrs[-1]) + else: + setattr(obj, attrs[-1], value) + return prev + +def set_attr_param(obj, attr, value): + return set_attr(obj, attr, torch.nn.Parameter(value, requires_grad=False)) + +def copy_to_param(obj, attr, value): + # inplace update tensor instead of replacing it + attrs = attr.split(".") + for name in attrs[:-1]: + obj = getattr(obj, name) + prev = getattr(obj, attrs[-1]) + prev.data.copy_(value) + +def get_attr(obj, attr: str): + """Retrieves a nested attribute from an object using dot notation. + + Args: + obj: The object to get the attribute from + attr (str): The attribute path using dot notation (e.g. "model.layer.weight") + + Returns: + The value of the requested attribute + + Example: + model = MyModel() + weight = get_attr(model, "layer1.conv.weight") + # Equivalent to: model.layer1.conv.weight + + Important: + Always prefer `comfy.model_patcher.ModelPatcher.get_model_object` when + accessing nested model objects under `ModelPatcher.model`. + """ + attrs = attr.split(".") + for name in attrs: + obj = getattr(obj, name) + return obj + +def bislerp(samples, width, height): + def slerp(b1, b2, r): + '''slerps batches b1, b2 according to ratio r, batches should be flat e.g. NxC''' + + c = b1.shape[-1] + + #norms + b1_norms = torch.norm(b1, dim=-1, keepdim=True) + b2_norms = torch.norm(b2, dim=-1, keepdim=True) + + #normalize + b1_normalized = b1 / b1_norms + b2_normalized = b2 / b2_norms + + #zero when norms are zero + b1_normalized[b1_norms.expand(-1,c) == 0.0] = 0.0 + b2_normalized[b2_norms.expand(-1,c) == 0.0] = 0.0 + + #slerp + dot = (b1_normalized*b2_normalized).sum(1) + omega = torch.acos(dot) + so = torch.sin(omega) + + #technically not mathematically correct, but more pleasing? + res = (torch.sin((1.0-r.squeeze(1))*omega)/so).unsqueeze(1)*b1_normalized + (torch.sin(r.squeeze(1)*omega)/so).unsqueeze(1) * b2_normalized + res *= (b1_norms * (1.0-r) + b2_norms * r).expand(-1,c) + + #edge cases for same or polar opposites + res[dot > 1 - 1e-5] = b1[dot > 1 - 1e-5] + res[dot < 1e-5 - 1] = (b1 * (1.0-r) + b2 * r)[dot < 1e-5 - 1] + return res + + def generate_bilinear_data(length_old, length_new, device): + coords_1 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) + coords_1 = torch.nn.functional.interpolate(coords_1, size=(1, length_new), mode="bilinear") + ratios = coords_1 - coords_1.floor() + coords_1 = coords_1.to(torch.int64) + + coords_2 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) + 1 + coords_2[:,:,:,-1] -= 1 + coords_2 = torch.nn.functional.interpolate(coords_2, size=(1, length_new), mode="bilinear") + coords_2 = coords_2.to(torch.int64) + return ratios, coords_1, coords_2 + + orig_dtype = samples.dtype + samples = samples.float() + n,c,h,w = samples.shape + h_new, w_new = (height, width) + + #linear w + ratios, coords_1, coords_2 = generate_bilinear_data(w, w_new, samples.device) + coords_1 = coords_1.expand((n, c, h, -1)) + coords_2 = coords_2.expand((n, c, h, -1)) + ratios = ratios.expand((n, 1, h, -1)) + + pass_1 = samples.gather(-1,coords_1).movedim(1, -1).reshape((-1,c)) + pass_2 = samples.gather(-1,coords_2).movedim(1, -1).reshape((-1,c)) + ratios = ratios.movedim(1, -1).reshape((-1,1)) + + result = slerp(pass_1, pass_2, ratios) + result = result.reshape(n, h, w_new, c).movedim(-1, 1) + + #linear h + ratios, coords_1, coords_2 = generate_bilinear_data(h, h_new, samples.device) + coords_1 = coords_1.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) + coords_2 = coords_2.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) + ratios = ratios.reshape((1,1,-1,1)).expand((n, 1, -1, w_new)) + + pass_1 = result.gather(-2,coords_1).movedim(1, -1).reshape((-1,c)) + pass_2 = result.gather(-2,coords_2).movedim(1, -1).reshape((-1,c)) + ratios = ratios.movedim(1, -1).reshape((-1,1)) + + result = slerp(pass_1, pass_2, ratios) + result = result.reshape(n, h_new, w_new, c).movedim(-1, 1) + return result.to(orig_dtype) + +def lanczos(samples, width, height): + #the below API is strict and expects grayscale to be squeezed + samples = samples.squeeze(1) if samples.shape[1] == 1 else samples.movedim(1, -1) + images = [Image.fromarray(np.clip(255. * image.cpu().numpy(), 0, 255).astype(np.uint8)) for image in samples] + images = [image.resize((width, height), resample=Image.Resampling.LANCZOS) for image in images] + images = [torch.from_numpy(np.array(image).astype(np.float32) / 255.0).movedim(-1, 0) for image in images] + result = torch.stack(images) + return result.to(samples.device, samples.dtype) + +def common_upscale(samples, width, height, upscale_method, crop): + orig_shape = tuple(samples.shape) + if len(orig_shape) > 4: + samples = samples.reshape(samples.shape[0], samples.shape[1], -1, samples.shape[-2], samples.shape[-1]) + samples = samples.movedim(2, 1) + samples = samples.reshape(-1, orig_shape[1], orig_shape[-2], orig_shape[-1]) + if crop == "center": + old_width = samples.shape[-1] + old_height = samples.shape[-2] + old_aspect = old_width / old_height + new_aspect = width / height + x = 0 + y = 0 + if old_aspect > new_aspect: + x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) + elif old_aspect < new_aspect: + y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) + s = samples.narrow(-2, y, old_height - y * 2).narrow(-1, x, old_width - x * 2) + else: + s = samples + + if upscale_method == "bislerp": + out = bislerp(s, width, height) + elif upscale_method == "lanczos": + out = lanczos(s, width, height) + else: + out = torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method) + + if len(orig_shape) == 4: + return out + + out = out.reshape((orig_shape[0], -1, orig_shape[1]) + (height, width)) + return out.movedim(2, 1).reshape(orig_shape[:-2] + (height, width)) + +def get_tiled_scale_steps(width, height, tile_x, tile_y, overlap): + rows = 1 if height <= tile_y else math.ceil((height - overlap) / (tile_y - overlap)) + cols = 1 if width <= tile_x else math.ceil((width - overlap) / (tile_x - overlap)) + return rows * cols + +@torch.inference_mode() +def tiled_scale_multidim(samples, function, tile=(64, 64), overlap=8, upscale_amount=4, out_channels=3, output_device="cpu", downscale=False, index_formulas=None, pbar=None): + dims = len(tile) + + if not (isinstance(upscale_amount, (tuple, list))): + upscale_amount = [upscale_amount] * dims + + if not (isinstance(overlap, (tuple, list))): + overlap = [overlap] * dims + + if index_formulas is None: + index_formulas = upscale_amount + + if not (isinstance(index_formulas, (tuple, list))): + index_formulas = [index_formulas] * dims + + def get_upscale(dim, val): + up = upscale_amount[dim] + if callable(up): + return up(val) + else: + return up * val + + def get_downscale(dim, val): + up = upscale_amount[dim] + if callable(up): + return up(val) + else: + return val / up + + def get_upscale_pos(dim, val): + up = index_formulas[dim] + if callable(up): + return up(val) + else: + return up * val + + def get_downscale_pos(dim, val): + up = index_formulas[dim] + if callable(up): + return up(val) + else: + return val / up + + if downscale: + get_scale = get_downscale + get_pos = get_downscale_pos + else: + get_scale = get_upscale + get_pos = get_upscale_pos + + def mult_list_upscale(a): + out = [] + for i in range(len(a)): + out.append(round(get_scale(i, a[i]))) + return out + + output = torch.empty([samples.shape[0], out_channels] + mult_list_upscale(samples.shape[2:]), device=output_device) + + for b in range(samples.shape[0]): + s = samples[b:b+1] + + # handle entire input fitting in a single tile + if all(s.shape[d+2] <= tile[d] for d in range(dims)): + output[b:b+1] = function(s).to(output_device) + if pbar is not None: + pbar.update(1) + continue + + out = torch.zeros([s.shape[0], out_channels] + mult_list_upscale(s.shape[2:]), device=output_device) + out_div = torch.zeros([s.shape[0], out_channels] + mult_list_upscale(s.shape[2:]), device=output_device) + + positions = [range(0, s.shape[d+2] - overlap[d], tile[d] - overlap[d]) if s.shape[d+2] > tile[d] else [0] for d in range(dims)] + + for it in itertools.product(*positions): + s_in = s + upscaled = [] + + for d in range(dims): + pos = max(0, min(s.shape[d + 2] - overlap[d], it[d])) + l = min(tile[d], s.shape[d + 2] - pos) + s_in = s_in.narrow(d + 2, pos, l) + upscaled.append(round(get_pos(d, pos))) + + ps = function(s_in).to(output_device) + mask = torch.ones_like(ps) + + for d in range(2, dims + 2): + feather = round(get_scale(d - 2, overlap[d - 2])) + if feather >= mask.shape[d]: + continue + for t in range(feather): + a = (t + 1) / feather + mask.narrow(d, t, 1).mul_(a) + mask.narrow(d, mask.shape[d] - 1 - t, 1).mul_(a) + + o = out + o_d = out_div + for d in range(dims): + o = o.narrow(d + 2, upscaled[d], mask.shape[d + 2]) + o_d = o_d.narrow(d + 2, upscaled[d], mask.shape[d + 2]) + + o.add_(ps * mask) + o_d.add_(mask) + + if pbar is not None: + pbar.update(1) + + output[b:b+1] = out/out_div + return output + +def tiled_scale(samples, function, tile_x=64, tile_y=64, overlap = 8, upscale_amount = 4, out_channels = 3, output_device="cpu", pbar = None): + return tiled_scale_multidim(samples, function, (tile_y, tile_x), overlap=overlap, upscale_amount=upscale_amount, out_channels=out_channels, output_device=output_device, pbar=pbar) + +def model_trange(*args, **kwargs): + if not comfy.memory_management.aimdo_enabled: + return trange(*args, **kwargs) + + pbar = trange(*args, **kwargs, smoothing=1.0) + pbar._i = 0 + pbar.set_postfix_str(" Model Initializing ... ") + + _update = pbar.update + + def warmup_update(n=1): + pbar._i += 1 + if pbar._i == 1: + pbar.i1_time = time.time() + pbar.set_postfix_str(" Model Initialization complete! ") + elif pbar._i == 2: + #bring forward the effective start time based the the diff between first and second iteration + #to attempt to remove load overhead from the final step rate estimate. + pbar.start_t = pbar.i1_time - (time.time() - pbar.i1_time) + pbar.set_postfix_str("") + + _update(n) + + pbar.update = warmup_update + return pbar + +PROGRESS_BAR_ENABLED = True +def set_progress_bar_enabled(enabled): + global PROGRESS_BAR_ENABLED + PROGRESS_BAR_ENABLED = enabled + +PROGRESS_BAR_HOOK = None +def set_progress_bar_global_hook(function): + global PROGRESS_BAR_HOOK + PROGRESS_BAR_HOOK = function + +# Throttle settings for progress bar updates to reduce WebSocket flooding +PROGRESS_THROTTLE_MIN_INTERVAL = 0.1 # 100ms minimum between updates +PROGRESS_THROTTLE_MIN_PERCENT = 0.5 # 0.5% minimum progress change + +class ProgressBar: + def __init__(self, total, node_id=None): + global PROGRESS_BAR_HOOK + self.total = total + self.current = 0 + self.hook = PROGRESS_BAR_HOOK + self.node_id = node_id + self._last_update_time = 0.0 + self._last_sent_value = -1 + + def update_absolute(self, value, total=None, preview=None): + if total is not None: + self.total = total + if value > self.total: + value = self.total + self.current = value + if self.hook is not None: + current_time = time.perf_counter() + is_first = (self._last_sent_value < 0) + is_final = (value >= self.total) + has_preview = (preview is not None) + + # Always send immediately for previews, first update, or final update + if has_preview or is_first or is_final: + self.hook(self.current, self.total, preview, node_id=self.node_id) + self._last_update_time = current_time + self._last_sent_value = value + return + + # Apply throttling for regular progress updates + if self.total > 0: + percent_changed = ((value - max(0, self._last_sent_value)) / self.total) * 100 + else: + percent_changed = 100 + time_elapsed = current_time - self._last_update_time + + if time_elapsed >= PROGRESS_THROTTLE_MIN_INTERVAL and percent_changed >= PROGRESS_THROTTLE_MIN_PERCENT: + self.hook(self.current, self.total, preview, node_id=self.node_id) + self._last_update_time = current_time + self._last_sent_value = value + + def update(self, value): + self.update_absolute(self.current + value) + +def reshape_mask(input_mask, output_shape): + dims = len(output_shape) - 2 + + if dims == 1: + scale_mode = "linear" + + if dims == 2: + input_mask = input_mask.reshape((-1, 1, input_mask.shape[-2], input_mask.shape[-1])) + scale_mode = "bilinear" + + if dims == 3: + if len(input_mask.shape) < 5: + input_mask = input_mask.reshape((1, 1, -1, input_mask.shape[-2], input_mask.shape[-1])) + scale_mode = "trilinear" + + mask = torch.nn.functional.interpolate(input_mask, size=output_shape[2:], mode=scale_mode) + if mask.shape[1] < output_shape[1]: + mask = mask.repeat((1, output_shape[1]) + (1,) * dims)[:,:output_shape[1]] + mask = repeat_to_batch_size(mask, output_shape[0]) + return mask + +def upscale_dit_mask(mask: torch.Tensor, img_size_in, img_size_out): + hi, wi = img_size_in + ho, wo = img_size_out + # if it's already the correct size, no need to do anything + if (hi, wi) == (ho, wo): + return mask + if mask.ndim == 2: + mask = mask.unsqueeze(0) + if mask.ndim != 3: + raise ValueError(f"Got a mask of shape {list(mask.shape)}, expected [b, q, k] or [q, k]") + txt_tokens = mask.shape[1] - (hi * wi) + # quadrants of the mask + txt_to_txt = mask[:, :txt_tokens, :txt_tokens] + txt_to_img = mask[:, :txt_tokens, txt_tokens:] + img_to_img = mask[:, txt_tokens:, txt_tokens:] + img_to_txt = mask[:, txt_tokens:, :txt_tokens] + + # convert to 1d x 2d, interpolate, then back to 1d x 1d + txt_to_img = rearrange (txt_to_img, "b t (h w) -> b t h w", h=hi, w=wi) + txt_to_img = interpolate(txt_to_img, size=img_size_out, mode="bilinear") + txt_to_img = rearrange (txt_to_img, "b t h w -> b t (h w)") + # this one is hard because we have to do it twice + # convert to 1d x 2d, interpolate, then to 2d x 1d, interpolate, then 1d x 1d + img_to_img = rearrange (img_to_img, "b hw (h w) -> b hw h w", h=hi, w=wi) + img_to_img = interpolate(img_to_img, size=img_size_out, mode="bilinear") + img_to_img = rearrange (img_to_img, "b (hk wk) hq wq -> b (hq wq) hk wk", hk=hi, wk=wi) + img_to_img = interpolate(img_to_img, size=img_size_out, mode="bilinear") + img_to_img = rearrange (img_to_img, "b (hq wq) hk wk -> b (hk wk) (hq wq)", hq=ho, wq=wo) + # convert to 2d x 1d, interpolate, then back to 1d x 1d + img_to_txt = rearrange (img_to_txt, "b (h w) t -> b t h w", h=hi, w=wi) + img_to_txt = interpolate(img_to_txt, size=img_size_out, mode="bilinear") + img_to_txt = rearrange (img_to_txt, "b t h w -> b (h w) t") + + # reassemble the mask from blocks + out = torch.cat([ + torch.cat([txt_to_txt, txt_to_img], dim=2), + torch.cat([img_to_txt, img_to_img], dim=2)], + dim=1 + ) + return out + +def pack_latents(latents): + latent_shapes = [] + tensors = [] + for tensor in latents: + latent_shapes.append(tensor.shape) + tensors.append(tensor.reshape(tensor.shape[0], 1, -1)) + + latent = torch.cat(tensors, dim=-1) + return latent, latent_shapes + +def unpack_latents(combined_latent, latent_shapes): + if len(latent_shapes) > 1: + output_tensors = [] + for shape in latent_shapes: + cut = math.prod(shape[1:]) + tens = combined_latent[:, :, :cut] + combined_latent = combined_latent[:, :, cut:] + output_tensors.append(tens.reshape([tens.shape[0]] + list(shape)[1:])) + else: + output_tensors = [combined_latent] + return output_tensors + +def detect_layer_quantization(state_dict, prefix): + for k in state_dict: + if k.startswith(prefix) and k.endswith(".comfy_quant"): + logging.info("Found quantization metadata version 1") + return {"mixed_ops": True} + return None + +def convert_old_quants(state_dict, model_prefix="", metadata={}): + if metadata is None: + metadata = {} + + quant_metadata = None + if "_quantization_metadata" not in metadata: + scaled_fp8_key = "{}scaled_fp8".format(model_prefix) + + if scaled_fp8_key in state_dict: + scaled_fp8_weight = state_dict[scaled_fp8_key] + scaled_fp8_dtype = scaled_fp8_weight.dtype + if scaled_fp8_dtype == torch.float32: + scaled_fp8_dtype = torch.float8_e4m3fn + + if scaled_fp8_weight.nelement() == 2: + full_precision_matrix_mult = True + else: + full_precision_matrix_mult = False + + out_sd = {} + layers = {} + for k in list(state_dict.keys()): + if k == scaled_fp8_key: + continue + if not k.startswith(model_prefix): + out_sd[k] = state_dict[k] + continue + k_out = k + w = state_dict.pop(k) + layer = None + if k_out.endswith(".scale_weight"): + layer = k_out[:-len(".scale_weight")] + k_out = "{}.weight_scale".format(layer) + + if layer is not None: + layer_conf = {"format": "float8_e4m3fn"} # TODO: check if anyone did some non e4m3fn scaled checkpoints + if full_precision_matrix_mult: + layer_conf["full_precision_matrix_mult"] = full_precision_matrix_mult + layers[layer] = layer_conf + + if k_out.endswith(".scale_input"): + layer = k_out[:-len(".scale_input")] + k_out = "{}.input_scale".format(layer) + if w.item() == 1.0: + continue + + out_sd[k_out] = w + + state_dict = out_sd + quant_metadata = {"layers": layers} + else: + quant_metadata = json.loads(metadata["_quantization_metadata"]) + + if quant_metadata is not None: + layers = quant_metadata["layers"] + for k, v in layers.items(): + state_dict["{}.comfy_quant".format(k)] = torch.tensor(list(json.dumps(v).encode('utf-8')), dtype=torch.uint8) + + return state_dict, metadata + +def string_to_seed(data): + crc = 0xFFFFFFFF + for byte in data: + if isinstance(byte, str): + byte = ord(byte) + crc ^= byte + for _ in range(8): + if crc & 1: + crc = (crc >> 1) ^ 0xEDB88320 + else: + crc >>= 1 + return crc ^ 0xFFFFFFFF + +def deepcopy_list_dict(obj, memo=None): + if memo is None: + memo = {} + + obj_id = id(obj) + if obj_id in memo: + return memo[obj_id] + + if isinstance(obj, dict): + res = {deepcopy_list_dict(k, memo): deepcopy_list_dict(v, memo) for k, v in obj.items()} + elif isinstance(obj, list): + res = [deepcopy_list_dict(i, memo) for i in obj] + else: + res = obj + + memo[obj_id] = res + return res + +def normalize_image_embeddings(embeds, embeds_info, scale_factor): + """Normalize image embeddings to match text embedding scale""" + for info in embeds_info: + if info.get("type") == "image": + start_idx = info["index"] + end_idx = start_idx + info["size"] + embeds[:, start_idx:end_idx, :] /= scale_factor diff --git a/docs/hel-892/sdpose-reference/core0150__comfy_api__latest___io.py b/docs/hel-892/sdpose-reference/core0150__comfy_api__latest___io.py new file mode 100644 index 00000000..02572707 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150__comfy_api__latest___io.py @@ -0,0 +1,2227 @@ +from __future__ import annotations + +import copy +import inspect +from abc import ABC, abstractmethod +from collections import Counter +from collections.abc import Iterable +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Callable, Literal, TypedDict, TypeVar, TYPE_CHECKING +from typing_extensions import NotRequired, final + +# used for type hinting +import torch + +if TYPE_CHECKING: + from spandrel import ImageModelDescriptor + from comfy.clip_vision import ClipVisionModel + from comfy.clip_vision import Output as ClipVisionOutput_ + from comfy.controlnet import ControlNet + from comfy.hooks import HookGroup, HookKeyframeGroup + from comfy.model_patcher import ModelPatcher + from comfy.samplers import CFGGuider, Sampler + from comfy.sd import CLIP, VAE + from comfy.sd import StyleModel as StyleModel_ + from comfy_api.input import VideoInput +from comfy_api.internal import (_ComfyNodeInternal, _NodeOutputInternal, classproperty, copy_class, first_real_override, is_class, + prune_dict, shallow_clone_class) +from comfy_execution.graph_utils import ExecutionBlocker +from ._util import MESH, VOXEL, SVG as _SVG, File3D + + +class FolderType(str, Enum): + input = "input" + output = "output" + temp = "temp" + + +class UploadType(str, Enum): + image = "image_upload" + audio = "audio_upload" + video = "video_upload" + model = "file_upload" + + +class RemoteOptions: + def __init__(self, route: str, refresh_button: bool, control_after_refresh: Literal["first", "last"]="first", + timeout: int=None, max_retries: int=None, refresh: int=None): + self.route = route + """The route to the remote source.""" + self.refresh_button = refresh_button + """Specifies whether to show a refresh button in the UI below the widget.""" + self.control_after_refresh = control_after_refresh + """Specifies the control after the refresh button is clicked. If "first", the first item will be automatically selected, and so on.""" + self.timeout = timeout + """The maximum amount of time to wait for a response from the remote source in milliseconds.""" + self.max_retries = max_retries + """The maximum number of retries before aborting the request.""" + self.refresh = refresh + """The TTL of the remote input's value in milliseconds. Specifies the interval at which the remote input's value is refreshed.""" + + def as_dict(self): + return prune_dict({ + "route": self.route, + "refresh_button": self.refresh_button, + "control_after_refresh": self.control_after_refresh, + "timeout": self.timeout, + "max_retries": self.max_retries, + "refresh": self.refresh, + }) + + +class NumberDisplay(str, Enum): + number = "number" + slider = "slider" + gradient_slider = "gradientslider" + + +class ControlAfterGenerate(str, Enum): + fixed = "fixed" + increment = "increment" + decrement = "decrement" + randomize = "randomize" + +class _ComfyType(ABC): + Type = Any + io_type: str = None + +# NOTE: this is a workaround to make the decorator return the correct type +T = TypeVar("T", bound=type) +def comfytype(io_type: str, **kwargs): + ''' + Decorator to mark nested classes as ComfyType; io_type will be bound to the class. + + A ComfyType may have the following attributes: + - Type = + - class Input(Input): ... + - class Output(Output): ... + ''' + def decorator(cls: T) -> T: + if isinstance(cls, _ComfyType) or issubclass(cls, _ComfyType): + # clone Input and Output classes to avoid modifying the original class + new_cls = cls + if hasattr(new_cls, "Input"): + new_cls.Input = copy_class(new_cls.Input) + if hasattr(new_cls, "Output"): + new_cls.Output = copy_class(new_cls.Output) + else: + # copy class attributes except for special ones that shouldn't be in type() + cls_dict = { + k: v for k, v in cls.__dict__.items() + if k not in ('__dict__', '__weakref__', '__module__', '__doc__') + } + # new class + new_cls: ComfyTypeIO = type( + cls.__name__, + (cls, ComfyTypeIO), + cls_dict + ) + # metadata preservation + new_cls.__module__ = cls.__module__ + new_cls.__doc__ = cls.__doc__ + # assign ComfyType attributes, if needed + new_cls.io_type = io_type + if hasattr(new_cls, "Input") and new_cls.Input is not None: + new_cls.Input.Parent = new_cls + if hasattr(new_cls, "Output") and new_cls.Output is not None: + new_cls.Output.Parent = new_cls + return new_cls + return decorator + +def Custom(io_type: str) -> type[ComfyTypeIO]: + '''Create a ComfyType for a custom io_type.''' + @comfytype(io_type=io_type) + class CustomComfyType(ComfyTypeIO): + ... + return CustomComfyType + +class _IO_V3: + ''' + Base class for V3 Inputs and Outputs. + ''' + Parent: _ComfyType = None + + def __init__(self): + pass + + def validate(self): + pass + + @property + def io_type(self): + return self.Parent.io_type + + @property + def Type(self): + return self.Parent.Type + +class Input(_IO_V3): + ''' + Base class for a V3 Input. + ''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__() + self.id = id + self.display_name = display_name + self.optional = optional + self.tooltip = tooltip + self.lazy = lazy + self.extra_dict = extra_dict if extra_dict is not None else {} + self.rawLink = raw_link + self.advanced = advanced + + def as_dict(self): + return prune_dict({ + "display_name": self.display_name, + "optional": self.optional, + "tooltip": self.tooltip, + "lazy": self.lazy, + "rawLink": self.rawLink, + "advanced": self.advanced, + }) | prune_dict(self.extra_dict) + + def get_io_type(self): + return self.io_type + + def get_all(self) -> list[Input]: + return [self] + +class WidgetInput(Input): + ''' + Base class for a V3 Input with widget. + ''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: Any=None, + socketless: bool=None, widget_type: str=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self.default = default + self.socketless = socketless + self.widget_type = widget_type + self.force_input = force_input + + def as_dict(self): + return super().as_dict() | prune_dict({ + "default": self.default, + "socketless": self.socketless, + "widgetType": self.widget_type, + "forceInput": self.force_input, + }) + + def get_io_type(self): + return self.widget_type if self.widget_type is not None else super().get_io_type() + + +class Output(_IO_V3): + def __init__(self, id: str=None, display_name: str=None, tooltip: str=None, + is_output_list=False): + self.id = id + self.display_name = display_name if display_name else id + self.tooltip = tooltip + self.is_output_list = is_output_list + + def as_dict(self): + display_name = self.display_name if self.display_name else self.id + return prune_dict({ + "display_name": display_name, + "tooltip": self.tooltip, + "is_output_list": self.is_output_list, + }) + + def get_io_type(self): + return self.io_type + + +class ComfyTypeI(_ComfyType): + '''ComfyType subclass that only has a default Input class - intended for types that only have Inputs.''' + class Input(Input): + ... + +class ComfyTypeIO(ComfyTypeI): + '''ComfyType subclass that has default Input and Output classes; useful for types with both Inputs and Outputs.''' + class Output(Output): + ... + + +@comfytype(io_type="BOOLEAN") +class Boolean(ComfyTypeIO): + Type = bool + + class Input(WidgetInput): + '''Boolean input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: bool=None, label_on: str=None, label_off: str=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.label_on = label_on + self.label_off = label_off + self.default: bool + + def as_dict(self): + return super().as_dict() | prune_dict({ + "label_on": self.label_on, + "label_off": self.label_off, + }) + +@comfytype(io_type="INT") +class Int(ComfyTypeIO): + Type = int + + class Input(WidgetInput): + '''Integer input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: int=None, min: int=None, max: int=None, step: int=None, control_after_generate: bool | ControlAfterGenerate=None, + display_mode: NumberDisplay=None, socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.min = min + self.max = max + self.step = step + self.control_after_generate = control_after_generate + self.display_mode = display_mode + self.default: int + + def as_dict(self): + return super().as_dict() | prune_dict({ + "min": self.min, + "max": self.max, + "step": self.step, + "control_after_generate": self.control_after_generate, + "display": self.display_mode.value if self.display_mode else None, + }) + +@comfytype(io_type="FLOAT") +class Float(ComfyTypeIO): + Type = float + + class Input(WidgetInput): + '''Float input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: float=None, min: float=None, max: float=None, step: float=None, round: float=None, + display_mode: NumberDisplay=None, gradient_stops: list[list[float]]=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.min = min + self.max = max + self.step = step + self.round = round + self.display_mode = display_mode + self.gradient_stops = gradient_stops + self.default: float + + def as_dict(self): + return super().as_dict() | prune_dict({ + "min": self.min, + "max": self.max, + "step": self.step, + "round": self.round, + "display": self.display_mode, + "gradient_stops": self.gradient_stops, + }) + +@comfytype(io_type="STRING") +class String(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + '''String input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + multiline=False, placeholder: str=None, default: str=None, dynamic_prompts: bool=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.multiline = multiline + self.placeholder = placeholder + self.dynamic_prompts = dynamic_prompts + self.default: str + + def as_dict(self): + return super().as_dict() | prune_dict({ + "multiline": self.multiline, + "placeholder": self.placeholder, + "dynamicPrompts": self.dynamic_prompts, + }) + +@comfytype(io_type="COMBO") +class Combo(ComfyTypeIO): + Type = str + class Input(WidgetInput): + """Combo input (dropdown).""" + Type = str + def __init__( + self, + id: str, + options: list[str] | list[int] | type[Enum] = None, + display_name: str=None, + optional=False, + tooltip: str=None, + lazy: bool=None, + default: str | int | Enum = None, + control_after_generate: bool | ControlAfterGenerate=None, + upload: UploadType=None, + image_folder: FolderType=None, + remote: RemoteOptions=None, + socketless: bool=None, + extra_dict=None, + raw_link: bool=None, + advanced: bool=None, + ): + if isinstance(options, type) and issubclass(options, Enum): + options = [v.value for v in options] + if isinstance(default, Enum): + default = default.value + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, None, extra_dict, raw_link, advanced) + self.multiselect = False + self.options = options + self.control_after_generate = control_after_generate + self.upload = upload + self.image_folder = image_folder + self.remote = remote + self.default: str + + def as_dict(self): + return super().as_dict() | prune_dict({ + "multiselect": self.multiselect, + "options": self.options, + "control_after_generate": self.control_after_generate, + **({self.upload.value: True} if self.upload is not None else {}), + "image_folder": self.image_folder.value if self.image_folder else None, + "remote": self.remote.as_dict() if self.remote else None, + }) + + class Output(Output): + def __init__(self, id: str=None, display_name: str=None, options: list[str]=None, tooltip: str=None, is_output_list=False): + super().__init__(id, display_name, tooltip, is_output_list) + self.options = options if options is not None else [] + +@comfytype(io_type="COMBO") +class MultiCombo(ComfyTypeI): + '''Multiselect Combo input (dropdown for selecting potentially more than one value).''' + # TODO: something is wrong with the serialization, frontend does not recognize it as multiselect + Type = list[str] + class Input(Combo.Input): + def __init__(self, id: str, options: list[str], display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: list[str]=None, placeholder: str=None, chip: bool=None, control_after_generate: bool | ControlAfterGenerate=None, + socketless: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, options, display_name, optional, tooltip, lazy, default, control_after_generate, socketless=socketless, extra_dict=extra_dict, raw_link=raw_link, advanced=advanced) + self.multiselect = True + self.placeholder = placeholder + self.chip = chip + self.default: list[str] + + def as_dict(self): + to_return = super().as_dict() | prune_dict({ + "multi_select": self.multiselect, + "placeholder": self.placeholder, + "chip": self.chip, + }) + return to_return + +@comfytype(io_type="IMAGE") +class Image(ComfyTypeIO): + Type = torch.Tensor + + +@comfytype(io_type="WAN_CAMERA_EMBEDDING") +class WanCameraEmbedding(ComfyTypeIO): + Type = torch.Tensor + + +@comfytype(io_type="WEBCAM") +class Webcam(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + """Webcam input.""" + Type = str + def __init__( + self, id: str, display_name: str=None, optional=False, + tooltip: str=None, lazy: bool=None, default: str=None, socketless: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None + ): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, None, extra_dict, raw_link, advanced) + + +@comfytype(io_type="MASK") +class Mask(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="LATENT") +class Latent(ComfyTypeIO): + '''Latents are stored as a dictionary.''' + class LatentDict(TypedDict): + samples: torch.Tensor + '''Latent tensors.''' + noise_mask: NotRequired[torch.Tensor] + batch_index: NotRequired[list[int]] + type: NotRequired[str] + '''Only needed if dealing with these types: audio, hunyuan3dv2''' + Type = LatentDict + +@comfytype(io_type="CONDITIONING") +class Conditioning(ComfyTypeIO): + class PooledDict(TypedDict): + pooled_output: torch.Tensor + '''Pooled output from CLIP.''' + control: NotRequired[ControlNet] + '''ControlNet to apply to conditioning.''' + control_apply_to_uncond: NotRequired[bool] + '''Whether to apply ControlNet to matching negative conditioning at sample time, if applicable.''' + cross_attn_controlnet: NotRequired[torch.Tensor] + '''CrossAttn from CLIP to use for controlnet only.''' + pooled_output_controlnet: NotRequired[torch.Tensor] + '''Pooled output from CLIP to use for controlnet only.''' + gligen: NotRequired[tuple[str, Gligen, list[tuple[torch.Tensor, int, ...]]]] + '''GLIGEN to apply to conditioning.''' + area: NotRequired[tuple[int, ...] | tuple[str, float, ...]] + '''Set area of conditioning. First half of values apply to dimensions, the second half apply to coordinates. + By default, the dimensions are based on total pixel amount, but the first value can be set to "percentage" to use a percentage of the image size instead. + + (1024, 1024, 0, 0) would apply conditioning to the top-left 1024x1024 pixels. + + ("percentage", 0.5, 0.5, 0, 0) would apply conditioning to the top-left 50% of the image.''' # TODO: verify its actually top-left + strength: NotRequired[float] + '''Strength of conditioning. Default strength is 1.0.''' + mask: NotRequired[torch.Tensor] + '''Mask to apply conditioning to.''' + mask_strength: NotRequired[float] + '''Strength of conditioning mask. Default strength is 1.0.''' + set_area_to_bounds: NotRequired[bool] + '''Whether conditioning mask should determine bounds of area - if set to false, latents are sampled at full resolution and result is applied in mask.''' + concat_latent_image: NotRequired[torch.Tensor] + '''Used for inpainting and specific models.''' + concat_mask: NotRequired[torch.Tensor] + '''Used for inpainting and specific models.''' + concat_image: NotRequired[torch.Tensor] + '''Used by SD_4XUpscale_Conditioning.''' + noise_augmentation: NotRequired[float] + '''Used by SD_4XUpscale_Conditioning.''' + hooks: NotRequired[HookGroup] + '''Applies hooks to conditioning.''' + default: NotRequired[bool] + '''Whether to this conditioning is 'default'; default conditioning gets applied to any areas of the image that have no masks/areas applied, assuming at least one area/mask is present during sampling.''' + start_percent: NotRequired[float] + '''Determines relative step to begin applying conditioning, expressed as a float between 0.0 and 1.0.''' + end_percent: NotRequired[float] + '''Determines relative step to end applying conditioning, expressed as a float between 0.0 and 1.0.''' + clip_start_percent: NotRequired[float] + '''Internal variable for conditioning scheduling - start of application, expressed as a float between 0.0 and 1.0.''' + clip_end_percent: NotRequired[float] + '''Internal variable for conditioning scheduling - end of application, expressed as a float between 0.0 and 1.0.''' + attention_mask: NotRequired[torch.Tensor] + '''Masks text conditioning; used by StyleModel among others.''' + attention_mask_img_shape: NotRequired[tuple[int, ...]] + '''Masks text conditioning; used by StyleModel among others.''' + unclip_conditioning: NotRequired[list[dict]] + '''Used by unCLIP.''' + conditioning_lyrics: NotRequired[torch.Tensor] + '''Used by AceT5Model.''' + seconds_start: NotRequired[float] + '''Used by StableAudio.''' + seconds_total: NotRequired[float] + '''Used by StableAudio.''' + lyrics_strength: NotRequired[float] + '''Used by AceStepAudio.''' + width: NotRequired[int] + '''Used by certain models (e.g. CLIPTextEncodeSDXL/Refiner, PixArtAlpha).''' + height: NotRequired[int] + '''Used by certain models (e.g. CLIPTextEncodeSDXL/Refiner, PixArtAlpha).''' + aesthetic_score: NotRequired[float] + '''Used by CLIPTextEncodeSDXL/Refiner.''' + crop_w: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + crop_h: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + target_width: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + target_height: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + reference_latents: NotRequired[list[torch.Tensor]] + '''Used by ReferenceLatent.''' + guidance: NotRequired[float] + '''Used by Flux-like models with guidance embed.''' + guiding_frame_index: NotRequired[int] + '''Used by Hunyuan ImageToVideo.''' + ref_latent: NotRequired[torch.Tensor] + '''Used by Hunyuan ImageToVideo.''' + keyframe_idxs: NotRequired[list[int]] + '''Used by LTXV.''' + frame_rate: NotRequired[float] + '''Used by LTXV.''' + stable_cascade_prior: NotRequired[torch.Tensor] + '''Used by StableCascade.''' + elevation: NotRequired[list[float]] + '''Used by SV3D.''' + azimuth: NotRequired[list[float]] + '''Used by SV3D.''' + motion_bucket_id: NotRequired[int] + '''Used by SVD-like models.''' + fps: NotRequired[int] + '''Used by SVD-like models.''' + augmentation_level: NotRequired[float] + '''Used by SVD-like models.''' + clip_vision_output: NotRequired[ClipVisionOutput_] + '''Used by WAN-like models.''' + vace_frames: NotRequired[torch.Tensor] + '''Used by WAN VACE.''' + vace_mask: NotRequired[torch.Tensor] + '''Used by WAN VACE.''' + vace_strength: NotRequired[float] + '''Used by WAN VACE.''' + camera_conditions: NotRequired[Any] # TODO: assign proper type once defined + '''Used by WAN Camera.''' + time_dim_concat: NotRequired[torch.Tensor] + '''Used by WAN Phantom Subject.''' + time_dim_replace: NotRequired[torch.Tensor] + '''Used by Kandinsky5 I2V.''' + + CondList = list[tuple[torch.Tensor, PooledDict]] + Type = CondList + +@comfytype(io_type="SAMPLER") +class Sampler(ComfyTypeIO): + if TYPE_CHECKING: + Type = Sampler + +@comfytype(io_type="SIGMAS") +class Sigmas(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="NOISE") +class Noise(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="GUIDER") +class Guider(ComfyTypeIO): + if TYPE_CHECKING: + Type = CFGGuider + +@comfytype(io_type="CLIP") +class Clip(ComfyTypeIO): + if TYPE_CHECKING: + Type = CLIP + +@comfytype(io_type="CONTROL_NET") +class ControlNet(ComfyTypeIO): + if TYPE_CHECKING: + Type = ControlNet + +@comfytype(io_type="VAE") +class Vae(ComfyTypeIO): + if TYPE_CHECKING: + Type = VAE + +@comfytype(io_type="MODEL") +class Model(ComfyTypeIO): + if TYPE_CHECKING: + Type = ModelPatcher + +@comfytype(io_type="CLIP_VISION") +class ClipVision(ComfyTypeIO): + if TYPE_CHECKING: + Type = ClipVisionModel + +@comfytype(io_type="CLIP_VISION_OUTPUT") +class ClipVisionOutput(ComfyTypeIO): + if TYPE_CHECKING: + Type = ClipVisionOutput_ + +@comfytype(io_type="STYLE_MODEL") +class StyleModel(ComfyTypeIO): + if TYPE_CHECKING: + Type = StyleModel_ + +@comfytype(io_type="GLIGEN") +class Gligen(ComfyTypeIO): + '''ModelPatcher that wraps around a 'Gligen' model.''' + if TYPE_CHECKING: + Type = ModelPatcher + +@comfytype(io_type="UPSCALE_MODEL") +class UpscaleModel(ComfyTypeIO): + if TYPE_CHECKING: + Type = ImageModelDescriptor + +@comfytype(io_type="LATENT_UPSCALE_MODEL") +class LatentUpscaleModel(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO") +class Audio(ComfyTypeIO): + class AudioDict(TypedDict): + waveform: torch.Tensor + sampler_rate: int + Type = AudioDict + +@comfytype(io_type="VIDEO") +class Video(ComfyTypeIO): + if TYPE_CHECKING: + Type = VideoInput + +@comfytype(io_type="SVG") +class SVG(ComfyTypeIO): + Type = _SVG + +@comfytype(io_type="LORA_MODEL") +class LoraModel(ComfyTypeIO): + Type = dict[str, torch.Tensor] + +@comfytype(io_type="LOSS_MAP") +class LossMap(ComfyTypeIO): + class LossMapDict(TypedDict): + loss: list[torch.Tensor] + Type = LossMapDict + +@comfytype(io_type="VOXEL") +class Voxel(ComfyTypeIO): + Type = VOXEL + +@comfytype(io_type="MESH") +class Mesh(ComfyTypeIO): + Type = MESH + + +@comfytype(io_type="FILE_3D") +class File3DAny(ComfyTypeIO): + """General 3D file type - accepts any supported 3D format.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_GLB") +class File3DGLB(ComfyTypeIO): + """GLB format 3D file - binary glTF, best for web and cross-platform.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_GLTF") +class File3DGLTF(ComfyTypeIO): + """GLTF format 3D file - JSON-based glTF with external resources.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_FBX") +class File3DFBX(ComfyTypeIO): + """FBX format 3D file - best for game engines and animation.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_OBJ") +class File3DOBJ(ComfyTypeIO): + """OBJ format 3D file - simple geometry format.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_STL") +class File3DSTL(ComfyTypeIO): + """STL format 3D file - best for 3D printing.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_USDZ") +class File3DUSDZ(ComfyTypeIO): + """USDZ format 3D file - Apple AR format.""" + Type = File3D + + +@comfytype(io_type="HOOKS") +class Hooks(ComfyTypeIO): + if TYPE_CHECKING: + Type = HookGroup + +@comfytype(io_type="HOOK_KEYFRAMES") +class HookKeyframes(ComfyTypeIO): + if TYPE_CHECKING: + Type = HookKeyframeGroup + +@comfytype(io_type="TIMESTEPS_RANGE") +class TimestepsRange(ComfyTypeIO): + '''Range defined by start and endpoint, between 0.0 and 1.0.''' + Type = tuple[int, int] + +@comfytype(io_type="LATENT_OPERATION") +class LatentOperation(ComfyTypeIO): + Type = Callable[[torch.Tensor], torch.Tensor] + +@comfytype(io_type="FLOW_CONTROL") +class FlowControl(ComfyTypeIO): + # NOTE: only used in testing_nodes right now + Type = tuple[str, Any] + +@comfytype(io_type="ACCUMULATION") +class Accumulation(ComfyTypeIO): + # NOTE: only used in testing_nodes right now + class AccumulationDict(TypedDict): + accum: list[Any] + Type = AccumulationDict + + +@comfytype(io_type="LOAD3D_CAMERA") +class Load3DCamera(ComfyTypeIO): + class CameraInfo(TypedDict): + position: dict[str, float | int] + target: dict[str, float | int] + zoom: int + cameraType: str + + Type = CameraInfo + + +@comfytype(io_type="LOAD_3D") +class Load3D(ComfyTypeIO): + """3D models are stored as a dictionary.""" + class Model3DDict(TypedDict): + image: str + mask: str + normal: str + camera_info: Load3DCamera.CameraInfo + recording: NotRequired[str] + + Type = Model3DDict + + +@comfytype(io_type="LOAD_3D_ANIMATION") +class Load3DAnimation(Load3D): + ... + + +@comfytype(io_type="PHOTOMAKER") +class Photomaker(ComfyTypeIO): + Type = Any + + +@comfytype(io_type="POINT") +class Point(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="FACE_ANALYSIS") +class FaceAnalysis(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="BBOX") +class BBOX(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="SEGS") +class SEGS(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="*") +class AnyType(ComfyTypeIO): + Type = Any + +@comfytype(io_type="MODEL_PATCH") +class ModelPatch(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO_ENCODER") +class AudioEncoder(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO_ENCODER_OUTPUT") +class AudioEncoderOutput(ComfyTypeIO): + Type = Any + +@comfytype(io_type="TRACKS") +class Tracks(ComfyTypeIO): + class TrackDict(TypedDict): + track_path: torch.Tensor + track_visibility: torch.Tensor + Type = TrackDict + +@comfytype(io_type="COMFY_MULTITYPED_V3") +class MultiType: + Type = Any + class Input(Input): + ''' + Input that permits more than one input type; if `id` is an instance of `ComfyType.Input`, then that input will be used to create a widget (if applicable) with overridden values. + ''' + def __init__(self, id: str | Input, types: list[type[_ComfyType] | _ComfyType], display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + # if id is an Input, then use that Input with overridden values + self.input_override = None + if isinstance(id, Input): + self.input_override = copy.copy(id) + optional = id.optional if id.optional is True else optional + tooltip = id.tooltip if id.tooltip is not None else tooltip + display_name = id.display_name if id.display_name is not None else display_name + lazy = id.lazy if id.lazy is not None else lazy + id = id.id + # if is a widget input, make sure widget_type is set appropriately + if isinstance(self.input_override, WidgetInput): + self.input_override.widget_type = self.input_override.get_io_type() + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self._io_types = types + + @property + def io_types(self) -> list[type[Input]]: + ''' + Returns list of Input class types permitted. + ''' + io_types = [] + for x in self._io_types: + if not is_class(x): + io_types.append(type(x)) + else: + io_types.append(x) + return io_types + + def get_io_type(self): + # ensure types are unique and order is preserved + str_types = [x.io_type for x in self.io_types] + if self.input_override is not None: + str_types.insert(0, self.input_override.get_io_type()) + return ",".join(list(dict.fromkeys(str_types))) + + def as_dict(self): + if self.input_override is not None: + return self.input_override.as_dict() | super().as_dict() + else: + return super().as_dict() + +@comfytype(io_type="COMFY_MATCHTYPE_V3") +class MatchType(ComfyTypeIO): + class Template: + def __init__(self, template_id: str, allowed_types: _ComfyType | list[_ComfyType] = AnyType): + self.template_id = template_id + # account for syntactic sugar + if not isinstance(allowed_types, Iterable): + allowed_types = [allowed_types] + for t in allowed_types: + if not isinstance(t, type): + if not isinstance(t, _ComfyType): + raise ValueError(f"Allowed types must be a ComfyType or a list of ComfyTypes, got {t.__class__.__name__}") + else: + if not issubclass(t, _ComfyType): + raise ValueError(f"Allowed types must be a ComfyType or a list of ComfyTypes, got {t.__name__}") + self.allowed_types = allowed_types + + def as_dict(self): + return { + "template_id": self.template_id, + "allowed_types": ",".join([t.io_type for t in self.allowed_types]), + } + + class Input(Input): + def __init__(self, id: str, template: MatchType.Template, + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + + class Output(Output): + def __init__(self, template: MatchType.Template, id: str=None, display_name: str=None, tooltip: str=None, + is_output_list=False): + if not id and not display_name: + display_name = "MATCHTYPE" + super().__init__(id, display_name, tooltip, is_output_list) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + +class DynamicInput(Input, ABC): + ''' + Abstract class for dynamic input registration. + ''' + pass + + +class DynamicOutput(Output, ABC): + ''' + Abstract class for dynamic output registration. + ''' + pass + + +def handle_prefix(prefix_list: list[str] | None, id: str | None = None) -> list[str]: + if prefix_list is None: + prefix_list = [] + if id is not None: + prefix_list = prefix_list + [id] + return prefix_list + +def finalize_prefix(prefix_list: list[str] | None, id: str | None = None) -> str: + assert not (prefix_list is None and id is None) + if prefix_list is None: + return id + elif id is not None: + prefix_list = prefix_list + [id] + return ".".join(prefix_list) + +@comfytype(io_type="COMFY_AUTOGROW_V3") +class Autogrow(ComfyTypeI): + Type = dict[str, Any] + _MaxNames = 100 # NOTE: max 100 names for sanity + + class _AutogrowTemplate: + def __init__(self, input: Input): + # dynamic inputs are not allowed as the template input + assert(not isinstance(input, DynamicInput)) + self.input = copy.copy(input) + if isinstance(self.input, WidgetInput): + self.input.force_input = True + self.names: list[str] = [] + self.cached_inputs = {} + + def _create_input(self, input: Input, name: str): + new_input = copy.copy(self.input) + new_input.id = name + return new_input + + def _create_cached_inputs(self): + for name in self.names: + self.cached_inputs[name] = self._create_input(self.input, name) + + def get_all(self) -> list[Input]: + return list(self.cached_inputs.values()) + + def as_dict(self): + return prune_dict({ + "input": create_input_dict_v1([self.input]), + }) + + def validate(self): + self.input.validate() + + class TemplatePrefix(_AutogrowTemplate): + def __init__(self, input: Input, prefix: str, min: int=1, max: int=10): + super().__init__(input) + self.prefix = prefix + assert(min >= 0) + assert(max >= 1) + assert(max <= Autogrow._MaxNames) + self.min = min + self.max = max + self.names = [f"{self.prefix}{i}" for i in range(self.max)] + self._create_cached_inputs() + + def as_dict(self): + return super().as_dict() | prune_dict({ + "prefix": self.prefix, + "min": self.min, + "max": self.max, + }) + + class TemplateNames(_AutogrowTemplate): + def __init__(self, input: Input, names: list[str], min: int=1): + super().__init__(input) + self.names = names[:Autogrow._MaxNames] + assert(min >= 0) + self.min = min + self._create_cached_inputs() + + def as_dict(self): + return super().as_dict() | prune_dict({ + "names": self.names, + "min": self.min, + }) + + class Input(DynamicInput): + def __init__(self, id: str, template: Autogrow.TemplatePrefix | Autogrow.TemplateNames, + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + + def get_all(self) -> list[Input]: + return [self] + self.template.get_all() + + def validate(self): + self.template.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + # NOTE: purposely do not include self in out_dict; instead use only the template inputs + # need to figure out names based on template type + is_names = ("names" in value[1]["template"]) + is_prefix = ("prefix" in value[1]["template"]) + input = value[1]["template"]["input"] + if is_names: + min = value[1]["template"]["min"] + names = value[1]["template"]["names"] + max = len(names) + elif is_prefix: + prefix = value[1]["template"]["prefix"] + min = value[1]["template"]["min"] + max = value[1]["template"]["max"] + names = [f"{prefix}{i}" for i in range(max)] + # need to create a new input based on the contents of input + template_input = None + template_required = True + for _input_type, dict_input in input.items(): + # for now, get just the first value from dict_input; if not required, min can be ignored + if len(dict_input) == 0: + continue + template_input = list(dict_input.values())[0] + template_required = _input_type == "required" + break + if template_input is None: + raise Exception("template_input could not be determined from required or optional; this should never happen.") + new_dict = {} + new_dict_added_to = False + # first, add possible inputs into out_dict + for i, name in enumerate(names): + expected_id = finalize_prefix(curr_prefix, name) + # required + if i < min and template_required: + out_dict["required"][expected_id] = template_input + type_dict = new_dict.setdefault("required", {}) + # optional + else: + out_dict["optional"][expected_id] = template_input + type_dict = new_dict.setdefault("optional", {}) + if expected_id in live_inputs: + # NOTE: prefix gets added in parse_class_inputs + type_dict[name] = template_input + new_dict_added_to = True + # account for the edge case that all inputs are optional and no values are received + if not new_dict_added_to: + finalized_prefix = finalize_prefix(curr_prefix) + out_dict["dynamic_paths"][finalized_prefix] = finalized_prefix + out_dict["dynamic_paths_default_value"][finalized_prefix] = DynamicPathsDefaultValue.EMPTY_DICT + parse_class_inputs(out_dict, live_inputs, new_dict, curr_prefix) + +@comfytype(io_type="COMFY_DYNAMICCOMBO_V3") +class DynamicCombo(ComfyTypeI): + Type = dict[str, Any] + + class Option: + def __init__(self, key: str, inputs: list[Input]): + self.key = key + self.inputs = inputs + + def as_dict(self): + return { + "key": self.key, + "inputs": create_input_dict_v1(self.inputs), + } + + class Input(DynamicInput): + def __init__(self, id: str, options: list[DynamicCombo.Option], + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict) + self.options = options + + def get_all(self) -> list[Input]: + return [self] + [input for option in self.options for input in option.inputs] + + def as_dict(self): + return super().as_dict() | prune_dict({ + "options": [o.as_dict() for o in self.options], + }) + + def validate(self): + # make sure all nested inputs are validated + for option in self.options: + for input in option.inputs: + input.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + finalized_id = finalize_prefix(curr_prefix) + if finalized_id in live_inputs: + key = live_inputs[finalized_id] + selected_option = None + # get options from dict + options: list[dict[str, str | dict[str, Any]]] = value[1]["options"] + for option in options: + if option["key"] == key: + selected_option = option + break + if selected_option is not None: + parse_class_inputs(out_dict, live_inputs, selected_option["inputs"], curr_prefix) + # add self to inputs + out_dict[input_type][finalized_id] = value + out_dict["dynamic_paths"][finalized_id] = finalize_prefix(curr_prefix, curr_prefix[-1]) + +@comfytype(io_type="COMFY_DYNAMICSLOT_V3") +class DynamicSlot(ComfyTypeI): + Type = dict[str, Any] + + class Input(DynamicInput): + def __init__(self, slot: Input, inputs: list[Input], + display_name: str=None, tooltip: str=None, lazy: bool=None, extra_dict=None): + assert(not isinstance(slot, DynamicInput)) + self.slot = copy.copy(slot) + self.slot.display_name = slot.display_name if slot.display_name is not None else display_name + optional = True + self.slot.tooltip = slot.tooltip if slot.tooltip is not None else tooltip + self.slot.lazy = slot.lazy if slot.lazy is not None else lazy + self.slot.extra_dict = slot.extra_dict if slot.extra_dict is not None else extra_dict + super().__init__(slot.id, self.slot.display_name, optional, self.slot.tooltip, self.slot.lazy, self.slot.extra_dict) + self.inputs = inputs + self.force_input = None + # force widget inputs to have no widgets, otherwise this would be awkward + if isinstance(self.slot, WidgetInput): + self.force_input = True + self.slot.force_input = True + + def get_all(self) -> list[Input]: + return [self.slot] + self.inputs + + def as_dict(self): + return super().as_dict() | prune_dict({ + "slotType": str(self.slot.get_io_type()), + "inputs": create_input_dict_v1(self.inputs), + "forceInput": self.force_input, + }) + + def validate(self): + self.slot.validate() + for input in self.inputs: + input.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + finalized_id = finalize_prefix(curr_prefix) + if finalized_id in live_inputs: + inputs = value[1]["inputs"] + parse_class_inputs(out_dict, live_inputs, inputs, curr_prefix) + # add self to inputs + out_dict[input_type][finalized_id] = value + out_dict["dynamic_paths"][finalized_id] = finalize_prefix(curr_prefix, curr_prefix[-1]) + +@comfytype(io_type="IMAGECOMPARE") +class ImageCompare(ComfyTypeI): + Type = dict + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, None, socketless, None, None, None, None, advanced) + + def as_dict(self): + return super().as_dict() + + +@comfytype(io_type="COLOR") +class Color(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, advanced: bool=None, default: str="#ffffff"): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + self.default: str + + def as_dict(self): + return super().as_dict() + +@comfytype(io_type="BOUNDING_BOX") +class BoundingBox(ComfyTypeIO): + class BoundingBoxDict(TypedDict): + x: int + y: int + width: int + height: int + Type = BoundingBoxDict + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: dict=None, component: str=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless) + self.component = component + if default is None: + self.default = {"x": 0, "y": 0, "width": 512, "height": 512} + + def as_dict(self): + d = super().as_dict() + if self.component: + d["component"] = self.component + return d + + +DYNAMIC_INPUT_LOOKUP: dict[str, Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]] = {} +def register_dynamic_input_func(io_type: str, func: Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]): + DYNAMIC_INPUT_LOOKUP[io_type] = func + +def get_dynamic_input_func(io_type: str) -> Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]: + return DYNAMIC_INPUT_LOOKUP[io_type] + +def setup_dynamic_input_funcs(): + # Autogrow.Input + register_dynamic_input_func(Autogrow.io_type, Autogrow._expand_schema_for_dynamic) + # DynamicCombo.Input + register_dynamic_input_func(DynamicCombo.io_type, DynamicCombo._expand_schema_for_dynamic) + # DynamicSlot.Input + register_dynamic_input_func(DynamicSlot.io_type, DynamicSlot._expand_schema_for_dynamic) + +if len(DYNAMIC_INPUT_LOOKUP) == 0: + setup_dynamic_input_funcs() + +class V3Data(TypedDict): + hidden_inputs: dict[str, Any] + 'Dictionary where the keys are the hidden input ids and the values are the values of the hidden inputs.' + dynamic_paths: dict[str, Any] + 'Dictionary where the keys are the input ids and the values dictate how to turn the inputs into a nested dictionary.' + dynamic_paths_default_value: dict[str, Any] + 'Dictionary where the keys are the input ids and the values are a string from DynamicPathsDefaultValue for the inputs if value is None.' + create_dynamic_tuple: bool + 'When True, the value of the dynamic input will be in the format (value, path_key).' + +class HiddenHolder: + def __init__(self, unique_id: str, prompt: Any, + extra_pnginfo: Any, dynprompt: Any, + auth_token_comfy_org: str, api_key_comfy_org: str, **kwargs): + self.unique_id = unique_id + """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages).""" + self.prompt = prompt + """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description.""" + self.extra_pnginfo = extra_pnginfo + """EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node).""" + self.dynprompt = dynprompt + """DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion.""" + self.auth_token_comfy_org = auth_token_comfy_org + """AUTH_TOKEN_COMFY_ORG is a token acquired from signing into a ComfyOrg account on frontend.""" + self.api_key_comfy_org = api_key_comfy_org + """API_KEY_COMFY_ORG is an API Key generated by ComfyOrg that allows skipping signing into a ComfyOrg account on frontend.""" + + def __getattr__(self, key: str): + '''If hidden variable not found, return None.''' + return None + + @classmethod + def from_dict(cls, d: dict | None): + if d is None: + d = {} + return cls( + unique_id=d.get(Hidden.unique_id, None), + prompt=d.get(Hidden.prompt, None), + extra_pnginfo=d.get(Hidden.extra_pnginfo, None), + dynprompt=d.get(Hidden.dynprompt, None), + auth_token_comfy_org=d.get(Hidden.auth_token_comfy_org, None), + api_key_comfy_org=d.get(Hidden.api_key_comfy_org, None), + ) + + @classmethod + def from_v3_data(cls, v3_data: V3Data | None) -> HiddenHolder: + return cls.from_dict(v3_data["hidden_inputs"] if v3_data else None) + +class Hidden(str, Enum): + ''' + Enumerator for requesting hidden variables in nodes. + ''' + unique_id = "UNIQUE_ID" + """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages).""" + prompt = "PROMPT" + """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description.""" + extra_pnginfo = "EXTRA_PNGINFO" + """EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node).""" + dynprompt = "DYNPROMPT" + """DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion.""" + auth_token_comfy_org = "AUTH_TOKEN_COMFY_ORG" + """AUTH_TOKEN_COMFY_ORG is a token acquired from signing into a ComfyOrg account on frontend.""" + api_key_comfy_org = "API_KEY_COMFY_ORG" + """API_KEY_COMFY_ORG is an API Key generated by ComfyOrg that allows skipping signing into a ComfyOrg account on frontend.""" + + +@dataclass +class NodeInfoV1: + input: dict=None + input_order: dict[str, list[str]]=None + is_input_list: bool=None + output: list[str]=None + output_is_list: list[bool]=None + output_name: list[str]=None + output_tooltips: list[str]=None + output_matchtypes: list[str]=None + name: str=None + display_name: str=None + description: str=None + python_module: Any=None + category: str=None + output_node: bool=None + deprecated: bool=None + experimental: bool=None + dev_only: bool=None + api_node: bool=None + price_badge: dict | None = None + search_aliases: list[str]=None + essentials_category: str=None + + +@dataclass +class PriceBadgeDepends: + widgets: list[str] = field(default_factory=list) + inputs: list[str] = field(default_factory=list) + input_groups: list[str] = field(default_factory=list) + + def validate(self) -> None: + if not isinstance(self.widgets, list) or any(not isinstance(x, str) for x in self.widgets): + raise ValueError("PriceBadgeDepends.widgets must be a list[str].") + if not isinstance(self.inputs, list) or any(not isinstance(x, str) for x in self.inputs): + raise ValueError("PriceBadgeDepends.inputs must be a list[str].") + if not isinstance(self.input_groups, list) or any(not isinstance(x, str) for x in self.input_groups): + raise ValueError("PriceBadgeDepends.input_groups must be a list[str].") + + def as_dict(self, schema_inputs: list["Input"]) -> dict[str, Any]: + # Build lookup: widget_id -> io_type + input_types: dict[str, str] = {} + for inp in schema_inputs: + all_inputs = inp.get_all() + input_types[inp.id] = inp.get_io_type() # First input is always the parent itself + for nested_inp in all_inputs[1:]: + # For DynamicCombo/DynamicSlot, nested inputs are prefixed with parent ID + # to match frontend naming convention (e.g., "should_texture.enable_pbr") + prefixed_id = f"{inp.id}.{nested_inp.id}" + input_types[prefixed_id] = nested_inp.get_io_type() + + # Enrich widgets with type information, raising error for unknown widgets + widgets_data: list[dict[str, str]] = [] + for w in self.widgets: + if w not in input_types: + raise ValueError( + f"PriceBadge depends_on.widgets references unknown widget '{w}'. " + f"Available widgets: {list(input_types.keys())}" + ) + widgets_data.append({"name": w, "type": input_types[w]}) + + return { + "widgets": widgets_data, + "inputs": self.inputs, + "input_groups": self.input_groups, + } + + +@dataclass +class PriceBadge: + expr: str + depends_on: PriceBadgeDepends = field(default_factory=PriceBadgeDepends) + engine: str = field(default="jsonata") + + def validate(self) -> None: + if self.engine != "jsonata": + raise ValueError(f"Unsupported PriceBadge.engine '{self.engine}'. Only 'jsonata' is supported.") + if not isinstance(self.expr, str) or not self.expr.strip(): + raise ValueError("PriceBadge.expr must be a non-empty string.") + self.depends_on.validate() + + def as_dict(self, schema_inputs: list["Input"]) -> dict[str, Any]: + return { + "engine": self.engine, + "depends_on": self.depends_on.as_dict(schema_inputs), + "expr": self.expr, + } + + +@dataclass +class Schema: + """Definition of V3 node properties.""" + + node_id: str + """ID of node - should be globally unique. If this is a custom node, add a prefix or postfix to avoid name clashes.""" + display_name: str = None + """Display name of node.""" + category: str = "sd" + """The category of the node, as per the "Add Node" menu.""" + inputs: list[Input] = field(default_factory=list) + outputs: list[Output] = field(default_factory=list) + hidden: list[Hidden] = field(default_factory=list) + description: str="" + """Node description, shown as a tooltip when hovering over the node.""" + search_aliases: list[str] = field(default_factory=list) + """Alternative names for search. Useful for synonyms, abbreviations, or old names after renaming.""" + is_input_list: bool = False + """A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes. + + All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``. + + From the docs: + + A node can also override the default input behaviour and receive the whole list in a single call. This is done by setting a class attribute `INPUT_IS_LIST` to ``True``. + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing + """ + is_output_node: bool=False + """Flags this node as an output node, causing any inputs it requires to be executed. + + If a node is not connected to any output nodes, that node will not be executed. Usage:: + + From the docs: + + By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is. + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#output-node + """ + is_deprecated: bool=False + """Flags a node as deprecated, indicating to users that they should find alternatives to this node.""" + is_experimental: bool=False + """Flags a node as experimental, informing users that it may change or not work as expected.""" + is_dev_only: bool=False + """Flags a node as dev-only, hiding it from search/menus unless dev mode is enabled.""" + is_api_node: bool=False + """Flags a node as an API node. See: https://docs.comfy.org/tutorials/api-nodes/overview.""" + price_badge: PriceBadge | None = None + """Optional client-evaluated pricing badge declaration for this node.""" + not_idempotent: bool=False + """Flags a node as not idempotent; when True, the node will run and not reuse the cached outputs when identical inputs are provided on a different node in the graph.""" + enable_expand: bool=False + """Flags a node as expandable, allowing NodeOutput to include 'expand' property.""" + accept_all_inputs: bool=False + """When True, all inputs from the prompt will be passed to the node as kwargs, even if not defined in the schema.""" + essentials_category: str | None = None + """Optional category for the Essentials tab. Path-based like category field (e.g., 'Basic', 'Image Tools/Editing').""" + + def validate(self): + '''Validate the schema: + - verify ids on inputs and outputs are unique - both internally and in relation to each other + ''' + nested_inputs: list[Input] = [] + for input in self.inputs: + if not isinstance(input, DynamicInput): + nested_inputs.extend(input.get_all()) + input_ids = [i.id for i in nested_inputs] + output_ids = [o.id for o in self.outputs] + input_set = set(input_ids) + output_set = set(output_ids) + issues: list[str] = [] + # verify ids are unique per list + if len(input_set) != len(input_ids): + issues.append(f"Input ids must be unique, but {[item for item, count in Counter(input_ids).items() if count > 1]} are not.") + if len(output_set) != len(output_ids): + issues.append(f"Output ids must be unique, but {[item for item, count in Counter(output_ids).items() if count > 1]} are not.") + if len(issues) > 0: + raise ValueError("\n".join(issues)) + # validate inputs and outputs + for input in self.inputs: + input.validate() + for output in self.outputs: + output.validate() + if self.price_badge is not None: + self.price_badge.validate() + + def finalize(self): + """Add hidden based on selected schema options, and give outputs without ids default ids.""" + # ensure inputs, outputs, and hidden are lists + if self.inputs is None: + self.inputs = [] + if self.outputs is None: + self.outputs = [] + if self.hidden is None: + self.hidden = [] + # if is an api_node, will need key-related hidden + if self.is_api_node: + if Hidden.auth_token_comfy_org not in self.hidden: + self.hidden.append(Hidden.auth_token_comfy_org) + if Hidden.api_key_comfy_org not in self.hidden: + self.hidden.append(Hidden.api_key_comfy_org) + # if is an output_node, will need prompt and extra_pnginfo + if self.is_output_node: + if Hidden.prompt not in self.hidden: + self.hidden.append(Hidden.prompt) + if Hidden.extra_pnginfo not in self.hidden: + self.hidden.append(Hidden.extra_pnginfo) + # give outputs without ids default ids + for i, output in enumerate(self.outputs): + if output.id is None: + output.id = f"_{i}_{output.io_type}_" + + def get_v1_info(self, cls) -> NodeInfoV1: + # get V1 inputs + input = create_input_dict_v1(self.inputs) + if self.hidden: + for hidden in self.hidden: + input.setdefault("hidden", {})[hidden.name] = (hidden.value,) + # create separate lists from output fields + output = [] + output_is_list = [] + output_name = [] + output_tooltips = [] + output_matchtypes = [] + any_matchtypes = False + if self.outputs: + for o in self.outputs: + output.append(o.io_type) + output_is_list.append(o.is_output_list) + output_name.append(o.display_name if o.display_name else o.io_type) + output_tooltips.append(o.tooltip if o.tooltip else None) + # special handling for MatchType + if isinstance(o, MatchType.Output): + output_matchtypes.append(o.template.template_id) + any_matchtypes = True + else: + output_matchtypes.append(None) + + # clear out lists that are all None + if not any_matchtypes: + output_matchtypes = None + + info = NodeInfoV1( + input=input, + input_order={key: list(value.keys()) for (key, value) in input.items()}, + is_input_list=self.is_input_list, + output=output, + output_is_list=output_is_list, + output_name=output_name, + output_tooltips=output_tooltips, + output_matchtypes=output_matchtypes, + name=self.node_id, + display_name=self.display_name, + category=self.category, + description=self.description, + output_node=self.is_output_node, + deprecated=self.is_deprecated, + experimental=self.is_experimental, + dev_only=self.is_dev_only, + api_node=self.is_api_node, + python_module=getattr(cls, "RELATIVE_PYTHON_MODULE", "nodes"), + price_badge=self.price_badge.as_dict(self.inputs) if self.price_badge is not None else None, + search_aliases=self.search_aliases if self.search_aliases else None, + essentials_category=self.essentials_category, + ) + return info + +def get_finalized_class_inputs(d: dict[str, Any], live_inputs: dict[str, Any], include_hidden=False) -> tuple[dict[str, Any], V3Data]: + out_dict = { + "required": {}, + "optional": {}, + "dynamic_paths": {}, + "dynamic_paths_default_value": {}, + } + d = d.copy() + # ignore hidden for parsing + hidden = d.pop("hidden", None) + parse_class_inputs(out_dict, live_inputs, d) + if hidden is not None and include_hidden: + out_dict["hidden"] = hidden + v3_data = {} + dynamic_paths = out_dict.pop("dynamic_paths", None) + if dynamic_paths is not None and len(dynamic_paths) > 0: + v3_data["dynamic_paths"] = dynamic_paths + # this list is used for autogrow, in the case all inputs are optional and no values are passed + dynamic_paths_default_value = out_dict.pop("dynamic_paths_default_value", None) + if dynamic_paths_default_value is not None and len(dynamic_paths_default_value) > 0: + v3_data["dynamic_paths_default_value"] = dynamic_paths_default_value + return out_dict, hidden, v3_data + +def parse_class_inputs(out_dict: dict[str, Any], live_inputs: dict[str, Any], curr_dict: dict[str, Any], curr_prefix: list[str] | None=None) -> None: + for input_type, inner_d in curr_dict.items(): + for id, value in inner_d.items(): + io_type = value[0] + if io_type in DYNAMIC_INPUT_LOOKUP: + # dynamic inputs need to be handled with lookup functions + dynamic_input_func = get_dynamic_input_func(io_type) + new_prefix = handle_prefix(curr_prefix, id) + dynamic_input_func(out_dict, live_inputs, value, input_type, new_prefix) + else: + # non-dynamic inputs get directly transferred + finalized_id = finalize_prefix(curr_prefix, id) + out_dict[input_type][finalized_id] = value + if curr_prefix: + out_dict["dynamic_paths"][finalized_id] = finalized_id + +def create_input_dict_v1(inputs: list[Input]) -> dict: + input = { + "required": {} + } + for i in inputs: + add_to_dict_v1(i, input) + return input + +def add_to_dict_v1(i: Input, d: dict): + key = "optional" if i.optional else "required" + as_dict = i.as_dict() + # for v1, we don't want to include the optional key + as_dict.pop("optional", None) + d.setdefault(key, {})[i.id] = (i.get_io_type(), as_dict) + +class DynamicPathsDefaultValue: + EMPTY_DICT = "empty_dict" + +def build_nested_inputs(values: dict[str, Any], v3_data: V3Data): + paths = v3_data.get("dynamic_paths", None) + default_value_dict = v3_data.get("dynamic_paths_default_value", {}) + if paths is None: + return values + values = values.copy() + + result = {} + + create_tuple = v3_data.get("create_dynamic_tuple", False) + + for key, path in paths.items(): + parts = path.split(".") + current = result + + for i, p in enumerate(parts): + is_last = (i == len(parts) - 1) + + if is_last: + value = values.pop(key, None) + if value is None: + # see if a default value was provided for this key + default_option = default_value_dict.get(key, None) + if default_option == DynamicPathsDefaultValue.EMPTY_DICT: + value = {} + if create_tuple: + value = (value, key) + current[p] = value + else: + current = current.setdefault(p, {}) + + values.update(result) + return values + + +class _ComfyNodeBaseInternal(_ComfyNodeInternal): + """Common base class for storing internal methods and properties; DO NOT USE for defining nodes.""" + + RELATIVE_PYTHON_MODULE = None + SCHEMA = None + + # filled in during execution + hidden: HiddenHolder = None + + @classmethod + @abstractmethod + def define_schema(cls) -> Schema: + """Override this function with one that returns a Schema instance.""" + raise NotImplementedError + + @classmethod + @abstractmethod + def execute(cls, **kwargs) -> NodeOutput: + """Override this function with one that performs node's actions.""" + raise NotImplementedError + + @classmethod + def validate_inputs(cls, **kwargs) -> bool | str: + """Optionally, define this function to validate inputs; equivalent to V1's VALIDATE_INPUTS. + + If the function returns a string, it will be used as the validation error message for the node. + """ + raise NotImplementedError + + @classmethod + def fingerprint_inputs(cls, **kwargs) -> Any: + """Optionally, define this function to fingerprint inputs; equivalent to V1's IS_CHANGED. + + If this function returns the same value as last run, the node will not be executed.""" + raise NotImplementedError + + @classmethod + def check_lazy_status(cls, **kwargs) -> list[str]: + """Optionally, define this function to return a list of input names that should be evaluated. + + This basic mixin impl. requires all inputs. + + :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \ + When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``. + + Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name). + Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params). + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status + """ + return [name for name in kwargs if kwargs[name] is None] + + def __init__(self): + self.__class__.VALIDATE_CLASS() + + @classmethod + def GET_BASE_CLASS(cls): + return _ComfyNodeBaseInternal + + @final + @classmethod + def VALIDATE_CLASS(cls): + if first_real_override(cls, "define_schema") is None: + raise Exception(f"No define_schema function was defined for node class {cls.__name__}.") + if first_real_override(cls, "execute") is None: + raise Exception(f"No execute function was defined for node class {cls.__name__}.") + + @classproperty + def FUNCTION(cls): # noqa + if inspect.iscoroutinefunction(cls.execute): + return "EXECUTE_NORMALIZED_ASYNC" + return "EXECUTE_NORMALIZED" + + @final + @classmethod + def EXECUTE_NORMALIZED(cls, *args, **kwargs) -> NodeOutput: + to_return = cls.execute(*args, **kwargs) + if to_return is None: + to_return = NodeOutput() + elif isinstance(to_return, NodeOutput): + pass + elif isinstance(to_return, tuple): + to_return = NodeOutput(*to_return) + elif isinstance(to_return, dict): + to_return = NodeOutput.from_dict(to_return) + elif isinstance(to_return, ExecutionBlocker): + to_return = NodeOutput(block_execution=to_return.message) + else: + raise Exception(f"Invalid return type from node: {type(to_return)}") + if to_return.expand is not None and not cls.SCHEMA.enable_expand: + raise Exception(f"Node {cls.__name__} is not expandable, but expand included in NodeOutput; developer should set enable_expand=True on node's Schema to allow this.") + return to_return + + @final + @classmethod + async def EXECUTE_NORMALIZED_ASYNC(cls, *args, **kwargs) -> NodeOutput: + to_return = await cls.execute(*args, **kwargs) + if to_return is None: + to_return = NodeOutput() + elif isinstance(to_return, NodeOutput): + pass + elif isinstance(to_return, tuple): + to_return = NodeOutput(*to_return) + elif isinstance(to_return, dict): + to_return = NodeOutput.from_dict(to_return) + elif isinstance(to_return, ExecutionBlocker): + to_return = NodeOutput(block_execution=to_return.message) + else: + raise Exception(f"Invalid return type from node: {type(to_return)}") + if to_return.expand is not None and not cls.SCHEMA.enable_expand: + raise Exception(f"Node {cls.__name__} is not expandable, but expand included in NodeOutput; developer should set enable_expand=True on node's Schema to allow this.") + return to_return + + @final + @classmethod + def PREPARE_CLASS_CLONE(cls, v3_data: V3Data | None) -> type[ComfyNode]: + """Creates clone of real node class to prevent monkey-patching.""" + c_type: type[ComfyNode] = cls if is_class(cls) else type(cls) + type_clone: type[ComfyNode] = shallow_clone_class(c_type) + # set hidden + type_clone.hidden = HiddenHolder.from_v3_data(v3_data) + return type_clone + ############################################# + # V1 Backwards Compatibility code + #-------------------------------------------- + @final + @classmethod + def GET_NODE_INFO_V1(cls) -> dict[str, Any]: + schema = cls.GET_SCHEMA() + info = schema.get_v1_info(cls) + return asdict(info) + + _DESCRIPTION = None + @final + @classproperty + def DESCRIPTION(cls): # noqa + if cls._DESCRIPTION is None: + cls.GET_SCHEMA() + return cls._DESCRIPTION + + _CATEGORY = None + @final + @classproperty + def CATEGORY(cls): # noqa + if cls._CATEGORY is None: + cls.GET_SCHEMA() + return cls._CATEGORY + + _EXPERIMENTAL = None + @final + @classproperty + def EXPERIMENTAL(cls): # noqa + if cls._EXPERIMENTAL is None: + cls.GET_SCHEMA() + return cls._EXPERIMENTAL + + _DEPRECATED = None + @final + @classproperty + def DEPRECATED(cls): # noqa + if cls._DEPRECATED is None: + cls.GET_SCHEMA() + return cls._DEPRECATED + + _DEV_ONLY = None + @final + @classproperty + def DEV_ONLY(cls): # noqa + if cls._DEV_ONLY is None: + cls.GET_SCHEMA() + return cls._DEV_ONLY + + _API_NODE = None + @final + @classproperty + def API_NODE(cls): # noqa + if cls._API_NODE is None: + cls.GET_SCHEMA() + return cls._API_NODE + + _OUTPUT_NODE = None + @final + @classproperty + def OUTPUT_NODE(cls): # noqa + if cls._OUTPUT_NODE is None: + cls.GET_SCHEMA() + return cls._OUTPUT_NODE + + _INPUT_IS_LIST = None + @final + @classproperty + def INPUT_IS_LIST(cls): # noqa + if cls._INPUT_IS_LIST is None: + cls.GET_SCHEMA() + return cls._INPUT_IS_LIST + _OUTPUT_IS_LIST = None + + @final + @classproperty + def OUTPUT_IS_LIST(cls): # noqa + if cls._OUTPUT_IS_LIST is None: + cls.GET_SCHEMA() + return cls._OUTPUT_IS_LIST + + _RETURN_TYPES = None + @final + @classproperty + def RETURN_TYPES(cls): # noqa + if cls._RETURN_TYPES is None: + cls.GET_SCHEMA() + return cls._RETURN_TYPES + + _RETURN_NAMES = None + @final + @classproperty + def RETURN_NAMES(cls): # noqa + if cls._RETURN_NAMES is None: + cls.GET_SCHEMA() + return cls._RETURN_NAMES + + _OUTPUT_TOOLTIPS = None + @final + @classproperty + def OUTPUT_TOOLTIPS(cls): # noqa + if cls._OUTPUT_TOOLTIPS is None: + cls.GET_SCHEMA() + return cls._OUTPUT_TOOLTIPS + + _NOT_IDEMPOTENT = None + @final + @classproperty + def NOT_IDEMPOTENT(cls): # noqa + if cls._NOT_IDEMPOTENT is None: + cls.GET_SCHEMA() + return cls._NOT_IDEMPOTENT + + _ACCEPT_ALL_INPUTS = None + @final + @classproperty + def ACCEPT_ALL_INPUTS(cls): # noqa + if cls._ACCEPT_ALL_INPUTS is None: + cls.GET_SCHEMA() + return cls._ACCEPT_ALL_INPUTS + + @final + @classmethod + def INPUT_TYPES(cls) -> dict[str, dict]: + schema = cls.FINALIZE_SCHEMA() + info = schema.get_v1_info(cls) + return info.input + + @final + @classmethod + def FINALIZE_SCHEMA(cls): + """Call define_schema and finalize it.""" + schema = cls.define_schema() + schema.finalize() + return schema + + @final + @classmethod + def GET_SCHEMA(cls) -> Schema: + """Validate node class, finalize schema, validate schema, and set expected class properties.""" + cls.VALIDATE_CLASS() + schema = cls.FINALIZE_SCHEMA() + schema.validate() + if cls._DESCRIPTION is None: + cls._DESCRIPTION = schema.description + if cls._CATEGORY is None: + cls._CATEGORY = schema.category + if cls._EXPERIMENTAL is None: + cls._EXPERIMENTAL = schema.is_experimental + if cls._DEPRECATED is None: + cls._DEPRECATED = schema.is_deprecated + if cls._DEV_ONLY is None: + cls._DEV_ONLY = schema.is_dev_only + if cls._API_NODE is None: + cls._API_NODE = schema.is_api_node + if cls._OUTPUT_NODE is None: + cls._OUTPUT_NODE = schema.is_output_node + if cls._INPUT_IS_LIST is None: + cls._INPUT_IS_LIST = schema.is_input_list + if cls._NOT_IDEMPOTENT is None: + cls._NOT_IDEMPOTENT = schema.not_idempotent + if cls._ACCEPT_ALL_INPUTS is None: + cls._ACCEPT_ALL_INPUTS = schema.accept_all_inputs + + if cls._RETURN_TYPES is None: + output = [] + output_name = [] + output_is_list = [] + output_tooltips = [] + if schema.outputs: + for o in schema.outputs: + output.append(o.io_type) + output_name.append(o.display_name if o.display_name else o.io_type) + output_is_list.append(o.is_output_list) + output_tooltips.append(o.tooltip if o.tooltip else None) + + cls._RETURN_TYPES = output + cls._RETURN_NAMES = output_name + cls._OUTPUT_IS_LIST = output_is_list + cls._OUTPUT_TOOLTIPS = output_tooltips + cls.SCHEMA = schema + return schema + #-------------------------------------------- + ############################################# + + +class ComfyNode(_ComfyNodeBaseInternal): + """Common base class for all V3 nodes.""" + + @classmethod + @abstractmethod + def define_schema(cls) -> Schema: + """Override this function with one that returns a Schema instance.""" + raise NotImplementedError + + @classmethod + @abstractmethod + def execute(cls, **kwargs) -> NodeOutput: + """Override this function with one that performs node's actions.""" + raise NotImplementedError + + @classmethod + def validate_inputs(cls, **kwargs) -> bool | str: + """Optionally, define this function to validate inputs; equivalent to V1's VALIDATE_INPUTS.""" + raise NotImplementedError + + @classmethod + def fingerprint_inputs(cls, **kwargs) -> Any: + """Optionally, define this function to fingerprint inputs; equivalent to V1's IS_CHANGED.""" + raise NotImplementedError + + @classmethod + def check_lazy_status(cls, **kwargs) -> list[str]: + """Optionally, define this function to return a list of input names that should be evaluated. + + This basic mixin impl. requires all inputs. + + :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \ + When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``. + + Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name). + Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params). + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status + """ + return [name for name in kwargs if kwargs[name] is None] + + @final + @classmethod + def GET_BASE_CLASS(cls): + """DO NOT override this class. Will break things in execution.py.""" + return ComfyNode + + +class NodeOutput(_NodeOutputInternal): + ''' + Standardized output of a node; can pass in any number of args and/or a UIOutput into 'ui' kwarg. + ''' + def __init__(self, *args: Any, ui: _UIOutput | dict=None, expand: dict=None, block_execution: str=None): + self.args = args + self.ui = ui + self.expand = expand + self.block_execution = block_execution + + @property + def result(self): + return self.args if len(self.args) > 0 else None + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> NodeOutput: + args = () + ui = None + expand = None + if "result" in data: + result = data["result"] + if isinstance(result, ExecutionBlocker): + return cls(block_execution=result.message) + args = result + if "ui" in data: + ui = data["ui"] + if "expand" in data: + expand = data["expand"] + return cls(*args, ui=ui, expand=expand) + + def __getitem__(self, index) -> Any: + return self.args[index] + +class _UIOutput(ABC): + def __init__(self): + pass + + @abstractmethod + def as_dict(self) -> dict: + ... + + +class InputMapOldId(TypedDict): + """Map an old node input to a new node input by ID.""" + new_id: str + old_id: str + +class InputMapSetValue(TypedDict): + """Set a specific value for a new node input.""" + new_id: str + set_value: Any + +InputMap = InputMapOldId | InputMapSetValue +""" +Input mapping for node replacement. Type is inferred by dictionary keys: +- {"new_id": str, "old_id": str} - maps old input to new input +- {"new_id": str, "set_value": Any} - sets a specific value for new input +""" + +class OutputMap(TypedDict): + """Map outputs of node replacement via indexes.""" + new_idx: int + old_idx: int + +class NodeReplace: + """ + Defines a possible node replacement, mapping inputs and outputs of the old node to the new node. + + Also supports assigning specific values to the input widgets of the new node. + + Args: + new_node_id: The class name of the new replacement node. + old_node_id: The class name of the deprecated node. + old_widget_ids: Ordered list of input IDs for widgets that may not have an input slot + connected. The workflow JSON stores widget values by their relative position index, + not by ID. This list maps those positional indexes to input IDs, enabling the + replacement system to correctly identify widget values during node migration. + input_mapping: List of input mappings from old node to new node. + output_mapping: List of output mappings from old node to new node. + """ + def __init__(self, + new_node_id: str, + old_node_id: str, + old_widget_ids: list[str] | None=None, + input_mapping: list[InputMap] | None=None, + output_mapping: list[OutputMap] | None=None, + ): + self.new_node_id = new_node_id + self.old_node_id = old_node_id + self.old_widget_ids = old_widget_ids + self.input_mapping = input_mapping + self.output_mapping = output_mapping + + def as_dict(self): + """Create serializable representation of the node replacement.""" + return { + "new_node_id": self.new_node_id, + "old_node_id": self.old_node_id, + "old_widget_ids": self.old_widget_ids, + "input_mapping": list(self.input_mapping) if self.input_mapping else None, + "output_mapping": list(self.output_mapping) if self.output_mapping else None, + } + + +__all__ = [ + "FolderType", + "UploadType", + "RemoteOptions", + "NumberDisplay", + "ControlAfterGenerate", + + "comfytype", + "Custom", + "Input", + "WidgetInput", + "Output", + "ComfyTypeI", + "ComfyTypeIO", + # Supported Types + "Boolean", + "Int", + "Float", + "String", + "Combo", + "MultiCombo", + "Image", + "WanCameraEmbedding", + "Webcam", + "Mask", + "Latent", + "Conditioning", + "Sampler", + "Sigmas", + "Noise", + "Guider", + "Clip", + "ControlNet", + "Vae", + "Model", + "ModelPatch", + "ClipVision", + "ClipVisionOutput", + "AudioEncoder", + "AudioEncoderOutput", + "StyleModel", + "Gligen", + "UpscaleModel", + "LatentUpscaleModel", + "Audio", + "Video", + "SVG", + "LoraModel", + "LossMap", + "Voxel", + "Mesh", + "File3DAny", + "File3DGLB", + "File3DGLTF", + "File3DFBX", + "File3DOBJ", + "File3DSTL", + "File3DUSDZ", + "Hooks", + "HookKeyframes", + "TimestepsRange", + "LatentOperation", + "FlowControl", + "Accumulation", + "Load3DCamera", + "Load3D", + "Load3DAnimation", + "Photomaker", + "Point", + "FaceAnalysis", + "BBOX", + "SEGS", + "AnyType", + "MultiType", + "Tracks", + "Color", + # Dynamic Types + "MatchType", + "DynamicCombo", + "Autogrow", + # Other classes + "HiddenHolder", + "Hidden", + "NodeInfoV1", + "Schema", + "ComfyNode", + "NodeOutput", + "add_to_dict_v1", + "V3Data", + "ImageCompare", + "PriceBadgeDepends", + "PriceBadge", + "BoundingBox", + "NodeReplace", +] diff --git a/docs/hel-892/sdpose-reference/core0150__comfy_extras__nodes_post_processing.py b/docs/hel-892/sdpose-reference/core0150__comfy_extras__nodes_post_processing.py new file mode 100644 index 00000000..c67245e7 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150__comfy_extras__nodes_post_processing.py @@ -0,0 +1,679 @@ +from typing_extensions import override +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +import math +from enum import Enum +from typing import TypedDict, Literal + +import comfy.utils +import comfy.model_management +from comfy_extras.nodes_latent import reshape_latent_to +import node_helpers +from comfy_api.latest import ComfyExtension, io +from nodes import MAX_RESOLUTION + +class Blend(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageBlend", + display_name="Image Blend", + category="image/postprocessing", + inputs=[ + io.Image.Input("image1"), + io.Image.Input("image2"), + io.Float.Input("blend_factor", default=0.5, min=0.0, max=1.0, step=0.01), + io.Combo.Input("blend_mode", options=["normal", "multiply", "screen", "overlay", "soft_light", "difference"]), + ], + outputs=[ + io.Image.Output(), + ], + ) + + @classmethod + def execute(cls, image1: torch.Tensor, image2: torch.Tensor, blend_factor: float, blend_mode: str) -> io.NodeOutput: + image1, image2 = node_helpers.image_alpha_fix(image1, image2) + image2 = image2.to(image1.device) + if image1.shape != image2.shape: + image2 = image2.permute(0, 3, 1, 2) + image2 = comfy.utils.common_upscale(image2, image1.shape[2], image1.shape[1], upscale_method='bicubic', crop='center') + image2 = image2.permute(0, 2, 3, 1) + + blended_image = cls.blend_mode(image1, image2, blend_mode) + blended_image = image1 * (1 - blend_factor) + blended_image * blend_factor + blended_image = torch.clamp(blended_image, 0, 1) + return io.NodeOutput(blended_image) + + @classmethod + def blend_mode(cls, img1, img2, mode): + if mode == "normal": + return img2 + elif mode == "multiply": + return img1 * img2 + elif mode == "screen": + return 1 - (1 - img1) * (1 - img2) + elif mode == "overlay": + return torch.where(img1 <= 0.5, 2 * img1 * img2, 1 - 2 * (1 - img1) * (1 - img2)) + elif mode == "soft_light": + return torch.where(img2 <= 0.5, img1 - (1 - 2 * img2) * img1 * (1 - img1), img1 + (2 * img2 - 1) * (cls.g(img1) - img1)) + elif mode == "difference": + return img1 - img2 + raise ValueError(f"Unsupported blend mode: {mode}") + + @classmethod + def g(cls, x): + return torch.where(x <= 0.25, ((16 * x - 12) * x + 4) * x, torch.sqrt(x)) + +def gaussian_kernel(kernel_size: int, sigma: float, device=None): + x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size, device=device), torch.linspace(-1, 1, kernel_size, device=device), indexing="ij") + d = torch.sqrt(x * x + y * y) + g = torch.exp(-(d * d) / (2.0 * sigma * sigma)) + return g / g.sum() + +class Blur(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageBlur", + display_name="Image Blur", + category="image/postprocessing", + essentials_category="Image Tools", + inputs=[ + io.Image.Input("image"), + io.Int.Input("blur_radius", default=1, min=1, max=31, step=1), + io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.1), + ], + outputs=[ + io.Image.Output(), + ], + ) + + @classmethod + def execute(cls, image: torch.Tensor, blur_radius: int, sigma: float) -> io.NodeOutput: + if blur_radius == 0: + return io.NodeOutput(image) + + image = image.to(comfy.model_management.get_torch_device()) + batch_size, height, width, channels = image.shape + + kernel_size = blur_radius * 2 + 1 + kernel = gaussian_kernel(kernel_size, sigma, device=image.device).repeat(channels, 1, 1).unsqueeze(1) + + image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C) + padded_image = F.pad(image, (blur_radius,blur_radius,blur_radius,blur_radius), 'reflect') + blurred = F.conv2d(padded_image, kernel, padding=kernel_size // 2, groups=channels)[:,:,blur_radius:-blur_radius, blur_radius:-blur_radius] + blurred = blurred.permute(0, 2, 3, 1) + + return io.NodeOutput(blurred.to(comfy.model_management.intermediate_device())) + + +class Quantize(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageQuantize", + category="image/postprocessing", + inputs=[ + io.Image.Input("image"), + io.Int.Input("colors", default=256, min=1, max=256, step=1), + io.Combo.Input("dither", options=["none", "floyd-steinberg", "bayer-2", "bayer-4", "bayer-8", "bayer-16"]), + ], + outputs=[ + io.Image.Output(), + ], + ) + + @staticmethod + def bayer(im, pal_im, order): + def normalized_bayer_matrix(n): + if n == 0: + return np.zeros((1,1), "float32") + else: + q = 4 ** n + m = q * normalized_bayer_matrix(n - 1) + return np.bmat(((m-1.5, m+0.5), (m+1.5, m-0.5))) / q + + num_colors = len(pal_im.getpalette()) // 3 + spread = 2 * 256 / num_colors + bayer_n = int(math.log2(order)) + bayer_matrix = torch.from_numpy(spread * normalized_bayer_matrix(bayer_n) + 0.5) + + result = torch.from_numpy(np.array(im).astype(np.float32)) + tw = math.ceil(result.shape[0] / bayer_matrix.shape[0]) + th = math.ceil(result.shape[1] / bayer_matrix.shape[1]) + tiled_matrix = bayer_matrix.tile(tw, th).unsqueeze(-1) + result.add_(tiled_matrix[:result.shape[0],:result.shape[1]]).clamp_(0, 255) + result = result.to(dtype=torch.uint8) + + im = Image.fromarray(result.cpu().numpy()) + im = im.quantize(palette=pal_im, dither=Image.Dither.NONE) + return im + + @classmethod + def execute(cls, image: torch.Tensor, colors: int, dither: str) -> io.NodeOutput: + batch_size, height, width, _ = image.shape + result = torch.zeros_like(image) + + for b in range(batch_size): + im = Image.fromarray((image[b] * 255).to(torch.uint8).numpy(), mode='RGB') + + pal_im = im.quantize(colors=colors) # Required as described in https://github.com/python-pillow/Pillow/issues/5836 + + if dither == "none": + quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.NONE) + elif dither == "floyd-steinberg": + quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.FLOYDSTEINBERG) + elif dither.startswith("bayer"): + order = int(dither.split('-')[-1]) + quantized_image = Quantize.bayer(im, pal_im, order) + + quantized_array = torch.tensor(np.array(quantized_image.convert("RGB"))).float() / 255 + result[b] = quantized_array + + return io.NodeOutput(result) + +class Sharpen(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageSharpen", + category="image/postprocessing", + inputs=[ + io.Image.Input("image"), + io.Int.Input("sharpen_radius", default=1, min=1, max=31, step=1, advanced=True), + io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.01, advanced=True), + io.Float.Input("alpha", default=1.0, min=0.0, max=5.0, step=0.01, advanced=True), + ], + outputs=[ + io.Image.Output(), + ], + ) + + @classmethod + def execute(cls, image: torch.Tensor, sharpen_radius: int, sigma:float, alpha: float) -> io.NodeOutput: + if sharpen_radius == 0: + return io.NodeOutput(image) + + batch_size, height, width, channels = image.shape + image = image.to(comfy.model_management.get_torch_device()) + + kernel_size = sharpen_radius * 2 + 1 + kernel = gaussian_kernel(kernel_size, sigma, device=image.device) * -(alpha*10) + kernel = kernel.to(dtype=image.dtype) + center = kernel_size // 2 + kernel[center, center] = kernel[center, center] - kernel.sum() + 1.0 + kernel = kernel.repeat(channels, 1, 1).unsqueeze(1) + + tensor_image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C) + tensor_image = F.pad(tensor_image, (sharpen_radius,sharpen_radius,sharpen_radius,sharpen_radius), 'reflect') + sharpened = F.conv2d(tensor_image, kernel, padding=center, groups=channels)[:,:,sharpen_radius:-sharpen_radius, sharpen_radius:-sharpen_radius] + sharpened = sharpened.permute(0, 2, 3, 1) + + result = torch.clamp(sharpened, 0, 1) + + return io.NodeOutput(result.to(comfy.model_management.intermediate_device())) + +class ImageScaleToTotalPixels(io.ComfyNode): + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + crop_methods = ["disabled", "center"] + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ImageScaleToTotalPixels", + category="image/upscaling", + inputs=[ + io.Image.Input("image"), + io.Combo.Input("upscale_method", options=cls.upscale_methods), + io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01), + io.Int.Input("resolution_steps", default=1, min=1, max=256, advanced=True), + ], + outputs=[ + io.Image.Output(), + ], + ) + + @classmethod + def execute(cls, image, upscale_method, megapixels, resolution_steps) -> io.NodeOutput: + samples = image.movedim(-1,1) + total = megapixels * 1024 * 1024 + + scale_by = math.sqrt(total / (samples.shape[3] * samples.shape[2])) + width = round(samples.shape[3] * scale_by / resolution_steps) * resolution_steps + height = round(samples.shape[2] * scale_by / resolution_steps) * resolution_steps + + s = comfy.utils.common_upscale(samples, int(width), int(height), upscale_method, "disabled") + s = s.movedim(1,-1) + return io.NodeOutput(s) + +class ResizeType(str, Enum): + SCALE_BY = "scale by multiplier" + SCALE_DIMENSIONS = "scale dimensions" + SCALE_LONGER_DIMENSION = "scale longer dimension" + SCALE_SHORTER_DIMENSION = "scale shorter dimension" + SCALE_WIDTH = "scale width" + SCALE_HEIGHT = "scale height" + SCALE_TOTAL_PIXELS = "scale total pixels" + MATCH_SIZE = "match size" + SCALE_TO_MULTIPLE = "scale to multiple" + +def is_image(input: torch.Tensor) -> bool: + # images have 4 dimensions: [batch, height, width, channels] + # masks have 3 dimensions: [batch, height, width] + return len(input.shape) == 4 + +def init_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor: + if is_type_image: + input = input.movedim(-1, 1) + else: + input = input.unsqueeze(1) + return input + +def finalize_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor: + if is_type_image: + input = input.movedim(1, -1) + else: + input = input.squeeze(1) + return input + +def scale_by(input: torch.Tensor, multiplier: float, scale_method: str) -> torch.Tensor: + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + width = round(input.shape[-1] * multiplier) + height = round(input.shape[-2] * multiplier) + + input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled") + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_dimensions(input: torch.Tensor, width: int, height: int, scale_method: str, crop: str="disabled") -> torch.Tensor: + if width == 0 and height == 0: + return input + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + + if width == 0: + width = max(1, round(input.shape[-1] * height / input.shape[-2])) + elif height == 0: + height = max(1, round(input.shape[-2] * width / input.shape[-1])) + + input = comfy.utils.common_upscale(input, width, height, scale_method, crop) + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_longer_dimension(input: torch.Tensor, longer_size: int, scale_method: str) -> torch.Tensor: + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + width = input.shape[-1] + height = input.shape[-2] + + if height > width: + width = round((width / height) * longer_size) + height = longer_size + elif width > height: + height = round((height / width) * longer_size) + width = longer_size + else: + height = longer_size + width = longer_size + + input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled") + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_shorter_dimension(input: torch.Tensor, shorter_size: int, scale_method: str) -> torch.Tensor: + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + width = input.shape[-1] + height = input.shape[-2] + + if height < width: + width = round((width / height) * shorter_size) + height = shorter_size + elif width < height: + height = round((height / width) * shorter_size) + width = shorter_size + else: + height = shorter_size + width = shorter_size + + input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled") + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_total_pixels(input: torch.Tensor, megapixels: float, scale_method: str) -> torch.Tensor: + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + total = int(megapixels * 1024 * 1024) + + scale_by = math.sqrt(total / (input.shape[-1] * input.shape[-2])) + width = round(input.shape[-1] * scale_by) + height = round(input.shape[-2] * scale_by) + + input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled") + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_match_size(input: torch.Tensor, match: torch.Tensor, scale_method: str, crop: str) -> torch.Tensor: + is_type_image = is_image(input) + input = init_image_mask_input(input, is_type_image) + match = init_image_mask_input(match, is_image(match)) + + width = match.shape[-1] + height = match.shape[-2] + input = comfy.utils.common_upscale(input, width, height, scale_method, crop) + input = finalize_image_mask_input(input, is_type_image) + return input + +def scale_to_multiple_cover(input: torch.Tensor, multiple: int, scale_method: str) -> torch.Tensor: + if multiple <= 1: + return input + is_type_image = is_image(input) + if is_type_image: + _, height, width, _ = input.shape + else: + _, height, width = input.shape + target_w = (width // multiple) * multiple + target_h = (height // multiple) * multiple + if target_w == 0 or target_h == 0: + return input + if target_w == width and target_h == height: + return input + s_w = target_w / width + s_h = target_h / height + if s_w >= s_h: + scaled_w = target_w + scaled_h = int(math.ceil(height * s_w)) + if scaled_h < target_h: + scaled_h = target_h + else: + scaled_h = target_h + scaled_w = int(math.ceil(width * s_h)) + if scaled_w < target_w: + scaled_w = target_w + input = init_image_mask_input(input, is_type_image) + input = comfy.utils.common_upscale(input, scaled_w, scaled_h, scale_method, "disabled") + input = finalize_image_mask_input(input, is_type_image) + x0 = (scaled_w - target_w) // 2 + y0 = (scaled_h - target_h) // 2 + x1 = x0 + target_w + y1 = y0 + target_h + if is_type_image: + return input[:, y0:y1, x0:x1, :] + return input[:, y0:y1, x0:x1] + +class ResizeImageMaskNode(io.ComfyNode): + scale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + crop_methods = ["disabled", "center"] + + class ResizeTypedDict(TypedDict): + resize_type: ResizeType + scale_method: Literal["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + crop: Literal["disabled", "center"] + multiplier: float + width: int + height: int + longer_size: int + shorter_size: int + megapixels: float + multiple: int + + @classmethod + def define_schema(cls): + template = io.MatchType.Template("input_type", [io.Image, io.Mask]) + crop_combo = io.Combo.Input( + "crop", + options=cls.crop_methods, + default="center", + tooltip="How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + ) + return io.Schema( + node_id="ResizeImageMaskNode", + display_name="Resize Image/Mask", + description="Resize an image or mask using various scaling methods.", + category="transform", + search_aliases=["resize", "resize image", "resize mask", "scale", "scale image", "scale mask", "image resize", "change size", "dimensions", "shrink", "enlarge"], + inputs=[ + io.MatchType.Input("input", template=template), + io.DynamicCombo.Input( + "resize_type", + tooltip="Select how to resize: by exact dimensions, scale factor, matching another image, etc.", + options=[ + io.DynamicCombo.Option(ResizeType.SCALE_DIMENSIONS, [ + io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio."), + io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio."), + crop_combo, + ]), + io.DynamicCombo.Option(ResizeType.SCALE_BY, [ + io.Float.Input("multiplier", default=1.00, min=0.01, max=8.0, step=0.01, tooltip="Scale factor (e.g., 2.0 doubles size, 0.5 halves size)."), + ]), + io.DynamicCombo.Option(ResizeType.SCALE_LONGER_DIMENSION, [ + io.Int.Input("longer_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The longer edge will be resized to this value. Aspect ratio is preserved."), + ]), + io.DynamicCombo.Option(ResizeType.SCALE_SHORTER_DIMENSION, [ + io.Int.Input("shorter_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The shorter edge will be resized to this value. Aspect ratio is preserved."), + ]), + io.DynamicCombo.Option(ResizeType.SCALE_WIDTH, [ + io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Height auto-adjusts to preserve aspect ratio."), + ]), + io.DynamicCombo.Option(ResizeType.SCALE_HEIGHT, [ + io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Width auto-adjusts to preserve aspect ratio."), + ]), + io.DynamicCombo.Option(ResizeType.SCALE_TOTAL_PIXELS, [ + io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01, tooltip="Target total megapixels (e.g., 1.0 ≈ 1024×1024). Aspect ratio is preserved."), + ]), + io.DynamicCombo.Option(ResizeType.MATCH_SIZE, [ + io.MultiType.Input("match", [io.Image, io.Mask], tooltip="Resize input to match the dimensions of this reference image or mask."), + crop_combo, + ]), + io.DynamicCombo.Option(ResizeType.SCALE_TO_MULTIPLE, [ + io.Int.Input("multiple", default=8, min=1, max=MAX_RESOLUTION, step=1, tooltip="Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64)."), + ]), + ], + ), + io.Combo.Input( + "scale_method", + options=cls.scale_methods, + default="area", + tooltip="Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.", + ), + ], + outputs=[io.MatchType.Output(template=template, display_name="resized")] + ) + + @classmethod + def execute(cls, input: io.Image.Type | io.Mask.Type, scale_method: io.Combo.Type, resize_type: ResizeTypedDict) -> io.NodeOutput: + selected_type = resize_type["resize_type"] + if selected_type == ResizeType.SCALE_BY: + return io.NodeOutput(scale_by(input, resize_type["multiplier"], scale_method)) + elif selected_type == ResizeType.SCALE_DIMENSIONS: + return io.NodeOutput(scale_dimensions(input, resize_type["width"], resize_type["height"], scale_method, resize_type["crop"])) + elif selected_type == ResizeType.SCALE_LONGER_DIMENSION: + return io.NodeOutput(scale_longer_dimension(input, resize_type["longer_size"], scale_method)) + elif selected_type == ResizeType.SCALE_SHORTER_DIMENSION: + return io.NodeOutput(scale_shorter_dimension(input, resize_type["shorter_size"], scale_method)) + elif selected_type == ResizeType.SCALE_WIDTH: + return io.NodeOutput(scale_dimensions(input, resize_type["width"], 0, scale_method)) + elif selected_type == ResizeType.SCALE_HEIGHT: + return io.NodeOutput(scale_dimensions(input, 0, resize_type["height"], scale_method)) + elif selected_type == ResizeType.SCALE_TOTAL_PIXELS: + return io.NodeOutput(scale_total_pixels(input, resize_type["megapixels"], scale_method)) + elif selected_type == ResizeType.MATCH_SIZE: + return io.NodeOutput(scale_match_size(input, resize_type["match"], scale_method, resize_type["crop"])) + elif selected_type == ResizeType.SCALE_TO_MULTIPLE: + return io.NodeOutput(scale_to_multiple_cover(input, resize_type["multiple"], scale_method)) + raise ValueError(f"Unsupported resize type: {selected_type}") + +def batch_images(images: list[torch.Tensor]) -> torch.Tensor | None: + if len(images) == 0: + return None + # first, get the max channels count + max_channels = max(image.shape[-1] for image in images) + # then, pad all images to have the same channels count + padded_images: list[torch.Tensor] = [] + for image in images: + if image.shape[-1] < max_channels: + padded_images.append(torch.nn.functional.pad(image, (0,1), mode='constant', value=1.0)) + else: + padded_images.append(image) + # resize all images to be the same size as the first image + resized_images: list[torch.Tensor] = [] + first_image_shape = padded_images[0].shape + for image in padded_images: + if image.shape[1:] != first_image_shape[1:]: + resized_images.append(comfy.utils.common_upscale(image.movedim(-1,1), first_image_shape[2], first_image_shape[1], "bilinear", "center").movedim(1,-1)) + else: + resized_images.append(image) + # batch the images in the format [b, h, w, c] + return torch.cat(resized_images, dim=0) + +def batch_masks(masks: list[torch.Tensor]) -> torch.Tensor | None: + if len(masks) == 0: + return None + # resize all masks to be the same size as the first mask + resized_masks: list[torch.Tensor] = [] + first_mask_shape = masks[0].shape + for mask in masks: + if mask.shape[1:] != first_mask_shape[1:]: + mask = init_image_mask_input(mask, is_type_image=False) + mask = comfy.utils.common_upscale(mask, first_mask_shape[2], first_mask_shape[1], "bilinear", "center") + resized_masks.append(finalize_image_mask_input(mask, is_type_image=False)) + else: + resized_masks.append(mask) + # batch the masks in the format [b, h, w] + return torch.cat(resized_masks, dim=0) + +def batch_latents(latents: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor] | None: + if len(latents) == 0: + return None + samples_out = latents[0].copy() + samples_out["batch_index"] = [] + first_samples = latents[0]["samples"] + tensors: list[torch.Tensor] = [] + for latent in latents: + # first, deal with latent tensors + tensors.append(reshape_latent_to(first_samples.shape, latent["samples"], repeat_batch=False)) + # next, deal with batch_index + samples_out["batch_index"].extend(latent.get("batch_index", [x for x in range(0, latent["samples"].shape[0])])) + samples_out["samples"] = torch.cat(tensors, dim=0) + return samples_out + +class BatchImagesNode(io.ComfyNode): + @classmethod + def define_schema(cls): + autogrow_template = io.Autogrow.TemplatePrefix(io.Image.Input("image"), prefix="image", min=2, max=50) + return io.Schema( + node_id="BatchImagesNode", + display_name="Batch Images", + category="image", + search_aliases=["batch", "image batch", "batch images", "combine images", "merge images", "stack images"], + inputs=[ + io.Autogrow.Input("images", template=autogrow_template) + ], + outputs=[ + io.Image.Output() + ] + ) + + @classmethod + def execute(cls, images: io.Autogrow.Type) -> io.NodeOutput: + return io.NodeOutput(batch_images(list(images.values()))) + +class BatchMasksNode(io.ComfyNode): + @classmethod + def define_schema(cls): + autogrow_template = io.Autogrow.TemplatePrefix(io.Mask.Input("mask"), prefix="mask", min=2, max=50) + return io.Schema( + node_id="BatchMasksNode", + search_aliases=["combine masks", "stack masks", "merge masks"], + display_name="Batch Masks", + category="mask", + inputs=[ + io.Autogrow.Input("masks", template=autogrow_template) + ], + outputs=[ + io.Mask.Output() + ] + ) + + @classmethod + def execute(cls, masks: io.Autogrow.Type) -> io.NodeOutput: + return io.NodeOutput(batch_masks(list(masks.values()))) + +class BatchLatentsNode(io.ComfyNode): + @classmethod + def define_schema(cls): + autogrow_template = io.Autogrow.TemplatePrefix(io.Latent.Input("latent"), prefix="latent", min=2, max=50) + return io.Schema( + node_id="BatchLatentsNode", + search_aliases=["combine latents", "stack latents", "merge latents"], + display_name="Batch Latents", + category="latent", + inputs=[ + io.Autogrow.Input("latents", template=autogrow_template) + ], + outputs=[ + io.Latent.Output() + ] + ) + + @classmethod + def execute(cls, latents: io.Autogrow.Type) -> io.NodeOutput: + return io.NodeOutput(batch_latents(list(latents.values()))) + +class BatchImagesMasksLatentsNode(io.ComfyNode): + @classmethod + def define_schema(cls): + matchtype_template = io.MatchType.Template("input", allowed_types=[io.Image, io.Mask, io.Latent]) + autogrow_template = io.Autogrow.TemplatePrefix( + io.MatchType.Input("input", matchtype_template), + prefix="input", min=1, max=50) + return io.Schema( + node_id="BatchImagesMasksLatentsNode", + search_aliases=["combine batch", "merge batch", "stack inputs"], + display_name="Batch Images/Masks/Latents", + category="util", + inputs=[ + io.Autogrow.Input("inputs", template=autogrow_template) + ], + outputs=[ + io.MatchType.Output(id=None, template=matchtype_template) + ] + ) + + @classmethod + def execute(cls, inputs: io.Autogrow.Type) -> io.NodeOutput: + batched = None + values = list(inputs.values()) + # latents + if isinstance(values[0], dict): + batched = batch_latents(values) + # images + elif is_image(values[0]): + batched = batch_images(values) + # masks + else: + batched = batch_masks(values) + return io.NodeOutput(batched) + + +class PostProcessingExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + Blend, + Blur, + Quantize, + Sharpen, + ImageScaleToTotalPixels, + ResizeImageMaskNode, + BatchImagesNode, + BatchMasksNode, + BatchLatentsNode, + # BatchImagesMasksLatentsNode, + ] + +async def comfy_entrypoint() -> PostProcessingExtension: + return PostProcessingExtension() diff --git a/docs/hel-892/sdpose-reference/core0150__nodes.py b/docs/hel-892/sdpose-reference/core0150__nodes.py new file mode 100644 index 00000000..e2fc20d5 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0150__nodes.py @@ -0,0 +1,2516 @@ +from __future__ import annotations +import torch + + +import os +import sys +import json +import glob +import hashlib +import inspect + +import traceback +import math +import time +import random +import logging + +from PIL import Image, ImageOps, ImageSequence +from PIL.PngImagePlugin import PngInfo + +import numpy as np +import safetensors.torch + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy")) + +import comfy.diffusers_load +import comfy.samplers +import comfy.sample +import comfy.sd +import comfy.utils +import comfy.controlnet +from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict, FileLocator +from comfy_api.internal import register_versions, ComfyAPIWithVersion +from comfy_api.version_list import supported_versions +from comfy_api.latest import io, ComfyExtension + +import comfy.clip_vision + +import comfy.model_management +from comfy.cli_args import args + +import importlib + +import folder_paths +import latent_preview +import node_helpers + +if args.enable_manager: + import comfyui_manager + +def before_node_execution(): + comfy.model_management.throw_exception_if_processing_interrupted() + +def interrupt_processing(value=True): + comfy.model_management.interrupt_current_processing(value) + +MAX_RESOLUTION=16384 + +class CLIPTextEncode(ComfyNodeABC): + @classmethod + def INPUT_TYPES(s) -> InputTypeDict: + return { + "required": { + "text": (IO.STRING, {"multiline": True, "dynamicPrompts": True, "tooltip": "The text to be encoded."}), + "clip": (IO.CLIP, {"tooltip": "The CLIP model used for encoding the text."}) + } + } + RETURN_TYPES = (IO.CONDITIONING,) + OUTPUT_TOOLTIPS = ("A conditioning containing the embedded text used to guide the diffusion model.",) + FUNCTION = "encode" + + CATEGORY = "conditioning" + DESCRIPTION = "Encodes a text prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images." + SEARCH_ALIASES = ["text", "prompt", "text prompt", "positive prompt", "negative prompt", "encode text", "text encoder", "encode prompt"] + + def encode(self, clip, text): + if clip is None: + raise RuntimeError("ERROR: clip input is invalid: None\n\nIf the clip is from a checkpoint loader node your checkpoint does not contain a valid clip or text encoder model.") + tokens = clip.tokenize(text) + return (clip.encode_from_tokens_scheduled(tokens), ) + + +class ConditioningCombine: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "combine" + + CATEGORY = "conditioning" + SEARCH_ALIASES = ["combine", "merge conditioning", "combine prompts", "merge prompts", "mix prompts", "add prompt"] + + def combine(self, conditioning_1, conditioning_2): + return (conditioning_1 + conditioning_2, ) + +class ConditioningAverage : + SEARCH_ALIASES = ["blend prompts", "interpolate conditioning", "mix prompts", "style fusion", "weighted blend"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ), + "conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "addWeighted" + + CATEGORY = "conditioning" + + def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength): + out = [] + + if len(conditioning_from) > 1: + logging.warning("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.") + + cond_from = conditioning_from[0][0] + pooled_output_from = conditioning_from[0][1].get("pooled_output", None) + + for i in range(len(conditioning_to)): + t1 = conditioning_to[i][0] + pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from) + t0 = cond_from[:,:t1.shape[1]] + if t0.shape[1] < t1.shape[1]: + t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1) + + tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength)) + t_to = conditioning_to[i][1].copy() + if pooled_output_from is not None and pooled_output_to is not None: + t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength)) + elif pooled_output_from is not None: + t_to["pooled_output"] = pooled_output_from + + n = [tw, t_to] + out.append(n) + return (out, ) + +class ConditioningConcat: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "conditioning_to": ("CONDITIONING",), + "conditioning_from": ("CONDITIONING",), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "concat" + + CATEGORY = "conditioning" + + def concat(self, conditioning_to, conditioning_from): + out = [] + + if len(conditioning_from) > 1: + logging.warning("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.") + + cond_from = conditioning_from[0][0] + + for i in range(len(conditioning_to)): + t1 = conditioning_to[i][0] + tw = torch.cat((t1, cond_from),1) + n = [tw, conditioning_to[i][1].copy()] + out.append(n) + + return (out, ) + +class ConditioningSetArea: + SEARCH_ALIASES = ["regional prompt", "area prompt", "spatial conditioning", "localized prompt"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "conditioning" + + def append(self, conditioning, width, height, x, y, strength): + c = node_helpers.conditioning_set_values(conditioning, {"area": (height // 8, width // 8, y // 8, x // 8), + "strength": strength, + "set_area_to_bounds": False}) + return (c, ) + +class ConditioningSetAreaPercentage: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}), + "height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}), + "x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}), + "y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "conditioning" + + def append(self, conditioning, width, height, x, y, strength): + c = node_helpers.conditioning_set_values(conditioning, {"area": ("percentage", height, width, y, x), + "strength": strength, + "set_area_to_bounds": False}) + return (c, ) + +class ConditioningSetAreaStrength: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "conditioning" + + def append(self, conditioning, strength): + c = node_helpers.conditioning_set_values(conditioning, {"strength": strength}) + return (c, ) + + +class ConditioningSetMask: + SEARCH_ALIASES = ["masked prompt", "regional inpaint conditioning", "mask conditioning"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "mask": ("MASK", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "conditioning" + + def append(self, conditioning, mask, set_cond_area, strength): + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask.shape) < 3: + mask = mask.unsqueeze(0) + + c = node_helpers.conditioning_set_values(conditioning, {"mask": mask, + "set_area_to_bounds": set_area_to_bounds, + "mask_strength": strength}) + return (c, ) + +class ConditioningZeroOut: + SEARCH_ALIASES = ["null conditioning", "clear conditioning"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", )}} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "zero_out" + + CATEGORY = "advanced/conditioning" + + def zero_out(self, conditioning): + c = [] + for t in conditioning: + d = t[1].copy() + pooled_output = d.get("pooled_output", None) + if pooled_output is not None: + d["pooled_output"] = torch.zeros_like(pooled_output) + conditioning_lyrics = d.get("conditioning_lyrics", None) + if conditioning_lyrics is not None: + d["conditioning_lyrics"] = torch.zeros_like(conditioning_lyrics) + n = [torch.zeros_like(t[0]), d] + c.append(n) + return (c, ) + +class ConditioningSetTimestepRange: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "set_range" + + CATEGORY = "advanced/conditioning" + + def set_range(self, conditioning, start, end): + c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start, + "end_percent": end}) + return (c, ) + +class VAEDecode: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "samples": ("LATENT", {"tooltip": "The latent to be decoded."}), + "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."}) + } + } + RETURN_TYPES = ("IMAGE",) + OUTPUT_TOOLTIPS = ("The decoded image.",) + FUNCTION = "decode" + + CATEGORY = "latent" + DESCRIPTION = "Decodes latent images back into pixel space images." + SEARCH_ALIASES = ["decode", "decode latent", "latent to image", "render latent"] + + def decode(self, vae, samples): + latent = samples["samples"] + if latent.is_nested: + latent = latent.unbind()[0] + + images = vae.decode(latent) + if len(images.shape) == 5: #Combine batches + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + return (images, ) + +class VAEDecodeTiled: + @classmethod + def INPUT_TYPES(s): + return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ), + "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 32, "advanced": True}), + "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32, "advanced": True}), + "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to decode at a time.", "advanced": True}), + "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap.", "advanced": True}), + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "decode" + + CATEGORY = "_for_testing" + + def decode(self, vae, samples, tile_size, overlap=64, temporal_size=64, temporal_overlap=8): + if tile_size < overlap * 4: + overlap = tile_size // 4 + if temporal_size < temporal_overlap * 2: + temporal_overlap = temporal_overlap // 2 + temporal_compression = vae.temporal_compression_decode() + if temporal_compression is not None: + temporal_size = max(2, temporal_size // temporal_compression) + temporal_overlap = max(1, min(temporal_size // 2, temporal_overlap // temporal_compression)) + else: + temporal_size = None + temporal_overlap = None + + compression = vae.spacial_compression_decode() + images = vae.decode_tiled(samples["samples"], tile_x=tile_size // compression, tile_y=tile_size // compression, overlap=overlap // compression, tile_t=temporal_size, overlap_t=temporal_overlap) + if len(images.shape) == 5: #Combine batches + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + return (images, ) + +class VAEEncode: + @classmethod + def INPUT_TYPES(s): + return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "latent" + SEARCH_ALIASES = ["encode", "encode image", "image to latent"] + + def encode(self, vae, pixels): + t = vae.encode(pixels) + return ({"samples":t}, ) + +class VAEEncodeTiled: + @classmethod + def INPUT_TYPES(s): + return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ), + "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 64, "advanced": True}), + "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32, "advanced": True}), + "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to encode at a time.", "advanced": True}), + "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap.", "advanced": True}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "_for_testing" + + def encode(self, vae, pixels, tile_size, overlap, temporal_size=64, temporal_overlap=8): + t = vae.encode_tiled(pixels, tile_x=tile_size, tile_y=tile_size, overlap=overlap, tile_t=temporal_size, overlap_t=temporal_overlap) + return ({"samples": t}, ) + +class VAEEncodeForInpaint: + @classmethod + def INPUT_TYPES(s): + return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "latent/inpaint" + + def encode(self, vae, pixels, mask, grow_mask_by=6): + downscale_ratio = vae.spacial_compression_encode() + x = (pixels.shape[1] // downscale_ratio) * downscale_ratio + y = (pixels.shape[2] // downscale_ratio) * downscale_ratio + mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear") + + pixels = pixels.clone() + if pixels.shape[1] != x or pixels.shape[2] != y: + x_offset = (pixels.shape[1] % downscale_ratio) // 2 + y_offset = (pixels.shape[2] % downscale_ratio) // 2 + pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset] + + #grow mask by a few pixels to keep things seamless in latent space + if grow_mask_by == 0: + mask_erosion = mask + else: + kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by)) + padding = math.ceil((grow_mask_by - 1) / 2) + + mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1) + + m = (1.0 - mask.round()).squeeze(1) + for i in range(3): + pixels[:,:,:,i] -= 0.5 + pixels[:,:,:,i] *= m + pixels[:,:,:,i] += 0.5 + t = vae.encode(pixels) + + return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, ) + + +class InpaintModelConditioning: + @classmethod + def INPUT_TYPES(s): + return {"required": {"positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "vae": ("VAE", ), + "pixels": ("IMAGE", ), + "mask": ("MASK", ), + "noise_mask": ("BOOLEAN", {"default": True, "tooltip": "Add a noise mask to the latent so sampling will only happen within the mask. Might improve results or completely break things depending on the model."}), + }} + + RETURN_TYPES = ("CONDITIONING","CONDITIONING","LATENT") + RETURN_NAMES = ("positive", "negative", "latent") + FUNCTION = "encode" + + CATEGORY = "conditioning/inpaint" + + def encode(self, positive, negative, pixels, vae, mask, noise_mask=True): + x = (pixels.shape[1] // 8) * 8 + y = (pixels.shape[2] // 8) * 8 + mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear") + + orig_pixels = pixels + pixels = orig_pixels.clone() + if pixels.shape[1] != x or pixels.shape[2] != y: + x_offset = (pixels.shape[1] % 8) // 2 + y_offset = (pixels.shape[2] % 8) // 2 + pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset] + + m = (1.0 - mask.round()).squeeze(1) + for i in range(3): + pixels[:,:,:,i] -= 0.5 + pixels[:,:,:,i] *= m + pixels[:,:,:,i] += 0.5 + concat_latent = vae.encode(pixels) + orig_latent = vae.encode(orig_pixels) + + out_latent = {} + + out_latent["samples"] = orig_latent + if noise_mask: + out_latent["noise_mask"] = mask + + out = [] + for conditioning in [positive, negative]: + c = node_helpers.conditioning_set_values(conditioning, {"concat_latent_image": concat_latent, + "concat_mask": mask}) + out.append(c) + return (out[0], out[1], out_latent) + + +class SaveLatent: + SEARCH_ALIASES = ["export latent"] + + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT", ), + "filename_prefix": ("STRING", {"default": "latents/ComfyUI"})}, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + RETURN_TYPES = () + FUNCTION = "save" + + OUTPUT_NODE = True + + CATEGORY = "_for_testing" + + def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None): + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + + # support save metadata for latent sharing + prompt_info = "" + if prompt is not None: + prompt_info = json.dumps(prompt) + + metadata = None + if not args.disable_metadata: + metadata = {"prompt": prompt_info} + if extra_pnginfo is not None: + for x in extra_pnginfo: + metadata[x] = json.dumps(extra_pnginfo[x]) + + file = f"{filename}_{counter:05}_.latent" + + results: list[FileLocator] = [] + results.append({ + "filename": file, + "subfolder": subfolder, + "type": "output" + }) + + file = os.path.join(full_output_folder, file) + + output = {} + output["latent_tensor"] = samples["samples"].contiguous() + output["latent_format_version_0"] = torch.tensor([]) + + comfy.utils.save_torch_file(output, file, metadata=metadata) + return { "ui": { "latents": results } } + + +class LoadLatent: + SEARCH_ALIASES = ["import latent", "open latent"] + + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")] + return {"required": {"latent": [sorted(files), ]}, } + + CATEGORY = "_for_testing" + + RETURN_TYPES = ("LATENT", ) + FUNCTION = "load" + + def load(self, latent): + latent_path = folder_paths.get_annotated_filepath(latent) + latent = safetensors.torch.load_file(latent_path, device="cpu") + multiplier = 1.0 + if "latent_format_version_0" not in latent: + multiplier = 1.0 / 0.18215 + samples = {"samples": latent["latent_tensor"].float() * multiplier} + return (samples, ) + + @classmethod + def IS_CHANGED(s, latent): + image_path = folder_paths.get_annotated_filepath(latent) + m = hashlib.sha256() + with open(image_path, 'rb') as f: + m.update(f.read()) + return m.digest().hex() + + @classmethod + def VALIDATE_INPUTS(s, latent): + if not folder_paths.exists_annotated_filepath(latent): + return "Invalid latent file: {}".format(latent) + return True + + +class CheckpointLoader: + SEARCH_ALIASES = ["load model", "model loader"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ), + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}} + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + FUNCTION = "load_checkpoint" + + CATEGORY = "advanced/loaders" + DEPRECATED = True + + def load_checkpoint(self, config_name, ckpt_name): + config_path = folder_paths.get_full_path("configs", config_name) + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + +class CheckpointLoaderSimple: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}), + } + } + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + OUTPUT_TOOLTIPS = ("The model used for denoising latents.", + "The CLIP model used for encoding text prompts.", + "The VAE model used for encoding and decoding images to and from latent space.") + FUNCTION = "load_checkpoint" + + CATEGORY = "loaders" + DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents." + SEARCH_ALIASES = ["load model", "checkpoint", "model loader", "load checkpoint", "ckpt", "model"] + + def load_checkpoint(self, ckpt_name): + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + return out[:3] + +class DiffusersLoader: + SEARCH_ALIASES = ["load diffusers model"] + + @classmethod + def INPUT_TYPES(cls): + paths = [] + for search_path in folder_paths.get_folder_paths("diffusers"): + if os.path.exists(search_path): + for root, subdir, files in os.walk(search_path, followlinks=True): + if "model_index.json" in files: + paths.append(os.path.relpath(root, start=search_path)) + + return {"required": {"model_path": (paths,), }} + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + FUNCTION = "load_checkpoint" + + CATEGORY = "advanced/loaders/deprecated" + + def load_checkpoint(self, model_path, output_vae=True, output_clip=True): + for search_path in folder_paths.get_folder_paths("diffusers"): + if os.path.exists(search_path): + path = os.path.join(search_path, model_path) + if os.path.exists(path): + model_path = path + break + + return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings")) + + +class unCLIPCheckpointLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), + }} + RETURN_TYPES = ("MODEL", "CLIP", "VAE", "CLIP_VISION") + FUNCTION = "load_checkpoint" + + CATEGORY = "loaders" + + def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True): + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + return out + +class CLIPSetLastLayer: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip": ("CLIP", ), + "stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1, "advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "set_last_layer" + + CATEGORY = "conditioning" + + def set_last_layer(self, clip, stop_at_clip_layer): + clip = clip.clone() + clip.clip_layer(stop_at_clip_layer) + return (clip,) + +class LoraLoader: + ESSENTIALS_CATEGORY = "Image Generation" + + def __init__(self): + self.loaded_lora = None + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}), + "clip": ("CLIP", {"tooltip": "The CLIP model the LoRA will be applied to."}), + "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the diffusion model. This value can be negative."}), + "strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the CLIP model. This value can be negative."}), + } + } + + RETURN_TYPES = ("MODEL", "CLIP") + OUTPUT_TOOLTIPS = ("The modified diffusion model.", "The modified CLIP model.") + FUNCTION = "load_lora" + + CATEGORY = "loaders" + DESCRIPTION = "LoRAs are used to modify diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together." + SEARCH_ALIASES = ["lora", "load lora", "apply lora", "lora loader", "lora model"] + + def load_lora(self, model, clip, lora_name, strength_model, strength_clip): + if strength_model == 0 and strength_clip == 0: + return (model, clip) + + lora_path = folder_paths.get_full_path_or_raise("loras", lora_name) + lora = None + if self.loaded_lora is not None: + if self.loaded_lora[0] == lora_path: + lora = self.loaded_lora[1] + else: + self.loaded_lora = None + + if lora is None: + lora = comfy.utils.load_torch_file(lora_path, safe_load=True) + self.loaded_lora = (lora_path, lora) + + model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip) + return (model_lora, clip_lora) + +class LoraLoaderModelOnly(LoraLoader): + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "lora_name": (folder_paths.get_filename_list("loras"), ), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}), + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "load_lora_model_only" + + def load_lora_model_only(self, model, lora_name, strength_model): + return (self.load_lora(model, None, lora_name, strength_model, 0)[0],) + +class VAELoader: + video_taes = ["taehv", "lighttaew2_2", "lighttaew2_1", "lighttaehy1_5", "taeltx_2"] + image_taes = ["taesd", "taesdxl", "taesd3", "taef1"] + @staticmethod + def vae_list(s): + vaes = folder_paths.get_filename_list("vae") + approx_vaes = folder_paths.get_filename_list("vae_approx") + sdxl_taesd_enc = False + sdxl_taesd_dec = False + sd1_taesd_enc = False + sd1_taesd_dec = False + sd3_taesd_enc = False + sd3_taesd_dec = False + f1_taesd_enc = False + f1_taesd_dec = False + + for v in approx_vaes: + if v.startswith("taesd_decoder."): + sd1_taesd_dec = True + elif v.startswith("taesd_encoder."): + sd1_taesd_enc = True + elif v.startswith("taesdxl_decoder."): + sdxl_taesd_dec = True + elif v.startswith("taesdxl_encoder."): + sdxl_taesd_enc = True + elif v.startswith("taesd3_decoder."): + sd3_taesd_dec = True + elif v.startswith("taesd3_encoder."): + sd3_taesd_enc = True + elif v.startswith("taef1_encoder."): + f1_taesd_dec = True + elif v.startswith("taef1_decoder."): + f1_taesd_enc = True + else: + for tae in s.video_taes: + if v.startswith(tae): + vaes.append(v) + + if sd1_taesd_dec and sd1_taesd_enc: + vaes.append("taesd") + if sdxl_taesd_dec and sdxl_taesd_enc: + vaes.append("taesdxl") + if sd3_taesd_dec and sd3_taesd_enc: + vaes.append("taesd3") + if f1_taesd_dec and f1_taesd_enc: + vaes.append("taef1") + vaes.append("pixel_space") + return vaes + + @staticmethod + def load_taesd(name): + sd = {} + approx_vaes = folder_paths.get_filename_list("vae_approx") + + encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes)) + decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes)) + + enc = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", encoder)) + for k in enc: + sd["taesd_encoder.{}".format(k)] = enc[k] + + dec = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", decoder)) + for k in dec: + sd["taesd_decoder.{}".format(k)] = dec[k] + + if name == "taesd": + sd["vae_scale"] = torch.tensor(0.18215) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesdxl": + sd["vae_scale"] = torch.tensor(0.13025) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesd3": + sd["vae_scale"] = torch.tensor(1.5305) + sd["vae_shift"] = torch.tensor(0.0609) + elif name == "taef1": + sd["vae_scale"] = torch.tensor(0.3611) + sd["vae_shift"] = torch.tensor(0.1159) + return sd + + @classmethod + def INPUT_TYPES(s): + return {"required": { "vae_name": (s.vae_list(s), )}} + RETURN_TYPES = ("VAE",) + FUNCTION = "load_vae" + + CATEGORY = "loaders" + + #TODO: scale factor? + def load_vae(self, vae_name): + metadata = None + if vae_name == "pixel_space": + sd = {} + sd["pixel_space_vae"] = torch.tensor(1.0) + elif vae_name in self.image_taes: + sd = self.load_taesd(vae_name) + else: + if os.path.splitext(vae_name)[0] in self.video_taes: + vae_path = folder_paths.get_full_path_or_raise("vae_approx", vae_name) + else: + vae_path = folder_paths.get_full_path_or_raise("vae", vae_name) + sd, metadata = comfy.utils.load_torch_file(vae_path, return_metadata=True) + vae = comfy.sd.VAE(sd=sd, metadata=metadata) + vae.throw_exception_if_invalid() + return (vae,) + +class ControlNetLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}} + + RETURN_TYPES = ("CONTROL_NET",) + FUNCTION = "load_controlnet" + + CATEGORY = "loaders" + SEARCH_ALIASES = ["controlnet", "control net", "cn", "load controlnet", "controlnet loader"] + + def load_controlnet(self, control_net_name): + controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name) + controlnet = comfy.controlnet.load_controlnet(controlnet_path) + if controlnet is None: + raise RuntimeError("ERROR: controlnet file is invalid and does not contain a valid controlnet model.") + return (controlnet,) + +class DiffControlNetLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "control_net_name": (folder_paths.get_filename_list("controlnet"), )}} + + RETURN_TYPES = ("CONTROL_NET",) + FUNCTION = "load_controlnet" + + CATEGORY = "loaders" + + def load_controlnet(self, model, control_net_name): + controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name) + controlnet = comfy.controlnet.load_controlnet(controlnet_path, model) + return (controlnet,) + + +class ControlNetApply: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "control_net": ("CONTROL_NET", ), + "image": ("IMAGE", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_controlnet" + + DEPRECATED = True + CATEGORY = "conditioning/controlnet" + + def apply_controlnet(self, conditioning, control_net, image, strength): + if strength == 0: + return (conditioning, ) + + c = [] + control_hint = image.movedim(-1,1) + for t in conditioning: + n = [t[0], t[1].copy()] + c_net = control_net.copy().set_cond_hint(control_hint, strength) + if 'control' in t[1]: + c_net.set_previous_controlnet(t[1]['control']) + n[1]['control'] = c_net + n[1]['control_apply_to_uncond'] = True + c.append(n) + return (c, ) + + +class ControlNetApplyAdvanced: + @classmethod + def INPUT_TYPES(s): + return {"required": {"positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "control_net": ("CONTROL_NET", ), + "image": ("IMAGE", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}) + }, + "optional": {"vae": ("VAE", ), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING") + RETURN_NAMES = ("positive", "negative") + FUNCTION = "apply_controlnet" + + CATEGORY = "conditioning/controlnet" + SEARCH_ALIASES = ["controlnet", "apply controlnet", "use controlnet", "control net"] + + def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None, extra_concat=[]): + if strength == 0: + return (positive, negative) + + control_hint = image.movedim(-1,1) + cnets = {} + + out = [] + for conditioning in [positive, negative]: + c = [] + for t in conditioning: + d = t[1].copy() + + prev_cnet = d.get('control', None) + if prev_cnet in cnets: + c_net = cnets[prev_cnet] + else: + c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat) + c_net.set_previous_controlnet(prev_cnet) + cnets[prev_cnet] = c_net + + d['control'] = c_net + d['control_apply_to_uncond'] = False + n = [t[0], d] + c.append(n) + out.append(c) + return (out[0], out[1]) + + +class UNETLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "unet_name": (folder_paths.get_filename_list("diffusion_models"), ), + "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"],) + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "load_unet" + + CATEGORY = "advanced/loaders" + + def load_unet(self, unet_name, weight_dtype): + model_options = {} + if weight_dtype == "fp8_e4m3fn": + model_options["dtype"] = torch.float8_e4m3fn + elif weight_dtype == "fp8_e4m3fn_fast": + model_options["dtype"] = torch.float8_e4m3fn + model_options["fp8_optimizations"] = True + elif weight_dtype == "fp8_e5m2": + model_options["dtype"] = torch.float8_e5m2 + + unet_path = folder_paths.get_full_path_or_raise("diffusion_models", unet_name) + model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options) + return (model,) + +class CLIPLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name": (folder_paths.get_filename_list("text_encoders"), ), + "type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "lumina2", "wan", "hidream", "chroma", "ace", "omnigen2", "qwen_image", "hunyuan_image", "flux2", "ovis"], ), + }, + "optional": { + "device": (["default", "cpu"], {"advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "load_clip" + + CATEGORY = "advanced/loaders" + + DESCRIPTION = "[Recipes]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 xxl/ clip-g / clip-l\nstable_audio: t5 base\nmochi: t5 xxl\ncosmos: old t5 xxl\nlumina2: gemma 2 2B\nwan: umt5 xxl\n hidream: llama-3.1 (Recommend) or t5\nomnigen2: qwen vl 2.5 3B" + + def load_clip(self, clip_name, type="stable_diffusion", device="default"): + clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION) + + model_options = {} + if device == "cpu": + model_options["load_device"] = model_options["offload_device"] = torch.device("cpu") + + clip_path = folder_paths.get_full_path_or_raise("text_encoders", clip_name) + clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options) + return (clip,) + +class DualCLIPLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name1": (folder_paths.get_filename_list("text_encoders"), ), + "clip_name2": (folder_paths.get_filename_list("text_encoders"), ), + "type": (["sdxl", "sd3", "flux", "hunyuan_video", "hidream", "hunyuan_image", "hunyuan_video_15", "kandinsky5", "kandinsky5_image", "ltxv", "newbie", "ace"], ), + }, + "optional": { + "device": (["default", "cpu"], {"advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "load_clip" + + CATEGORY = "advanced/loaders" + + DESCRIPTION = "[Recipes]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5\nhidream: at least one of t5 or llama, recommended t5 and llama\nhunyuan_image: qwen2.5vl 7b and byt5 small\nnewbie: gemma-3-4b-it, jina clip v2" + + def load_clip(self, clip_name1, clip_name2, type, device="default"): + clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION) + + clip_path1 = folder_paths.get_full_path_or_raise("text_encoders", clip_name1) + clip_path2 = folder_paths.get_full_path_or_raise("text_encoders", clip_name2) + + model_options = {} + if device == "cpu": + model_options["load_device"] = model_options["offload_device"] = torch.device("cpu") + + clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options) + return (clip,) + +class CLIPVisionLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ), + }} + RETURN_TYPES = ("CLIP_VISION",) + FUNCTION = "load_clip" + + CATEGORY = "loaders" + + def load_clip(self, clip_name): + clip_path = folder_paths.get_full_path_or_raise("clip_vision", clip_name) + clip_vision = comfy.clip_vision.load(clip_path) + if clip_vision is None: + raise RuntimeError("ERROR: clip vision file is invalid and does not contain a valid vision model.") + return (clip_vision,) + +class CLIPVisionEncode: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_vision": ("CLIP_VISION",), + "image": ("IMAGE",), + "crop": (["center", "none"],) + }} + RETURN_TYPES = ("CLIP_VISION_OUTPUT",) + FUNCTION = "encode" + + CATEGORY = "conditioning" + + def encode(self, clip_vision, image, crop): + crop_image = True + if crop != "center": + crop_image = False + output = clip_vision.encode_image(image, crop=crop_image) + return (output,) + +class StyleModelLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}} + + RETURN_TYPES = ("STYLE_MODEL",) + FUNCTION = "load_style_model" + + CATEGORY = "loaders" + + def load_style_model(self, style_model_name): + style_model_path = folder_paths.get_full_path_or_raise("style_models", style_model_name) + style_model = comfy.sd.load_style_model(style_model_path) + return (style_model,) + + +class StyleModelApply: + SEARCH_ALIASES = ["style transfer"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "style_model": ("STYLE_MODEL", ), + "clip_vision_output": ("CLIP_VISION_OUTPUT", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}), + "strength_type": (["multiply", "attn_bias"], ), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_stylemodel" + + CATEGORY = "conditioning/style_model" + + def apply_stylemodel(self, conditioning, style_model, clip_vision_output, strength, strength_type): + cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0) + if strength_type == "multiply": + cond *= strength + + n = cond.shape[1] + c_out = [] + for t in conditioning: + (txt, keys) = t + keys = keys.copy() + # even if the strength is 1.0 (i.e, no change), if there's already a mask, we have to add to it + if "attention_mask" in keys or (strength_type == "attn_bias" and strength != 1.0): + # math.log raises an error if the argument is zero + # torch.log returns -inf, which is what we want + attn_bias = torch.log(torch.Tensor([strength if strength_type == "attn_bias" else 1.0])) + # get the size of the mask image + mask_ref_size = keys.get("attention_mask_img_shape", (1, 1)) + n_ref = mask_ref_size[0] * mask_ref_size[1] + n_txt = txt.shape[1] + # grab the existing mask + mask = keys.get("attention_mask", None) + # create a default mask if it doesn't exist + if mask is None: + mask = torch.zeros((txt.shape[0], n_txt + n_ref, n_txt + n_ref), dtype=torch.float16) + # convert the mask dtype, because it might be boolean + # we want it to be interpreted as a bias + if mask.dtype == torch.bool: + # log(True) = log(1) = 0 + # log(False) = log(0) = -inf + mask = torch.log(mask.to(dtype=torch.float16)) + # now we make the mask bigger to add space for our new tokens + new_mask = torch.zeros((txt.shape[0], n_txt + n + n_ref, n_txt + n + n_ref), dtype=torch.float16) + # copy over the old mask, in quandrants + new_mask[:, :n_txt, :n_txt] = mask[:, :n_txt, :n_txt] + new_mask[:, :n_txt, n_txt+n:] = mask[:, :n_txt, n_txt:] + new_mask[:, n_txt+n:, :n_txt] = mask[:, n_txt:, :n_txt] + new_mask[:, n_txt+n:, n_txt+n:] = mask[:, n_txt:, n_txt:] + # now fill in the attention bias to our redux tokens + new_mask[:, :n_txt, n_txt:n_txt+n] = attn_bias + new_mask[:, n_txt+n:, n_txt:n_txt+n] = attn_bias + keys["attention_mask"] = new_mask.to(txt.device) + keys["attention_mask_img_shape"] = mask_ref_size + + c_out.append([torch.cat((txt, cond), dim=1), keys]) + + return (c_out,) + +class unCLIPConditioning: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "clip_vision_output": ("CLIP_VISION_OUTPUT", ), + "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), + "noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_adm" + + CATEGORY = "conditioning" + + def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation): + if strength == 0: + return (conditioning, ) + + c = node_helpers.conditioning_set_values(conditioning, {"unclip_conditioning": [{"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}]}, append=True) + return (c, ) + +class GLIGENLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}} + + RETURN_TYPES = ("GLIGEN",) + FUNCTION = "load_gligen" + + CATEGORY = "loaders" + + def load_gligen(self, gligen_name): + gligen_path = folder_paths.get_full_path_or_raise("gligen", gligen_name) + gligen = comfy.sd.load_gligen(gligen_path) + return (gligen,) + +class GLIGENTextBoxApply: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_to": ("CONDITIONING", ), + "clip": ("CLIP", ), + "gligen_textbox_model": ("GLIGEN", ), + "text": ("STRING", {"multiline": True, "dynamicPrompts": True}), + "width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "conditioning/gligen" + + def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y): + c = [] + cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled="unprojected") + for t in conditioning_to: + n = [t[0], t[1].copy()] + position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)] + prev = [] + if "gligen" in n[1]: + prev = n[1]['gligen'][2] + + n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params) + c.append(n) + return (c, ) + +class EmptyLatentImage: + def __init__(self): + self.device = comfy.model_management.intermediate_device() + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the latent images in pixels."}), + "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of the latent images in pixels."}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."}) + } + } + RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The empty latent image batch.",) + FUNCTION = "generate" + + CATEGORY = "latent" + DESCRIPTION = "Create a new batch of empty latent images to be denoised via sampling." + SEARCH_ALIASES = ["empty", "empty latent", "new latent", "create latent", "blank latent", "blank"] + + def generate(self, width, height, batch_size=1): + latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device) + return ({"samples": latent, "downscale_ratio_spacial": 8}, ) + + +class LatentFromBatch: + SEARCH_ALIASES = ["select from batch", "pick latent", "batch subset"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "batch_index": ("INT", {"default": 0, "min": 0, "max": 63}), + "length": ("INT", {"default": 1, "min": 1, "max": 64}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "frombatch" + + CATEGORY = "latent/batch" + + def frombatch(self, samples, batch_index, length): + s = samples.copy() + s_in = samples["samples"] + batch_index = min(s_in.shape[0] - 1, batch_index) + length = min(s_in.shape[0] - batch_index, length) + s["samples"] = s_in[batch_index:batch_index + length].clone() + if "noise_mask" in samples: + masks = samples["noise_mask"] + if masks.shape[0] == 1: + s["noise_mask"] = masks.clone() + else: + if masks.shape[0] < s_in.shape[0]: + masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]] + s["noise_mask"] = masks[batch_index:batch_index + length].clone() + if "batch_index" not in s: + s["batch_index"] = [x for x in range(batch_index, batch_index+length)] + else: + s["batch_index"] = samples["batch_index"][batch_index:batch_index + length] + return (s,) + +class RepeatLatentBatch: + SEARCH_ALIASES = ["duplicate latent", "clone latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "amount": ("INT", {"default": 1, "min": 1, "max": 64}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "repeat" + + CATEGORY = "latent/batch" + + def repeat(self, samples, amount): + s = samples.copy() + s_in = samples["samples"] + + s["samples"] = s_in.repeat((amount,) + ((1,) * (s_in.ndim - 1))) + if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1: + masks = samples["noise_mask"] + if masks.shape[0] < s_in.shape[0]: + masks = masks.repeat((math.ceil(s_in.shape[0] / masks.shape[0]),) + ((1,) * (masks.ndim - 1)))[:s_in.shape[0]] + s["noise_mask"] = samples["noise_mask"].repeat((amount,) + ((1,) * (samples["noise_mask"].ndim - 1))) + if "batch_index" in s: + offset = max(s["batch_index"]) - min(s["batch_index"]) + 1 + s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]] + return (s,) + +class LatentUpscale: + SEARCH_ALIASES = ["enlarge latent", "resize latent"] + + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"] + crop_methods = ["disabled", "center"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,), + "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "crop": (s.crop_methods,)}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "upscale" + + CATEGORY = "latent" + + def upscale(self, samples, upscale_method, width, height, crop): + if width == 0 and height == 0: + s = samples + else: + s = samples.copy() + + if width == 0: + height = max(64, height) + width = max(64, round(samples["samples"].shape[-1] * height / samples["samples"].shape[-2])) + elif height == 0: + width = max(64, width) + height = max(64, round(samples["samples"].shape[-2] * width / samples["samples"].shape[-1])) + else: + width = max(64, width) + height = max(64, height) + + s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop) + return (s,) + +class LatentUpscaleBy: + SEARCH_ALIASES = ["enlarge latent", "resize latent", "scale latent"] + + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,), + "scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "upscale" + + CATEGORY = "latent" + + def upscale(self, samples, upscale_method, scale_by): + s = samples.copy() + width = round(samples["samples"].shape[-1] * scale_by) + height = round(samples["samples"].shape[-2] * scale_by) + s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled") + return (s,) + +class LatentRotate: + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "rotate" + + CATEGORY = "latent/transform" + + def rotate(self, samples, rotation): + s = samples.copy() + rotate_by = 0 + if rotation.startswith("90"): + rotate_by = 1 + elif rotation.startswith("180"): + rotate_by = 2 + elif rotation.startswith("270"): + rotate_by = 3 + + s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2]) + return (s,) + +class LatentFlip: + SEARCH_ALIASES = ["mirror latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "flip_method": (["x-axis: vertically", "y-axis: horizontally"],), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "flip" + + CATEGORY = "latent/transform" + + def flip(self, samples, flip_method): + s = samples.copy() + if flip_method.startswith("x"): + s["samples"] = torch.flip(samples["samples"], dims=[2]) + elif flip_method.startswith("y"): + s["samples"] = torch.flip(samples["samples"], dims=[3]) + + return (s,) + +class LatentComposite: + SEARCH_ALIASES = ["overlay latent", "layer latent", "paste latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples_to": ("LATENT",), + "samples_from": ("LATENT",), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "composite" + + CATEGORY = "latent" + + def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0): + x = x // 8 + y = y // 8 + feather = feather // 8 + samples_out = samples_to.copy() + s = samples_to["samples"].clone() + samples_to = samples_to["samples"] + samples_from = samples_from["samples"] + if feather == 0: + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] + else: + samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] + mask = torch.ones_like(samples_from) + for t in range(feather): + if y != 0: + mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1)) + + if y + samples_from.shape[2] < samples_to.shape[2]: + mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1)) + if x != 0: + mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1)) + if x + samples_from.shape[3] < samples_to.shape[3]: + mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1)) + rev_mask = torch.ones_like(mask) - mask + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] * mask + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] * rev_mask + samples_out["samples"] = s + return (samples_out,) + +class LatentBlend: + SEARCH_ALIASES = ["mix latents", "interpolate latents"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "samples1": ("LATENT",), + "samples2": ("LATENT",), + "blend_factor": ("FLOAT", { + "default": 0.5, + "min": 0, + "max": 1, + "step": 0.01 + }), + }} + + RETURN_TYPES = ("LATENT",) + FUNCTION = "blend" + + CATEGORY = "_for_testing" + + def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"): + + samples_out = samples1.copy() + samples1 = samples1["samples"] + samples2 = samples2["samples"] + + if samples1.shape != samples2.shape: + samples2.permute(0, 3, 1, 2) + samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center') + samples2.permute(0, 2, 3, 1) + + samples_blended = self.blend_mode(samples1, samples2, blend_mode) + samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor) + samples_out["samples"] = samples_blended + return (samples_out,) + + def blend_mode(self, img1, img2, mode): + if mode == "normal": + return img2 + else: + raise ValueError(f"Unsupported blend mode: {mode}") + +class LatentCrop: + SEARCH_ALIASES = ["trim latent", "cut latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "crop" + + CATEGORY = "latent/transform" + + def crop(self, samples, width, height, x, y): + s = samples.copy() + samples = samples['samples'] + x = x // 8 + y = y // 8 + + #enfonce minimum size of 64 + if x > (samples.shape[3] - 8): + x = samples.shape[3] - 8 + if y > (samples.shape[2] - 8): + y = samples.shape[2] - 8 + + new_height = height // 8 + new_width = width // 8 + to_x = new_width + x + to_y = new_height + y + s['samples'] = samples[:,:,y:to_y, x:to_x] + return (s,) + +class SetLatentNoiseMask: + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "mask": ("MASK",), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "set_mask" + + CATEGORY = "latent/inpaint" + + def set_mask(self, samples, mask): + s = samples.copy() + s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])) + return (s,) + +def common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False): + latent_image = latent["samples"] + latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image, latent.get("downscale_ratio_spacial", None)) + + if disable_noise: + noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu") + else: + batch_inds = latent["batch_index"] if "batch_index" in latent else None + noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) + + noise_mask = None + if "noise_mask" in latent: + noise_mask = latent["noise_mask"] + + callback = latent_preview.prepare_callback(model, steps) + disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED + samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, + denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step, + force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) + out = latent.copy() + out.pop("downscale_ratio_spacial", None) + out["samples"] = samples + return (out, ) + +class KSampler: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True, "tooltip": "The random seed used for creating the noise."}), + "steps": ("INT", {"default": 20, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}), + "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01, "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."}), + "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."}), + "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler controls how noise is gradually removed to form the image."}), + "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}), + "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}), + "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}), + "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."}), + } + } + + RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The denoised latent.",) + FUNCTION = "sample" + + CATEGORY = "sampling" + DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image." + SEARCH_ALIASES = ["sampler", "sample", "generate", "denoise", "diffuse", "txt2img", "img2img"] + + def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0): + return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise) + +class KSamplerAdvanced: + @classmethod + def INPUT_TYPES(s): + return {"required": + {"model": ("MODEL",), + "add_noise": (["enable", "disable"], {"advanced": True}), + "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}), + "steps": ("INT", {"default": 20, "min": 1, "max": 10000}), + "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}), + "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ), + "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ), + "positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "latent_image": ("LATENT", ), + "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000, "advanced": True}), + "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000, "advanced": True}), + "return_with_leftover_noise": (["disable", "enable"], {"advanced": True}), + } + } + + RETURN_TYPES = ("LATENT",) + FUNCTION = "sample" + + CATEGORY = "sampling" + + def sample(self, model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0): + force_full_denoise = True + if return_with_leftover_noise == "enable": + force_full_denoise = False + disable_noise = False + if add_noise == "disable": + disable_noise = True + return common_ksampler(model, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise) + +class SaveImage: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + self.type = "output" + self.prefix_append = "" + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE", {"tooltip": "The images to save."}), + "filename_prefix": ("STRING", {"default": "ComfyUI", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}) + }, + "hidden": { + "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO" + }, + } + + RETURN_TYPES = () + FUNCTION = "save_images" + + OUTPUT_NODE = True + + CATEGORY = "image" + ESSENTIALS_CATEGORY = "Basics" + DESCRIPTION = "Saves the input images to your ComfyUI output directory." + SEARCH_ALIASES = ["save", "save image", "export image", "output image", "write image", "download"] + + def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None): + filename_prefix += self.prefix_append + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) + results = list() + for (batch_number, image) in enumerate(images): + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + metadata = None + if not args.disable_metadata: + metadata = PngInfo() + if prompt is not None: + metadata.add_text("prompt", json.dumps(prompt)) + if extra_pnginfo is not None: + for x in extra_pnginfo: + metadata.add_text(x, json.dumps(extra_pnginfo[x])) + + filename_with_batch_num = filename.replace("%batch_num%", str(batch_number)) + file = f"{filename_with_batch_num}_{counter:05}_.png" + img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level) + results.append({ + "filename": file, + "subfolder": subfolder, + "type": self.type + }) + counter += 1 + + return { "ui": { "images": results } } + +class PreviewImage(SaveImage): + def __init__(self): + self.output_dir = folder_paths.get_temp_directory() + self.type = "temp" + self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5)) + self.compress_level = 1 + + SEARCH_ALIASES = ["preview", "preview image", "show image", "view image", "display image", "image viewer"] + + @classmethod + def INPUT_TYPES(s): + return {"required": + {"images": ("IMAGE", ), }, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + +class LoadImage: + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] + files = folder_paths.filter_files_content_types(files, ["image"]) + return {"required": + {"image": (sorted(files), {"image_upload": True})}, + } + + CATEGORY = "image" + ESSENTIALS_CATEGORY = "Basics" + SEARCH_ALIASES = ["load image", "open image", "import image", "image input", "upload image", "read image", "image loader"] + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "load_image" + def load_image(self, image): + image_path = folder_paths.get_annotated_filepath(image) + + img = node_helpers.pillow(Image.open, image_path) + + output_images = [] + output_masks = [] + w, h = None, None + + for i in ImageSequence.Iterator(img): + i = node_helpers.pillow(ImageOps.exif_transpose, i) + + if i.mode == 'I': + i = i.point(lambda i: i * (1 / 255)) + image = i.convert("RGB") + + if len(output_images) == 0: + w = image.size[0] + h = image.size[1] + + if image.size[0] != w or image.size[1] != h: + continue + + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + if 'A' in i.getbands(): + mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0 + mask = 1. - torch.from_numpy(mask) + elif i.mode == 'P' and 'transparency' in i.info: + mask = np.array(i.convert('RGBA').getchannel('A')).astype(np.float32) / 255.0 + mask = 1. - torch.from_numpy(mask) + else: + mask = torch.zeros((64,64), dtype=torch.float32, device="cpu") + output_images.append(image) + output_masks.append(mask.unsqueeze(0)) + + if img.format == "MPO": + break # ignore all frames except the first one for MPO format + + if len(output_images) > 1: + output_image = torch.cat(output_images, dim=0) + output_mask = torch.cat(output_masks, dim=0) + else: + output_image = output_images[0] + output_mask = output_masks[0] + + return (output_image, output_mask) + + @classmethod + def IS_CHANGED(s, image): + image_path = folder_paths.get_annotated_filepath(image) + m = hashlib.sha256() + with open(image_path, 'rb') as f: + m.update(f.read()) + return m.digest().hex() + + @classmethod + def VALIDATE_INPUTS(s, image): + if not folder_paths.exists_annotated_filepath(image): + return "Invalid image file: {}".format(image) + + return True + +class LoadImageMask: + SEARCH_ALIASES = ["import mask", "alpha mask", "channel mask"] + + _color_channels = ["alpha", "red", "green", "blue"] + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] + return {"required": + {"image": (sorted(files), {"image_upload": True}), + "channel": (s._color_channels, ), } + } + + CATEGORY = "mask" + + RETURN_TYPES = ("MASK",) + FUNCTION = "load_image" + def load_image(self, image, channel): + image_path = folder_paths.get_annotated_filepath(image) + i = node_helpers.pillow(Image.open, image_path) + i = node_helpers.pillow(ImageOps.exif_transpose, i) + if i.getbands() != ("R", "G", "B", "A"): + if i.mode == 'I': + i = i.point(lambda i: i * (1 / 255)) + i = i.convert("RGBA") + mask = None + c = channel[0].upper() + if c in i.getbands(): + mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0 + mask = torch.from_numpy(mask) + if c == 'A': + mask = 1. - mask + else: + mask = torch.zeros((64,64), dtype=torch.float32, device="cpu") + return (mask.unsqueeze(0),) + + @classmethod + def IS_CHANGED(s, image, channel): + image_path = folder_paths.get_annotated_filepath(image) + m = hashlib.sha256() + with open(image_path, 'rb') as f: + m.update(f.read()) + return m.digest().hex() + + @classmethod + def VALIDATE_INPUTS(s, image): + if not folder_paths.exists_annotated_filepath(image): + return "Invalid image file: {}".format(image) + + return True + + +class LoadImageOutput(LoadImage): + SEARCH_ALIASES = ["output image", "previous generation"] + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("COMBO", { + "image_upload": True, + "image_folder": "output", + "remote": { + "route": "/internal/files/output", + "refresh_button": True, + "control_after_refresh": "first", + }, + }), + } + } + + DESCRIPTION = "Load an image from the output folder. When the refresh button is clicked, the node will update the image list and automatically select the first image, allowing for easy iteration." + EXPERIMENTAL = True + FUNCTION = "load_image" + + +class ImageScale: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + crop_methods = ["disabled", "center"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,), + "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + "crop": (s.crop_methods,)}} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "upscale" + + CATEGORY = "image/upscaling" + ESSENTIALS_CATEGORY = "Image Tools" + SEARCH_ALIASES = ["resize", "resize image", "scale image", "image resize", "zoom", "zoom in", "change size"] + + def upscale(self, image, upscale_method, width, height, crop): + if width == 0 and height == 0: + s = image + else: + samples = image.movedim(-1,1) + + if width == 0: + width = max(1, round(samples.shape[3] * height / samples.shape[2])) + elif height == 0: + height = max(1, round(samples.shape[2] * width / samples.shape[3])) + + s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop) + s = s.movedim(1,-1) + return (s,) + +class ImageScaleBy: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,), + "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "upscale" + + CATEGORY = "image/upscaling" + + def upscale(self, image, upscale_method, scale_by): + samples = image.movedim(-1,1) + width = round(samples.shape[3] * scale_by) + height = round(samples.shape[2] * scale_by) + s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled") + s = s.movedim(1,-1) + return (s,) + +class ImageInvert: + SEARCH_ALIASES = ["reverse colors"] + ESSENTIALS_CATEGORY = "Image Tools" + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",)}} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "invert" + + CATEGORY = "image" + + def invert(self, image): + s = 1.0 - image + return (s,) + +class ImageBatch: + SEARCH_ALIASES = ["combine images", "merge images", "stack images"] + ESSENTIALS_CATEGORY = "Image Tools" + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "batch" + + CATEGORY = "image" + DEPRECATED = True + + def batch(self, image1, image2): + if image1.shape[-1] != image2.shape[-1]: + if image1.shape[-1] > image2.shape[-1]: + image2 = torch.nn.functional.pad(image2, (0,1), mode='constant', value=1.0) + else: + image1 = torch.nn.functional.pad(image1, (0,1), mode='constant', value=1.0) + if image1.shape[1:] != image2.shape[1:]: + image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1) + s = torch.cat((image1, image2), dim=0) + return (s,) + +class EmptyImage: + def __init__(self, device="cpu"): + self.device = device + + @classmethod + def INPUT_TYPES(s): + return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), + "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}), + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "generate" + + CATEGORY = "image" + + def generate(self, width, height, batch_size=1, color=0): + r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF) + g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF) + b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF) + return (torch.cat((r, g, b), dim=-1), ) + +class ImagePadForOutpaint: + SEARCH_ALIASES = ["extend canvas", "expand image"] + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1, "advanced": True}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "expand_image" + + CATEGORY = "image" + + def expand_image(self, image, left, top, right, bottom, feathering): + d1, d2, d3, d4 = image.size() + + new_image = torch.ones( + (d1, d2 + top + bottom, d3 + left + right, d4), + dtype=torch.float32, + ) * 0.5 + + new_image[:, top:top + d2, left:left + d3, :] = image + + mask = torch.ones( + (d2 + top + bottom, d3 + left + right), + dtype=torch.float32, + ) + + t = torch.zeros( + (d2, d3), + dtype=torch.float32 + ) + + if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3: + + for i in range(d2): + for j in range(d3): + dt = i if top != 0 else d2 + db = d2 - i if bottom != 0 else d2 + + dl = j if left != 0 else d3 + dr = d3 - j if right != 0 else d3 + + d = min(dt, db, dl, dr) + + if d >= feathering: + continue + + v = (feathering - d) / feathering + + t[i, j] = v * v + + mask[top:top + d2, left:left + d3] = t + + return (new_image, mask.unsqueeze(0)) + + +NODE_CLASS_MAPPINGS = { + "KSampler": KSampler, + "CheckpointLoaderSimple": CheckpointLoaderSimple, + "CLIPTextEncode": CLIPTextEncode, + "CLIPSetLastLayer": CLIPSetLastLayer, + "VAEDecode": VAEDecode, + "VAEEncode": VAEEncode, + "VAEEncodeForInpaint": VAEEncodeForInpaint, + "VAELoader": VAELoader, + "EmptyLatentImage": EmptyLatentImage, + "LatentUpscale": LatentUpscale, + "LatentUpscaleBy": LatentUpscaleBy, + "LatentFromBatch": LatentFromBatch, + "RepeatLatentBatch": RepeatLatentBatch, + "SaveImage": SaveImage, + "PreviewImage": PreviewImage, + "LoadImage": LoadImage, + "LoadImageMask": LoadImageMask, + "LoadImageOutput": LoadImageOutput, + "ImageScale": ImageScale, + "ImageScaleBy": ImageScaleBy, + "ImageInvert": ImageInvert, + "ImageBatch": ImageBatch, + "ImagePadForOutpaint": ImagePadForOutpaint, + "EmptyImage": EmptyImage, + "ConditioningAverage": ConditioningAverage , + "ConditioningCombine": ConditioningCombine, + "ConditioningConcat": ConditioningConcat, + "ConditioningSetArea": ConditioningSetArea, + "ConditioningSetAreaPercentage": ConditioningSetAreaPercentage, + "ConditioningSetAreaStrength": ConditioningSetAreaStrength, + "ConditioningSetMask": ConditioningSetMask, + "KSamplerAdvanced": KSamplerAdvanced, + "SetLatentNoiseMask": SetLatentNoiseMask, + "LatentComposite": LatentComposite, + "LatentBlend": LatentBlend, + "LatentRotate": LatentRotate, + "LatentFlip": LatentFlip, + "LatentCrop": LatentCrop, + "LoraLoader": LoraLoader, + "CLIPLoader": CLIPLoader, + "UNETLoader": UNETLoader, + "DualCLIPLoader": DualCLIPLoader, + "CLIPVisionEncode": CLIPVisionEncode, + "StyleModelApply": StyleModelApply, + "unCLIPConditioning": unCLIPConditioning, + "ControlNetApply": ControlNetApply, + "ControlNetApplyAdvanced": ControlNetApplyAdvanced, + "ControlNetLoader": ControlNetLoader, + "DiffControlNetLoader": DiffControlNetLoader, + "StyleModelLoader": StyleModelLoader, + "CLIPVisionLoader": CLIPVisionLoader, + "VAEDecodeTiled": VAEDecodeTiled, + "VAEEncodeTiled": VAEEncodeTiled, + "unCLIPCheckpointLoader": unCLIPCheckpointLoader, + "GLIGENLoader": GLIGENLoader, + "GLIGENTextBoxApply": GLIGENTextBoxApply, + "InpaintModelConditioning": InpaintModelConditioning, + + "CheckpointLoader": CheckpointLoader, + "DiffusersLoader": DiffusersLoader, + + "LoadLatent": LoadLatent, + "SaveLatent": SaveLatent, + + "ConditioningZeroOut": ConditioningZeroOut, + "ConditioningSetTimestepRange": ConditioningSetTimestepRange, + "LoraLoaderModelOnly": LoraLoaderModelOnly, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + # Sampling + "KSampler": "KSampler", + "KSamplerAdvanced": "KSampler (Advanced)", + # Loaders + "CheckpointLoader": "Load Checkpoint With Config (DEPRECATED)", + "CheckpointLoaderSimple": "Load Checkpoint", + "VAELoader": "Load VAE", + "LoraLoader": "Load LoRA (Model and CLIP)", + "LoraLoaderModelOnly": "Load LoRA", + "CLIPLoader": "Load CLIP", + "ControlNetLoader": "Load ControlNet Model", + "DiffControlNetLoader": "Load ControlNet Model (diff)", + "StyleModelLoader": "Load Style Model", + "CLIPVisionLoader": "Load CLIP Vision", + "UNETLoader": "Load Diffusion Model", + # Conditioning + "CLIPVisionEncode": "CLIP Vision Encode", + "StyleModelApply": "Apply Style Model", + "CLIPTextEncode": "CLIP Text Encode (Prompt)", + "CLIPSetLastLayer": "CLIP Set Last Layer", + "ConditioningCombine": "Conditioning (Combine)", + "ConditioningAverage ": "Conditioning (Average)", + "ConditioningConcat": "Conditioning (Concat)", + "ConditioningSetArea": "Conditioning (Set Area)", + "ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)", + "ConditioningSetMask": "Conditioning (Set Mask)", + "ControlNetApply": "Apply ControlNet (OLD)", + "ControlNetApplyAdvanced": "Apply ControlNet", + # Latent + "VAEEncodeForInpaint": "VAE Encode (for Inpainting)", + "SetLatentNoiseMask": "Set Latent Noise Mask", + "VAEDecode": "VAE Decode", + "VAEEncode": "VAE Encode", + "LatentRotate": "Rotate Latent", + "LatentFlip": "Flip Latent", + "LatentCrop": "Crop Latent", + "EmptyLatentImage": "Empty Latent Image", + "LatentUpscale": "Upscale Latent", + "LatentUpscaleBy": "Upscale Latent By", + "LatentComposite": "Latent Composite", + "LatentBlend": "Latent Blend", + "LatentFromBatch" : "Latent From Batch", + "RepeatLatentBatch": "Repeat Latent Batch", + # Image + "SaveImage": "Save Image", + "PreviewImage": "Preview Image", + "LoadImage": "Load Image", + "LoadImageMask": "Load Image (as Mask)", + "LoadImageOutput": "Load Image (from Outputs)", + "ImageScale": "Upscale Image", + "ImageScaleBy": "Upscale Image By", + "ImageInvert": "Invert Image", + "ImagePadForOutpaint": "Pad Image for Outpainting", + "ImageBatch": "Batch Images", + "ImageCrop": "Image Crop", + "ImageStitch": "Image Stitch", + "ImageBlend": "Image Blend", + "ImageBlur": "Image Blur", + "ImageQuantize": "Image Quantize", + "ImageSharpen": "Image Sharpen", + "ImageScaleToTotalPixels": "Scale Image to Total Pixels", + "GetImageSize": "Get Image Size", + # _for_testing + "VAEDecodeTiled": "VAE Decode (Tiled)", + "VAEEncodeTiled": "VAE Encode (Tiled)", +} + +EXTENSION_WEB_DIRS = {} + +# Dictionary of successfully loaded module names and associated directories. +LOADED_MODULE_DIRS = {} + + +def get_module_name(module_path: str) -> str: + """ + Returns the module name based on the given module path. + Examples: + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.py") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__.py") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__/") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.disabled") -> "custom_nodes + Args: + module_path (str): The path of the module. + Returns: + str: The module name. + """ + base_path = os.path.basename(module_path) + if os.path.isfile(module_path): + base_path = os.path.splitext(base_path)[0] + return base_path + + +async def load_custom_node(module_path: str, ignore=set(), module_parent="custom_nodes") -> bool: + module_name = get_module_name(module_path) + if os.path.isfile(module_path): + sp = os.path.splitext(module_path) + module_name = sp[0] + sys_module_name = module_name + elif os.path.isdir(module_path): + sys_module_name = module_path.replace(".", "_x_") + + try: + logging.debug("Trying to load custom node {}".format(module_path)) + if os.path.isfile(module_path): + module_spec = importlib.util.spec_from_file_location(sys_module_name, module_path) + module_dir = os.path.split(module_path)[0] + else: + module_spec = importlib.util.spec_from_file_location(sys_module_name, os.path.join(module_path, "__init__.py")) + module_dir = module_path + + module = importlib.util.module_from_spec(module_spec) + sys.modules[sys_module_name] = module + module_spec.loader.exec_module(module) + + LOADED_MODULE_DIRS[module_name] = os.path.abspath(module_dir) + + try: + from comfy_config import config_parser + + project_config = config_parser.extract_node_configuration(module_path) + + web_dir_name = project_config.tool_comfy.web + + if web_dir_name: + web_dir_path = os.path.join(module_path, web_dir_name) + + if os.path.isdir(web_dir_path): + project_name = project_config.project.name + + EXTENSION_WEB_DIRS[project_name] = web_dir_path + + logging.info("Automatically register web folder {} for {}".format(web_dir_name, project_name)) + except Exception as e: + logging.warning(f"Unable to parse pyproject.toml due to lack dependency pydantic-settings, please run 'pip install -r requirements.txt': {e}") + + if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None: + web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY"))) + if os.path.isdir(web_dir): + EXTENSION_WEB_DIRS[module_name] = web_dir + + # V1 node definition + if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: + for name, node_cls in module.NODE_CLASS_MAPPINGS.items(): + if name not in ignore: + NODE_CLASS_MAPPINGS[name] = node_cls + node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path)) + if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None: + NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS) + return True + # V3 Extension Definition + elif hasattr(module, "comfy_entrypoint"): + entrypoint = getattr(module, "comfy_entrypoint") + if not callable(entrypoint): + logging.warning(f"comfy_entrypoint in {module_path} is not callable, skipping.") + return False + try: + if inspect.iscoroutinefunction(entrypoint): + extension = await entrypoint() + else: + extension = entrypoint() + if not isinstance(extension, ComfyExtension): + logging.warning(f"comfy_entrypoint in {module_path} did not return a ComfyExtension, skipping.") + return False + await extension.on_load() + node_list = await extension.get_node_list() + if not isinstance(node_list, list): + logging.warning(f"comfy_entrypoint in {module_path} did not return a list of nodes, skipping.") + return False + for node_cls in node_list: + node_cls: io.ComfyNode + schema = node_cls.GET_SCHEMA() + if schema.node_id not in ignore: + NODE_CLASS_MAPPINGS[schema.node_id] = node_cls + node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path)) + if schema.display_name is not None: + NODE_DISPLAY_NAME_MAPPINGS[schema.node_id] = schema.display_name + return True + except Exception as e: + logging.warning(f"Error while calling comfy_entrypoint in {module_path}: {e}") + return False + else: + logging.warning(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS or NODES_LIST (need one).") + return False + except Exception as e: + logging.warning(traceback.format_exc()) + logging.warning(f"Cannot import {module_path} module for custom nodes: {e}") + return False + +async def init_external_custom_nodes(): + """ + Initializes the external custom nodes. + + This function loads custom nodes from the specified folder paths and imports them into the application. + It measures the import times for each custom node and logs the results. + + Returns: + None + """ + base_node_names = set(NODE_CLASS_MAPPINGS.keys()) + node_paths = folder_paths.get_folder_paths("custom_nodes") + node_import_times = [] + for custom_node_path in node_paths: + possible_modules = os.listdir(os.path.realpath(custom_node_path)) + if "__pycache__" in possible_modules: + possible_modules.remove("__pycache__") + + for possible_module in possible_modules: + module_path = os.path.join(custom_node_path, possible_module) + if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": + continue + if module_path.endswith(".disabled"): + continue + if args.disable_all_custom_nodes and possible_module not in args.whitelist_custom_nodes: + logging.info(f"Skipping {possible_module} due to disable_all_custom_nodes and whitelist_custom_nodes") + continue + + if args.enable_manager: + if comfyui_manager.should_be_disabled(module_path): + logging.info(f"Blocked by policy: {module_path}") + continue + + time_before = time.perf_counter() + success = await load_custom_node(module_path, base_node_names, module_parent="custom_nodes") + node_import_times.append((time.perf_counter() - time_before, module_path, success)) + + if len(node_import_times) > 0: + logging.info("\nImport times for custom nodes:") + for n in sorted(node_import_times): + if n[2]: + import_message = "" + else: + import_message = " (IMPORT FAILED)" + logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1])) + logging.info("") + +async def init_builtin_extra_nodes(): + """ + Initializes the built-in extra nodes in ComfyUI. + + This function loads the extra node files located in the "comfy_extras" directory and imports them into ComfyUI. + If any of the extra node files fail to import, a warning message is logged. + + Returns: + None + """ + extras_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras") + extras_files = [ + "nodes_latent.py", + "nodes_hypernetwork.py", + "nodes_upscale_model.py", + "nodes_post_processing.py", + "nodes_mask.py", + "nodes_compositing.py", + "nodes_rebatch.py", + "nodes_model_merging.py", + "nodes_tomesd.py", + "nodes_clip_sdxl.py", + "nodes_canny.py", + "nodes_freelunch.py", + "nodes_custom_sampler.py", + "nodes_hypertile.py", + "nodes_model_advanced.py", + "nodes_model_downscale.py", + "nodes_images.py", + "nodes_video_model.py", + "nodes_train.py", + "nodes_dataset.py", + "nodes_sag.py", + "nodes_perpneg.py", + "nodes_stable3d.py", + "nodes_sdupscale.py", + "nodes_photomaker.py", + "nodes_pixart.py", + "nodes_cond.py", + "nodes_morphology.py", + "nodes_stable_cascade.py", + "nodes_differential_diffusion.py", + "nodes_ip2p.py", + "nodes_model_merging_model_specific.py", + "nodes_pag.py", + "nodes_align_your_steps.py", + "nodes_attention_multiply.py", + "nodes_advanced_samplers.py", + "nodes_webcam.py", + "nodes_audio.py", + "nodes_sd3.py", + "nodes_gits.py", + "nodes_controlnet.py", + "nodes_hunyuan.py", + "nodes_eps.py", + "nodes_flux.py", + "nodes_lora_extract.py", + "nodes_torch_compile.py", + "nodes_mochi.py", + "nodes_slg.py", + "nodes_mahiro.py", + "nodes_lt_upsampler.py", + "nodes_lt_audio.py", + "nodes_lt.py", + "nodes_hooks.py", + "nodes_load_3d.py", + "nodes_cosmos.py", + "nodes_video.py", + "nodes_lumina2.py", + "nodes_wan.py", + "nodes_lotus.py", + "nodes_hunyuan3d.py", + "nodes_primitive.py", + "nodes_cfg.py", + "nodes_optimalsteps.py", + "nodes_hidream.py", + "nodes_fresca.py", + "nodes_apg.py", + "nodes_preview_any.py", + "nodes_ace.py", + "nodes_string.py", + "nodes_camera_trajectory.py", + "nodes_edit_model.py", + "nodes_tcfg.py", + "nodes_context_windows.py", + "nodes_qwen.py", + "nodes_chroma_radiance.py", + "nodes_model_patch.py", + "nodes_easycache.py", + "nodes_audio_encoder.py", + "nodes_rope.py", + "nodes_logic.py", + "nodes_nop.py", + "nodes_kandinsky5.py", + "nodes_wanmove.py", + "nodes_image_compare.py", + "nodes_zimage.py", + "nodes_glsl.py", + "nodes_lora_debug.py", + "nodes_textgen.py", + "nodes_color.py", + "nodes_toolkit.py", + "nodes_replacements.py", + "nodes_nag.py", + ] + + import_failed = [] + for node_file in extras_files: + if not await load_custom_node(os.path.join(extras_dir, node_file), module_parent="comfy_extras"): + import_failed.append(node_file) + + return import_failed + + +async def init_builtin_api_nodes(): + api_nodes_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_api_nodes") + api_nodes_files = sorted(glob.glob(os.path.join(api_nodes_dir, "nodes_*.py"))) + + import_failed = [] + for node_file in api_nodes_files: + if not await load_custom_node(node_file, module_parent="comfy_api_nodes"): + import_failed.append(os.path.basename(node_file)) + + return import_failed + +async def init_public_apis(): + register_versions([ + ComfyAPIWithVersion( + version=getattr(v, "VERSION"), + api_class=v + ) for v in supported_versions + ]) + +async def init_extra_nodes(init_custom_nodes=True, init_api_nodes=True): + await init_public_apis() + + import_failed = await init_builtin_extra_nodes() + + import_failed_api = [] + if init_api_nodes: + import_failed_api = await init_builtin_api_nodes() + + if init_custom_nodes: + await init_external_custom_nodes() + else: + logging.info("Skipping loading of custom nodes") + + if len(import_failed_api) > 0: + logging.warning("WARNING: some comfy_api_nodes/ nodes did not import correctly. This may be because they are missing some dependencies.\n") + for node in import_failed_api: + logging.warning("IMPORT FAILED: {}".format(node)) + logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.") + if args.windows_standalone_build: + logging.warning("Please run the update script: update/update_comfyui.bat") + else: + logging.warning("Please do a: pip install -r requirements.txt") + logging.warning("") + + if len(import_failed) > 0: + logging.warning("WARNING: some comfy_extras/ nodes did not import correctly. This may be because they are missing some dependencies.\n") + for node in import_failed: + logging.warning("IMPORT FAILED: {}".format(node)) + logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.") + if args.windows_standalone_build: + logging.warning("Please run the update script: update/update_comfyui.bat") + else: + logging.warning("Please do a: pip install -r requirements.txt") + logging.warning("") + + return import_failed diff --git a/docs/hel-892/sdpose-reference/core0151-commit.json b/docs/hel-892/sdpose-reference/core0151-commit.json new file mode 100644 index 00000000..32bdb34d --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151-commit.json @@ -0,0 +1 @@ +{"sha":"3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f","node_id":"C_kwDOIygeJtoAKDNkZDEwYTU5YzAwMjQ4ZDAwZjBjYjBhYjc5NGZmMWJiOWZiMDBhNWY","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f","author":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-02-26T20:59:22Z"},"committer":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-02-26T20:59:22Z"},"tree":{"sha":"7b8cbb865be9b72a3a8ef838595d34dfaa90e82a","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/trees/7b8cbb865be9b72a3a8ef838595d34dfaa90e82a"},"message":"ComfyUI v0.15.1","parents":[{"sha":"88d05fe483a9f420a69d681e615422930404292b","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/88d05fe483a9f420a69d681e615422930404292b","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/88d05fe483a9f420a69d681e615422930404292b"}],"verification":{"verified":false,"reason":"unsigned","signature":null,"payload":null,"verified_at":null}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/core0151-tag.json b/docs/hel-892/sdpose-reference/core0151-tag.json new file mode 100644 index 00000000..7225a75f --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151-tag.json @@ -0,0 +1 @@ +{"ref":"refs/tags/v0.15.1","node_id":"REF_kwDOIygeJrFyZWZzL3RhZ3MvdjAuMTUuMQ","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/refs/tags/v0.15.1","object":{"sha":"3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f"}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/core0151__LICENSE b/docs/hel-892/sdpose-reference/core0151__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input__video_types.py b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input__video_types.py new file mode 100644 index 00000000..451e9526 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input__video_types.py @@ -0,0 +1,128 @@ +from __future__ import annotations +from abc import ABC, abstractmethod +from fractions import Fraction +from typing import Optional, Union, IO +import io +import av +from .._util import VideoContainer, VideoCodec, VideoComponents + +class VideoInput(ABC): + """ + Abstract base class for video input types. + """ + + @abstractmethod + def get_components(self) -> VideoComponents: + """ + Abstract method to get the video components (images, audio, and frame rate). + + Returns: + VideoComponents containing images, audio, and frame rate + """ + pass + + @abstractmethod + def save_to( + self, + path: Union[str, IO[bytes]], + format: VideoContainer = VideoContainer.AUTO, + codec: VideoCodec = VideoCodec.AUTO, + metadata: Optional[dict] = None + ): + """ + Abstract method to save the video input to a file. + """ + pass + + @abstractmethod + def as_trimmed( + self, + start_time: float | None = None, + duration: float | None = None, + strict_duration: bool = False, + ) -> VideoInput | None: + """ + Create a new VideoInput which is trimmed to have the corresponding start_time and duration + + Returns: + A new VideoInput, or None if the result would have negative duration + """ + pass + + def get_stream_source(self) -> Union[str, io.BytesIO]: + """ + Get a streamable source for the video. This allows processing without + loading the entire video into memory. + + Returns: + Either a file path (str) or a BytesIO object that can be opened with av. + + Default implementation creates a BytesIO buffer, but subclasses should + override this for better performance when possible. + """ + buffer = io.BytesIO() + self.save_to(buffer) + buffer.seek(0) + return buffer + + # Provide a default implementation, but subclasses can provide optimized versions + # if possible. + def get_dimensions(self) -> tuple[int, int]: + """ + Returns the dimensions of the video input. + + Returns: + Tuple of (width, height) + """ + components = self.get_components() + return components.images.shape[2], components.images.shape[1] + + def get_duration(self) -> float: + """ + Returns the duration of the video in seconds. + + Returns: + Duration in seconds + """ + components = self.get_components() + frame_count = components.images.shape[0] + return float(frame_count / components.frame_rate) + + def get_frame_count(self) -> int: + """ + Returns the number of frames in the video. + + Default implementation uses :meth:`get_components`, which may require + loading all frames into memory. File-based implementations should + override this method and use container/stream metadata instead. + + Returns: + Total number of frames as an integer. + """ + return int(self.get_components().images.shape[0]) + + def get_frame_rate(self) -> Fraction: + """ + Returns the frame rate of the video. + + Default implementation materializes the video into memory via + `get_components()`. Subclasses that can inspect the underlying + container (e.g. `VideoFromFile`) should override this with a more + efficient implementation. + + Returns: + Frame rate as a Fraction. + """ + return self.get_components().frame_rate + + def get_container_format(self) -> str: + """ + Returns the container format of the video (e.g., 'mp4', 'mov', 'avi'). + + Returns: + Container format as string + """ + # Default implementation - subclasses should override for better performance + source = self.get_stream_source() + with av.open(source, mode="r") as container: + return container.format.name diff --git a/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py new file mode 100644 index 00000000..a3d48c87 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___input_impl__video_types.py @@ -0,0 +1,464 @@ +from __future__ import annotations +from av.container import InputContainer +from av.subtitles.stream import SubtitleStream +from fractions import Fraction +from typing import Optional +from .._input import AudioInput, VideoInput +import av +import io +import itertools +import json +import numpy as np +import math +import torch +from .._util import VideoContainer, VideoCodec, VideoComponents + + +def container_to_output_format(container_format: str | None) -> str | None: + """ + A container's `format` may be a comma-separated list of formats. + E.g., iso container's `format` may be `mov,mp4,m4a,3gp,3g2,mj2`. + However, writing to a file/stream with `av.open` requires a single format, + or `None` to auto-detect. + """ + if not container_format: + return None # Auto-detect + + if "," not in container_format: + return container_format + + formats = container_format.split(",") + return formats[0] + +def get_open_write_kwargs( + dest: str | io.BytesIO, container_format: str, to_format: str | None +) -> dict: + """Get kwargs for writing a `VideoFromFile` to a file/stream with `av.open`""" + open_kwargs = { + "mode": "w", + # If isobmff, preserve custom metadata tags (workflow, prompt, extra_pnginfo) + "options": {"movflags": "use_metadata_tags"}, + } + + is_write_to_buffer = isinstance(dest, io.BytesIO) + if is_write_to_buffer: + # Set output format explicitly, since it cannot be inferred from file extension + if to_format == VideoContainer.AUTO: + to_format = container_format.lower() + elif isinstance(to_format, str): + to_format = to_format.lower() + open_kwargs["format"] = container_to_output_format(to_format) + + return open_kwargs + + +class VideoFromFile(VideoInput): + """ + Class representing video input from a file. + """ + + def __init__(self, file: str | io.BytesIO, *, start_time: float=0, duration: float=0): + """ + Initialize the VideoFromFile object based off of either a path on disk or a BytesIO object + containing the file contents. + """ + self.__file = file + self.__start_time = start_time + self.__duration = duration + + def get_stream_source(self) -> str | io.BytesIO: + """ + Return the underlying file source for efficient streaming. + This avoids unnecessary memory copies when the source is already a file path. + """ + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + return self.__file + + def get_dimensions(self) -> tuple[int, int]: + """ + Returns the dimensions of the video input. + + Returns: + Tuple of (width, height) + """ + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) # Reset the BytesIO object to the beginning + with av.open(self.__file, mode='r') as container: + for stream in container.streams: + if stream.type == 'video': + assert isinstance(stream, av.VideoStream) + return stream.width, stream.height + raise ValueError(f"No video stream found in file '{self.__file}'") + + def get_duration(self) -> float: + """ + Returns the duration of the video in seconds. + + Returns: + Duration in seconds + """ + raw_duration = self._get_raw_duration() + if self.__start_time < 0: + duration_from_start = min(raw_duration, -self.__start_time) + else: + duration_from_start = raw_duration - self.__start_time + if self.__duration: + return min(self.__duration, duration_from_start) + return duration_from_start + + def _get_raw_duration(self) -> float: + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + with av.open(self.__file, mode="r") as container: + if container.duration is not None: + return float(container.duration / av.time_base) + + # Fallback: calculate from frame count and frame rate + video_stream = next( + (s for s in container.streams if s.type == "video"), None + ) + if video_stream and video_stream.frames and video_stream.average_rate: + return float(video_stream.frames / video_stream.average_rate) + + # Last resort: decode frames to count them + if video_stream and video_stream.average_rate: + frame_count = 0 + container.seek(0) + frame_iterator = ( + container.decode(video_stream) + if video_stream.codec.capabilities & 0x100 + else container.demux(video_stream) + ) + for packet in frame_iterator: + frame_count += 1 + if frame_count > 0: + return float(frame_count / video_stream.average_rate) + + raise ValueError(f"Could not determine duration for file '{self.__file}'") + + def get_frame_count(self) -> int: + """ + Returns the number of frames in the video without materializing them as + torch tensors. + """ + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + + with av.open(self.__file, mode="r") as container: + video_stream = self._get_first_video_stream(container) + # 1. Prefer the frames field if available and usable + if ( + video_stream.frames + and video_stream.frames > 0 + and not self.__start_time + and not self.__duration + ): + return int(video_stream.frames) + + # 2. Try to estimate from duration and average_rate using only metadata + if ( + getattr(video_stream, "duration", None) is not None + and getattr(video_stream, "time_base", None) is not None + and video_stream.average_rate + ): + raw_duration = float(video_stream.duration * video_stream.time_base) + if self.__start_time < 0: + duration_from_start = min(raw_duration, -self.__start_time) + else: + duration_from_start = raw_duration - self.__start_time + duration_seconds = min(self.__duration, duration_from_start) + estimated_frames = int(round(duration_seconds * float(video_stream.average_rate))) + if estimated_frames > 0: + return estimated_frames + + # 3. Last resort: decode frames and count them (streaming) + if self.__start_time < 0: + start_time = max(self._get_raw_duration() + self.__start_time, 0) + else: + start_time = self.__start_time + frame_count = 1 + start_pts = int(start_time / video_stream.time_base) + end_pts = int((start_time + self.__duration) / video_stream.time_base) + container.seek(start_pts, stream=video_stream) + frame_iterator = ( + container.decode(video_stream) + if video_stream.codec.capabilities & 0x100 + else container.demux(video_stream) + ) + for frame in frame_iterator: + if frame.pts >= start_pts: + break + else: + raise ValueError(f"Could not determine frame count for file '{self.__file}'\nNo frames exist for start_time {self.__start_time}") + for frame in frame_iterator: + if frame.pts >= end_pts: + break + frame_count += 1 + return frame_count + + def get_frame_rate(self) -> Fraction: + """ + Returns the average frame rate of the video using container metadata + without decoding all frames. + """ + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + + with av.open(self.__file, mode="r") as container: + video_stream = self._get_first_video_stream(container) + # Preferred: use PyAV's average_rate (usually already a Fraction-like) + if video_stream.average_rate: + return Fraction(video_stream.average_rate) + + # Fallback: estimate from frames + duration if available + if video_stream.frames and container.duration: + duration_seconds = float(container.duration / av.time_base) + if duration_seconds > 0: + return Fraction(video_stream.frames / duration_seconds).limit_denominator() + + # Last resort: match get_components_internal default + return Fraction(1) + + def get_container_format(self) -> str: + """ + Returns the container format of the video (e.g., 'mp4', 'mov', 'avi'). + + Returns: + Container format as string + """ + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) + with av.open(self.__file, mode='r') as container: + return container.format.name + + def get_components_internal(self, container: InputContainer) -> VideoComponents: + video_stream = self._get_first_video_stream(container) + if self.__start_time < 0: + start_time = max(self._get_raw_duration() + self.__start_time, 0) + else: + start_time = self.__start_time + # Get video frames + frames = [] + start_pts = int(start_time / video_stream.time_base) + end_pts = int((start_time + self.__duration) / video_stream.time_base) + container.seek(start_pts, stream=video_stream) + for frame in container.decode(video_stream): + if frame.pts < start_pts: + continue + if self.__duration and frame.pts >= end_pts: + break + img = frame.to_ndarray(format='rgb24') # shape: (H, W, 3) + img = torch.from_numpy(img) / 255.0 # shape: (H, W, 3) + frames.append(img) + + images = torch.stack(frames) if len(frames) > 0 else torch.zeros(0, 3, 0, 0) + + # Get frame rate + frame_rate = Fraction(video_stream.average_rate) if video_stream.average_rate else Fraction(1) + + # Get audio if available + audio = None + container.seek(start_pts, stream=video_stream) + # Use last stream for consistency + if len(container.streams.audio): + audio_stream = container.streams.audio[-1] + audio_frames = [] + resample = av.audio.resampler.AudioResampler(format='fltp').resample + frames = itertools.chain.from_iterable( + map(resample, container.decode(audio_stream)) + ) + + has_first_frame = False + for frame in frames: + offset_seconds = start_time - frame.pts * audio_stream.time_base + to_skip = int(offset_seconds * audio_stream.sample_rate) + if to_skip < frame.samples: + has_first_frame = True + break + if has_first_frame: + audio_frames.append(frame.to_ndarray()[..., to_skip:]) + + for frame in frames: + if frame.time > start_time + self.__duration: + break + audio_frames.append(frame.to_ndarray()) # shape: (channels, samples) + if len(audio_frames) > 0: + audio_data = np.concatenate(audio_frames, axis=1) # shape: (channels, total_samples) + if self.__duration: + audio_data = audio_data[..., :int(self.__duration * audio_stream.sample_rate)] + + audio_tensor = torch.from_numpy(audio_data).unsqueeze(0) # shape: (1, channels, total_samples) + audio = AudioInput({ + "waveform": audio_tensor, + "sample_rate": int(audio_stream.sample_rate) if audio_stream.sample_rate else 1, + }) + + metadata = container.metadata + return VideoComponents(images=images, audio=audio, frame_rate=frame_rate, metadata=metadata) + + def get_components(self) -> VideoComponents: + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) # Reset the BytesIO object to the beginning + with av.open(self.__file, mode='r') as container: + return self.get_components_internal(container) + raise ValueError(f"No video stream found in file '{self.__file}'") + + def save_to( + self, + path: str | io.BytesIO, + format: VideoContainer = VideoContainer.AUTO, + codec: VideoCodec = VideoCodec.AUTO, + metadata: Optional[dict] = None, + ): + if isinstance(self.__file, io.BytesIO): + self.__file.seek(0) # Reset the BytesIO object to the beginning + with av.open(self.__file, mode='r') as container: + container_format = container.format.name + video_encoding = container.streams.video[0].codec.name if len(container.streams.video) > 0 else None + reuse_streams = True + if format != VideoContainer.AUTO and format not in container_format.split(","): + reuse_streams = False + if codec != VideoCodec.AUTO and codec != video_encoding and video_encoding is not None: + reuse_streams = False + if self.__start_time or self.__duration: + reuse_streams = False + + if not reuse_streams: + components = self.get_components_internal(container) + video = VideoFromComponents(components) + return video.save_to( + path, format=format, codec=codec, metadata=metadata + ) + + streams = container.streams + + open_kwargs = get_open_write_kwargs(path, container_format, format) + with av.open(path, **open_kwargs) as output_container: + # Copy over the original metadata + for key, value in container.metadata.items(): + if metadata is None or key not in metadata: + output_container.metadata[key] = value + + # Add our new metadata + if metadata is not None: + for key, value in metadata.items(): + if isinstance(value, str): + output_container.metadata[key] = value + else: + output_container.metadata[key] = json.dumps(value) + + # Add streams to the new container + stream_map = {} + for stream in streams: + if isinstance(stream, (av.VideoStream, av.AudioStream, SubtitleStream)): + out_stream = output_container.add_stream_from_template(template=stream, opaque=True) + stream_map[stream] = out_stream + + # Write packets to the new container + for packet in container.demux(): + if packet.stream in stream_map and packet.dts is not None: + packet.stream = stream_map[packet.stream] + output_container.mux(packet) + + def _get_first_video_stream(self, container: InputContainer): + if len(container.streams.video): + return container.streams.video[0] + raise ValueError(f"No video stream found in file '{self.__file}'") + + def as_trimmed( + self, start_time: float = 0, duration: float = 0, strict_duration: bool = True + ) -> VideoInput | None: + trimmed = VideoFromFile( + self.get_stream_source(), + start_time=start_time + self.__start_time, + duration=duration, + ) + if trimmed.get_duration() < duration and strict_duration: + return None + return trimmed + + +class VideoFromComponents(VideoInput): + """ + Class representing video input from tensors. + """ + + def __init__(self, components: VideoComponents): + self.__components = components + + def get_components(self) -> VideoComponents: + return VideoComponents( + images=self.__components.images, + audio=self.__components.audio, + frame_rate=self.__components.frame_rate, + ) + + def save_to( + self, + path: str, + format: VideoContainer = VideoContainer.AUTO, + codec: VideoCodec = VideoCodec.AUTO, + metadata: Optional[dict] = None, + ): + if format != VideoContainer.AUTO and format != VideoContainer.MP4: + raise ValueError("Only MP4 format is supported for now") + if codec != VideoCodec.AUTO and codec != VideoCodec.H264: + raise ValueError("Only H264 codec is supported for now") + extra_kwargs = {} + if isinstance(format, VideoContainer) and format != VideoContainer.AUTO: + extra_kwargs["format"] = format.value + with av.open(path, mode='w', options={'movflags': 'use_metadata_tags'}, **extra_kwargs) as output: + # Add metadata before writing any streams + if metadata is not None: + for key, value in metadata.items(): + output.metadata[key] = json.dumps(value) + + frame_rate = Fraction(round(self.__components.frame_rate * 1000), 1000) + # Create a video stream + video_stream = output.add_stream('h264', rate=frame_rate) + video_stream.width = self.__components.images.shape[2] + video_stream.height = self.__components.images.shape[1] + video_stream.pix_fmt = 'yuv420p' + + # Create an audio stream + audio_sample_rate = 1 + audio_stream: Optional[av.AudioStream] = None + if self.__components.audio: + audio_sample_rate = int(self.__components.audio['sample_rate']) + waveform = self.__components.audio['waveform'] + waveform = waveform[0, :, :math.ceil((audio_sample_rate / frame_rate) * self.__components.images.shape[0])] + layout = {1: 'mono', 2: 'stereo', 6: '5.1'}.get(waveform.shape[0], 'stereo') + audio_stream = output.add_stream('aac', rate=audio_sample_rate, layout=layout) + + # Encode video + for i, frame in enumerate(self.__components.images): + img = (frame * 255).clamp(0, 255).byte().cpu().numpy() # shape: (H, W, 3) + frame = av.VideoFrame.from_ndarray(img, format='rgb24') + frame = frame.reformat(format='yuv420p') # Convert to YUV420P as required by h264 + packet = video_stream.encode(frame) + output.mux(packet) + + # Flush video + packet = video_stream.encode(None) + output.mux(packet) + + if audio_stream and self.__components.audio: + frame = av.AudioFrame.from_ndarray(waveform.float().cpu().contiguous().numpy(), format='fltp', layout=layout) + frame.sample_rate = audio_sample_rate + frame.pts = 0 + output.mux(audio_stream.encode(frame)) + + # Flush encoder + output.mux(audio_stream.encode(None)) + + def as_trimmed( + self, + start_time: float | None = None, + duration: float | None = None, + strict_duration: bool = True, + ) -> VideoInput | None: + if self.get_duration() < start_time + duration: + return None + #TODO Consider tracking duration and trimming at time of save? + return VideoFromFile(self.get_stream_source(), start_time=start_time, duration=duration) diff --git a/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util____init__.py b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util____init__.py new file mode 100644 index 00000000..115baf39 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util____init__.py @@ -0,0 +1,14 @@ +from .video_types import VideoContainer, VideoCodec, VideoComponents +from .geometry_types import VOXEL, MESH, File3D +from .image_types import SVG + +__all__ = [ + # Utility Types + "VideoContainer", + "VideoCodec", + "VideoComponents", + "VOXEL", + "MESH", + "File3D", + "SVG", +] diff --git a/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util__video_types.py b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util__video_types.py new file mode 100644 index 00000000..fd3b5a51 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__comfy_api__latest___util__video_types.py @@ -0,0 +1,52 @@ +from __future__ import annotations +from dataclasses import dataclass +from enum import Enum +from fractions import Fraction +from typing import Optional +from .._input import ImageInput, AudioInput + +class VideoCodec(str, Enum): + AUTO = "auto" + H264 = "h264" + + @classmethod + def as_input(cls) -> list[str]: + """ + Returns a list of codec names that can be used as node input. + """ + return [member.value for member in cls] + +class VideoContainer(str, Enum): + AUTO = "auto" + MP4 = "mp4" + + @classmethod + def as_input(cls) -> list[str]: + """ + Returns a list of container names that can be used as node input. + """ + return [member.value for member in cls] + + @classmethod + def get_extension(cls, value) -> str: + """ + Returns the file extension for the container. + """ + if isinstance(value, str): + value = cls(value) + if value == VideoContainer.MP4 or value == VideoContainer.AUTO: + return "mp4" + return "" + +@dataclass +class VideoComponents: + """ + Dataclass representing the components of a video. + """ + + images: ImageInput + frame_rate: Fraction + audio: Optional[AudioInput] = None + metadata: Optional[dict] = None + + diff --git a/docs/hel-892/sdpose-reference/core0151__comfy_extras__nodes_video.py b/docs/hel-892/sdpose-reference/core0151__comfy_extras__nodes_video.py new file mode 100644 index 00000000..5c096c23 --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__comfy_extras__nodes_video.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +import os +import av +import torch +import folder_paths +import json +from typing import Optional +from typing_extensions import override +from fractions import Fraction +from comfy_api.latest import ComfyExtension, io, ui, Input, InputImpl, Types +from comfy.cli_args import args + +class SaveWEBM(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SaveWEBM", + search_aliases=["export webm"], + category="image/video", + is_experimental=True, + inputs=[ + io.Image.Input("images"), + io.String.Input("filename_prefix", default="ComfyUI"), + io.Combo.Input("codec", options=["vp9", "av1"]), + io.Float.Input("fps", default=24.0, min=0.01, max=1000.0, step=0.01), + io.Float.Input("crf", default=32.0, min=0, max=63.0, step=1, tooltip="Higher crf means lower quality with a smaller file size, lower crf means higher quality higher filesize."), + ], + hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo], + is_output_node=True, + ) + + @classmethod + def execute(cls, images, codec, fps, filename_prefix, crf) -> io.NodeOutput: + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path( + filename_prefix, folder_paths.get_output_directory(), images[0].shape[1], images[0].shape[0] + ) + + file = f"{filename}_{counter:05}_.webm" + container = av.open(os.path.join(full_output_folder, file), mode="w") + + if cls.hidden.prompt is not None: + container.metadata["prompt"] = json.dumps(cls.hidden.prompt) + + if cls.hidden.extra_pnginfo is not None: + for x in cls.hidden.extra_pnginfo: + container.metadata[x] = json.dumps(cls.hidden.extra_pnginfo[x]) + + codec_map = {"vp9": "libvpx-vp9", "av1": "libsvtav1"} + stream = container.add_stream(codec_map[codec], rate=Fraction(round(fps * 1000), 1000)) + stream.width = images.shape[-2] + stream.height = images.shape[-3] + stream.pix_fmt = "yuv420p10le" if codec == "av1" else "yuv420p" + stream.bit_rate = 0 + stream.options = {'crf': str(crf)} + if codec == "av1": + stream.options["preset"] = "6" + + for frame in images: + frame = av.VideoFrame.from_ndarray(torch.clamp(frame[..., :3] * 255, min=0, max=255).to(device=torch.device("cpu"), dtype=torch.uint8).numpy(), format="rgb24") + for packet in stream.encode(frame): + container.mux(packet) + container.mux(stream.encode()) + container.close() + + return io.NodeOutput(ui=ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.output)])) + +class SaveVideo(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SaveVideo", + search_aliases=["export video"], + display_name="Save Video", + category="image/video", + essentials_category="Basics", + description="Saves the input images to your ComfyUI output directory.", + inputs=[ + io.Video.Input("video", tooltip="The video to save."), + io.String.Input("filename_prefix", default="video/ComfyUI", tooltip="The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."), + io.Combo.Input("format", options=Types.VideoContainer.as_input(), default="auto", tooltip="The format to save the video as."), + io.Combo.Input("codec", options=Types.VideoCodec.as_input(), default="auto", tooltip="The codec to use for the video."), + ], + hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo], + is_output_node=True, + ) + + @classmethod + def execute(cls, video: Input.Video, filename_prefix, format: str, codec) -> io.NodeOutput: + width, height = video.get_dimensions() + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path( + filename_prefix, + folder_paths.get_output_directory(), + width, + height + ) + saved_metadata = None + if not args.disable_metadata: + metadata = {} + if cls.hidden.extra_pnginfo is not None: + metadata.update(cls.hidden.extra_pnginfo) + if cls.hidden.prompt is not None: + metadata["prompt"] = cls.hidden.prompt + if len(metadata) > 0: + saved_metadata = metadata + file = f"{filename}_{counter:05}_.{Types.VideoContainer.get_extension(format)}" + video.save_to( + os.path.join(full_output_folder, file), + format=Types.VideoContainer(format), + codec=codec, + metadata=saved_metadata + ) + + return io.NodeOutput(ui=ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.output)])) + + +class CreateVideo(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="CreateVideo", + search_aliases=["images to video"], + display_name="Create Video", + category="image/video", + description="Create a video from images.", + inputs=[ + io.Image.Input("images", tooltip="The images to create a video from."), + io.Float.Input("fps", default=30.0, min=1.0, max=120.0, step=1.0), + io.Audio.Input("audio", optional=True, tooltip="The audio to add to the video."), + ], + outputs=[ + io.Video.Output(), + ], + ) + + @classmethod + def execute(cls, images: Input.Image, fps: float, audio: Optional[Input.Audio] = None) -> io.NodeOutput: + return io.NodeOutput( + InputImpl.VideoFromComponents(Types.VideoComponents(images=images, audio=audio, frame_rate=Fraction(fps))) + ) + +class GetVideoComponents(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="GetVideoComponents", + search_aliases=["extract frames", "split video", "video to images", "demux"], + display_name="Get Video Components", + category="image/video", + description="Extracts all components from a video: frames, audio, and framerate.", + inputs=[ + io.Video.Input("video", tooltip="The video to extract components from."), + ], + outputs=[ + io.Image.Output(display_name="images"), + io.Audio.Output(display_name="audio"), + io.Float.Output(display_name="fps"), + ], + ) + + @classmethod + def execute(cls, video: Input.Video) -> io.NodeOutput: + components = video.get_components() + return io.NodeOutput(components.images, components.audio, float(components.frame_rate)) + + +class LoadVideo(io.ComfyNode): + @classmethod + def define_schema(cls): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] + files = folder_paths.filter_files_content_types(files, ["video"]) + return io.Schema( + node_id="LoadVideo", + search_aliases=["import video", "open video", "video file"], + display_name="Load Video", + category="image/video", + essentials_category="Basics", + inputs=[ + io.Combo.Input("file", options=sorted(files), upload=io.UploadType.video), + ], + outputs=[ + io.Video.Output(), + ], + ) + + @classmethod + def execute(cls, file) -> io.NodeOutput: + video_path = folder_paths.get_annotated_filepath(file) + return io.NodeOutput(InputImpl.VideoFromFile(video_path)) + + @classmethod + def fingerprint_inputs(s, file): + video_path = folder_paths.get_annotated_filepath(file) + mod_time = os.path.getmtime(video_path) + # Instead of hashing the file, we can just use the modification time to avoid + # rehashing large files. + return mod_time + + @classmethod + def validate_inputs(s, file): + if not folder_paths.exists_annotated_filepath(file): + return "Invalid video file: {}".format(file) + + return True + +class VideoSlice(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="Video Slice", + display_name="Video Slice", + search_aliases=[ + "trim video duration", + "skip first frames", + "frame load cap", + "start time", + ], + category="image/video", + essentials_category="Video Tools", + inputs=[ + io.Video.Input("video"), + io.Float.Input( + "start_time", + default=0.0, + max=1e5, + min=-1e5, + step=0.001, + tooltip="Start time in seconds", + ), + io.Float.Input( + "duration", + default=0.0, + min=0.0, + step=0.001, + tooltip="Duration in seconds, or 0 for unlimited duration", + ), + io.Boolean.Input( + "strict_duration", + default=False, + tooltip="If True, when the specified duration is not possible, an error will be raised.", + ), + ], + outputs=[ + io.Video.Output(), + ], + ) + + @classmethod + def execute(cls, video: io.Video.Type, start_time: float, duration: float, strict_duration: bool) -> io.NodeOutput: + trimmed = video.as_trimmed(start_time, duration, strict_duration=strict_duration) + if trimmed is not None: + return io.NodeOutput(trimmed) + raise ValueError( + f"Failed to slice video:\nSource duration: {video.get_duration()}\nStart time: {start_time}\nTarget duration: {duration}" + ) + + +class VideoExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + SaveWEBM, + SaveVideo, + CreateVideo, + GetVideoComponents, + LoadVideo, + VideoSlice, + ] + +async def comfy_entrypoint() -> VideoExtension: + return VideoExtension() diff --git a/docs/hel-892/sdpose-reference/core0151__folder_paths.py b/docs/hel-892/sdpose-reference/core0151__folder_paths.py new file mode 100644 index 00000000..9c96540e --- /dev/null +++ b/docs/hel-892/sdpose-reference/core0151__folder_paths.py @@ -0,0 +1,496 @@ +from __future__ import annotations + +import os +import time +import mimetypes +import logging +from typing import Literal, List +from collections.abc import Collection + +from comfy.cli_args import args + +supported_pt_extensions: set[str] = {'.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'} + +folder_names_and_paths: dict[str, tuple[list[str], set[str]]] = {} + +# --base-directory - Resets all default paths configured in folder_paths with a new base path +if args.base_directory: + base_path = os.path.abspath(args.base_directory) +else: + base_path = os.path.dirname(os.path.realpath(__file__)) + +models_dir = os.path.join(base_path, "models") +folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions) +folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"]) + +folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions) +folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions) +folder_names_and_paths["text_encoders"] = ([os.path.join(models_dir, "text_encoders"), os.path.join(models_dir, "clip")], supported_pt_extensions) +folder_names_and_paths["diffusion_models"] = ([os.path.join(models_dir, "unet"), os.path.join(models_dir, "diffusion_models")], supported_pt_extensions) +folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions) +folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions) +folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions) +folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"]) +folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions) + +folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions) +folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions) + +folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions) + +folder_names_and_paths["latent_upscale_models"] = ([os.path.join(models_dir, "latent_upscale_models")], supported_pt_extensions) + +folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set()) + +folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions) + +folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions) + +folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")], {""}) + +folder_names_and_paths["model_patches"] = ([os.path.join(models_dir, "model_patches")], supported_pt_extensions) + +folder_names_and_paths["audio_encoders"] = ([os.path.join(models_dir, "audio_encoders")], supported_pt_extensions) + +output_directory = os.path.join(base_path, "output") +temp_directory = os.path.join(base_path, "temp") +input_directory = os.path.join(base_path, "input") +user_directory = os.path.join(base_path, "user") + +filename_list_cache: dict[str, tuple[list[str], dict[str, float], float]] = {} + +class CacheHelper: + """ + Helper class for managing file list cache data. + """ + def __init__(self): + self.cache: dict[str, tuple[list[str], dict[str, float], float]] = {} + self.active = False + + def get(self, key: str, default=None) -> tuple[list[str], dict[str, float], float]: + if not self.active: + return default + return self.cache.get(key, default) + + def set(self, key: str, value: tuple[list[str], dict[str, float], float]) -> None: + if self.active: + self.cache[key] = value + + def clear(self): + self.cache.clear() + + def __enter__(self): + self.active = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.active = False + self.clear() + +cache_helper = CacheHelper() + +extension_mimetypes_cache = { + "webp" : "image", + "fbx" : "model", +} + +def map_legacy(folder_name: str) -> str: + legacy = {"unet": "diffusion_models", + "clip": "text_encoders"} + return legacy.get(folder_name, folder_name) + +if not os.path.exists(input_directory): + try: + os.makedirs(input_directory) + except: + logging.error("Failed to create input directory") + +def set_output_directory(output_dir: str) -> None: + global output_directory + output_directory = output_dir + +def set_temp_directory(temp_dir: str) -> None: + global temp_directory + temp_directory = temp_dir + +def set_input_directory(input_dir: str) -> None: + global input_directory + input_directory = input_dir + +def get_output_directory() -> str: + global output_directory + return output_directory + +def get_temp_directory() -> str: + global temp_directory + return temp_directory + +def get_input_directory() -> str: + global input_directory + return input_directory + +def get_user_directory() -> str: + return user_directory + +def set_user_directory(user_dir: str) -> None: + global user_directory + user_directory = user_dir + + +# System User Protection - Protects system directories from HTTP endpoint access +# System Users are internal-only users that cannot be accessed via HTTP endpoints. +# They use the '__' prefix convention (similar to Python's private member convention). +SYSTEM_USER_PREFIX = "__" + + +def get_system_user_directory(name: str = "system") -> str: + """ + Get the path to a System User directory. + + System User directories (prefixed with '__') are only accessible via internal API, + not through HTTP endpoints. Use this for storing system-internal data that + should not be exposed to users. + + Args: + name: System user name (e.g., "system", "cache"). Must be alphanumeric + with underscores allowed, but cannot start with underscore. + + Returns: + Absolute path to the system user directory. + + Raises: + ValueError: If name is empty, invalid, or starts with underscore. + + Example: + >>> get_system_user_directory("cache") + '/path/to/user/__cache' + """ + if not name or not isinstance(name, str): + raise ValueError("System user name cannot be empty") + if not name.replace("_", "").isalnum(): + raise ValueError(f"Invalid system user name: '{name}'") + if name.startswith("_"): + raise ValueError("System user name should not start with underscore") + return os.path.join(get_user_directory(), f"{SYSTEM_USER_PREFIX}{name}") + + +def get_public_user_directory(user_id: str) -> str | None: + """ + Get the path to a Public User directory for HTTP endpoint access. + + This function provides structural security by returning None for any + System User (prefixed with '__'). All HTTP endpoints should use this + function instead of directly constructing user paths. + + Args: + user_id: User identifier from HTTP request. + + Returns: + Absolute path to the user directory, or None if user_id is invalid + or refers to a System User. + + Example: + >>> get_public_user_directory("default") + '/path/to/user/default' + >>> get_public_user_directory("__system") + None + """ + if not user_id or not isinstance(user_id, str): + return None + if user_id.startswith(SYSTEM_USER_PREFIX): + return None + return os.path.join(get_user_directory(), user_id) + + +#NOTE: used in http server so don't put folders that should not be accessed remotely +def get_directory_by_type(type_name: str) -> str | None: + if type_name == "output": + return get_output_directory() + if type_name == "temp": + return get_temp_directory() + if type_name == "input": + return get_input_directory() + return None + +def filter_files_content_types(files: list[str], content_types: List[Literal["image", "video", "audio", "model"]]) -> list[str]: + """ + Example: + files = os.listdir(folder_paths.get_input_directory()) + videos = filter_files_content_types(files, ["video"]) + + Note: + - 'model' in MIME context refers to 3D models, not files containing trained weights and parameters + """ + global extension_mimetypes_cache + result = [] + for file in files: + extension = file.split('.')[-1] + if extension not in extension_mimetypes_cache: + mime_type, _ = mimetypes.guess_type(file, strict=False) + if not mime_type: + continue + content_type = mime_type.split('/')[0] + extension_mimetypes_cache[extension] = content_type + else: + content_type = extension_mimetypes_cache[extension] + + if content_type in content_types: + result.append(file) + return result + +# determine base_dir rely on annotation if name is 'filename.ext [annotation]' format +# otherwise use default_path as base_dir +def annotated_filepath(name: str) -> tuple[str, str | None]: + if name.endswith("[output]"): + base_dir = get_output_directory() + name = name[:-9] + elif name.endswith("[input]"): + base_dir = get_input_directory() + name = name[:-8] + elif name.endswith("[temp]"): + base_dir = get_temp_directory() + name = name[:-7] + else: + return name, None + + return name, base_dir + + +def get_annotated_filepath(name: str, default_dir: str | None=None) -> str: + name, base_dir = annotated_filepath(name) + + if base_dir is None: + if default_dir is not None: + base_dir = default_dir + else: + base_dir = get_input_directory() # fallback path + + return os.path.join(base_dir, name) + + +def exists_annotated_filepath(name) -> bool: + name, base_dir = annotated_filepath(name) + + if base_dir is None: + base_dir = get_input_directory() # fallback path + + filepath = os.path.join(base_dir, name) + return os.path.exists(filepath) + + +def add_model_folder_path(folder_name: str, full_folder_path: str, is_default: bool = False) -> None: + global folder_names_and_paths + folder_name = map_legacy(folder_name) + if folder_name in folder_names_and_paths: + paths, _exts = folder_names_and_paths[folder_name] + if full_folder_path in paths: + if is_default and paths[0] != full_folder_path: + # If the path to the folder is not the first in the list, move it to the beginning. + paths.remove(full_folder_path) + paths.insert(0, full_folder_path) + else: + if is_default: + paths.insert(0, full_folder_path) + else: + paths.append(full_folder_path) + else: + folder_names_and_paths[folder_name] = ([full_folder_path], set()) + +def get_folder_paths(folder_name: str) -> list[str]: + folder_name = map_legacy(folder_name) + return folder_names_and_paths[folder_name][0][:] + +def recursive_search(directory: str, excluded_dir_names: list[str] | None=None) -> tuple[list[str], dict[str, float]]: + if not os.path.isdir(directory): + return [], {} + + if excluded_dir_names is None: + excluded_dir_names = [] + + result = [] + dirs = {} + + # Attempt to add the initial directory to dirs with error handling + try: + dirs[directory] = os.path.getmtime(directory) + except FileNotFoundError: + logging.warning(f"Warning: Unable to access {directory}. Skipping this path.") + + logging.debug("recursive file list on directory {}".format(directory)) + dirpath: str + subdirs: list[str] + filenames: list[str] + + for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True): + subdirs[:] = [d for d in subdirs if d not in excluded_dir_names] + for file_name in filenames: + try: + relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory) + result.append(relative_path) + except: + logging.warning(f"Warning: Unable to access {file_name}. Skipping this file.") + continue + + for d in subdirs: + path: str = os.path.join(dirpath, d) + try: + dirs[path] = os.path.getmtime(path) + except FileNotFoundError: + logging.warning(f"Warning: Unable to access {path}. Skipping this path.") + continue + logging.debug("found {} files".format(len(result))) + return result, dirs + +def filter_files_extensions(files: Collection[str], extensions: Collection[str]) -> list[str]: + return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files))) + + + +def get_full_path(folder_name: str, filename: str) -> str | None: + """ + Get the full path of a file in a folder, has to be a file + """ + global folder_names_and_paths + folder_name = map_legacy(folder_name) + if folder_name not in folder_names_and_paths: + return None + folders = folder_names_and_paths[folder_name] + filename = os.path.relpath(os.path.join("/", filename), "/") + for x in folders[0]: + full_path = os.path.join(x, filename) + if os.path.isfile(full_path): + return full_path + elif os.path.islink(full_path): + logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path)) + + return None + + +def get_full_path_or_raise(folder_name: str, filename: str) -> str: + """ + Get the full path of a file in a folder, has to be a file + """ + full_path = get_full_path(folder_name, filename) + if full_path is None: + raise FileNotFoundError(f"Model in folder '{folder_name}' with filename '{filename}' not found.") + return full_path + + +def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]: + folder_name = map_legacy(folder_name) + global folder_names_and_paths + output_list = set() + folders = folder_names_and_paths[folder_name] + output_folders = {} + for x in folders[0]: + files, folders_all = recursive_search(x, excluded_dir_names=[".git"]) + output_list.update(filter_files_extensions(files, folders[1])) + output_folders = {**output_folders, **folders_all} + + return sorted(list(output_list)), output_folders, time.perf_counter() + +def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None: + strong_cache = cache_helper.get(folder_name) + if strong_cache is not None: + return strong_cache + + global filename_list_cache + global folder_names_and_paths + folder_name = map_legacy(folder_name) + if folder_name not in filename_list_cache: + return None + out = filename_list_cache[folder_name] + + for x in out[1]: + time_modified = out[1][x] + folder = x + if os.path.getmtime(folder) != time_modified: + return None + + folders = folder_names_and_paths[folder_name] + for x in folders[0]: + if os.path.isdir(x): + if x not in out[1]: + return None + + return out + +def get_filename_list(folder_name: str) -> list[str]: + folder_name = map_legacy(folder_name) + out = cached_filename_list_(folder_name) + if out is None: + out = get_filename_list_(folder_name) + global filename_list_cache + filename_list_cache[folder_name] = out + cache_helper.set(folder_name, out) + return list(out[0]) + +def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]: + def map_filename(filename: str) -> tuple[int, str]: + prefix_len = len(os.path.basename(filename_prefix)) + prefix = filename[:prefix_len + 1] + try: + digits = int(filename[prefix_len + 1:].split('_')[0]) + except: + digits = 0 + return digits, prefix + + def compute_vars(input: str, image_width: int, image_height: int) -> str: + input = input.replace("%width%", str(image_width)) + input = input.replace("%height%", str(image_height)) + now = time.localtime() + input = input.replace("%year%", str(now.tm_year)) + input = input.replace("%month%", str(now.tm_mon).zfill(2)) + input = input.replace("%day%", str(now.tm_mday).zfill(2)) + input = input.replace("%hour%", str(now.tm_hour).zfill(2)) + input = input.replace("%minute%", str(now.tm_min).zfill(2)) + input = input.replace("%second%", str(now.tm_sec).zfill(2)) + return input + + if "%" in filename_prefix: + filename_prefix = compute_vars(filename_prefix, image_width, image_height) + + subfolder = os.path.dirname(os.path.normpath(filename_prefix)) + filename = os.path.basename(os.path.normpath(filename_prefix)) + + full_output_folder = os.path.join(output_dir, subfolder) + + if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir: + err = "**** ERROR: Saving image outside the output folder is not allowed." + \ + "\n full_output_folder: " + os.path.abspath(full_output_folder) + \ + "\n output_dir: " + output_dir + \ + "\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) + logging.error(err) + raise Exception(err) + + try: + counter = max(filter(lambda a: os.path.normcase(a[1][:-1]) == os.path.normcase(filename) and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1 + except ValueError: + counter = 1 + except FileNotFoundError: + os.makedirs(full_output_folder, exist_ok=True) + counter = 1 + return full_output_folder, filename, counter, subfolder, filename_prefix + +def get_input_subfolders() -> list[str]: + """Returns a list of all subfolder paths in the input directory, recursively. + + Returns: + List of folder paths relative to the input directory, excluding the root directory + """ + input_dir = get_input_directory() + folders = [] + + try: + if not os.path.exists(input_dir): + return [] + + for root, dirs, _ in os.walk(input_dir): + rel_path = os.path.relpath(root, input_dir) + if rel_path != ".": # Only include non-root directories + # Normalize path separators to forward slashes + folders.append(rel_path.replace(os.sep, '/')) + + return sorted(folders) + except FileNotFoundError: + return [] diff --git a/docs/hel-892/sdpose-reference/frontend-commit.json b/docs/hel-892/sdpose-reference/frontend-commit.json new file mode 100644 index 00000000..5525548d --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend-commit.json @@ -0,0 +1 @@ +{"sha":"d91c283b7b758787b4d29126c1a9ac39dc14d6a7","node_id":"C_kwDOMIrOxtoAKGQ5MWMyODNiN2I3NTg3ODdiNGQyOTEyNmMxYTlhYzM5ZGMxNGQ2YTc","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/d91c283b7b758787b4d29126c1a9ac39dc14d6a7","html_url":"https://github.com/Comfy-Org/ComfyUI_frontend/commit/d91c283b7b758787b4d29126c1a9ac39dc14d6a7","author":{"name":"Comfy Org PR Bot","email":"snomiao+comfy-pr@gmail.com","date":"2026-02-26T01:58:37Z"},"committer":{"name":"GitHub","email":"noreply@github.com","date":"2026-02-26T01:58:37Z"},"tree":{"sha":"1ab8f2711eae0b72039707d5b12bd4e91ed555cb","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/trees/1ab8f2711eae0b72039707d5b12bd4e91ed555cb"},"message":"1.39.19 (#9228)\n\nPatch version increment to 1.39.19\n\n**Base branch:** `core/1.39`\n\n┆Issue is synchronized with this [Notion\npage](https://www.notion.so/PR-9228-1-39-19-3136d73d365081c6bc75e2ec6b293254)\nby [Unito](https://www.unito.io)\n\nCo-authored-by: christian-byrne <72887196+christian-byrne@users.noreply.github.com>","parents":[{"sha":"7482ae1849d89de6b2257676f260092b7932fb08","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/7482ae1849d89de6b2257676f260092b7932fb08","html_url":"https://github.com/Comfy-Org/ComfyUI_frontend/commit/7482ae1849d89de6b2257676f260092b7932fb08"}],"verification":{"verified":true,"reason":"valid","signature":"-----BEGIN PGP SIGNATURE-----\n\nwsFcBAABCAAQBQJpn6jOCRC1aQ7uu5UhlAAAD7AQABbC5lsLE6WVprExfB621mVz\nr+yghHkxyg1v0cCqvborunE1TsKOB5XfWvoz/FUc+I901xrBZC5bV5dt2OJTHHOb\n8895QT3WefzuJqk71lm+xZDkzAVnSpPk7qnWTvyf4O7q0GJk9Aaie9k9+JthSrLH\nTEu7q+lRbXazDEbZXO2z8NxaEvIbu+0B5lfRnEDW0l+sb4qPSpzsnjKI/nj5UttA\ntaLxsWuC7CSZlqtD/7emugZ92Op59am4YddqPRG8bEx0mJRNSxmvnbNJd14QicAU\n1lvhIGxPmz6RzTI5+XgsY2uD8IFjp65rbMjxlQc0jsomQLoVd+eLryr5kgMJ/Hnk\n6GFKW9VhOlrxYWS5nAsDbWTuxRbrfNTx1aQemp6RjO/Pgm4PRpxNZlXHOtP/v5lk\niA9dEPpmKoGi5keNSfd597HcBj9PIQdRgMPpqG6M/6cWJOs5Ehfq04RgfBVK9mqr\n3yTWVuikeNFTp6wPd0kzzrL6jUNCe3jMQtCvWegDmy85g9KGab1PzyI50fgCqjVP\nezZiHzUcfV+/vqjsRD5bCpmCpN/jJfmc8+8NqGa0+yrq8NQRv1xuWJv8O/Essnsj\nNzLuE6djayVu5UIdY4LJNvS+RK5seB/F/9A8XsWLI1RdHIK6O5Z1Xgw/pGKBgIPb\nXnRb6GdT+y8aq490G9Zd\n=/ABS\n-----END PGP SIGNATURE-----\n","payload":"tree 1ab8f2711eae0b72039707d5b12bd4e91ed555cb\nparent 7482ae1849d89de6b2257676f260092b7932fb08\nauthor Comfy Org PR Bot 1772071117 +0900\ncommitter GitHub 1772071117 -0800\n\n1.39.19 (#9228)\n\nPatch version increment to 1.39.19\n\n**Base branch:** `core/1.39`\n\n┆Issue is synchronized with this [Notion\npage](https://www.notion.so/PR-9228-1-39-19-3136d73d365081c6bc75e2ec6b293254)\nby [Unito](https://www.unito.io)\n\nCo-authored-by: christian-byrne <72887196+christian-byrne@users.noreply.github.com>","verified_at":"2026-02-26T01:58:38Z"}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/frontend-tag.json b/docs/hel-892/sdpose-reference/frontend-tag.json new file mode 100644 index 00000000..0dbb2d53 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend-tag.json @@ -0,0 +1 @@ +{"ref":"refs/tags/v1.39.19","node_id":"REF_kwDOMIrOxrJyZWZzL3RhZ3MvdjEuMzkuMTk","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/refs/tags/v1.39.19","object":{"sha":"d91c283b7b758787b4d29126c1a9ac39dc14d6a7","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/d91c283b7b758787b4d29126c1a9ac39dc14d6a7"}} \ No newline at end of file diff --git a/docs/hel-892/sdpose-reference/frontend__LICENSE b/docs/hel-892/sdpose-reference/frontend__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts b/docs/hel-892/sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts new file mode 100644 index 00000000..3058e813 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts @@ -0,0 +1,600 @@ +import { remove } from 'es-toolkit' +import { shallowReactive } from 'vue' + +import { useChainCallback } from '@/composables/functional/useChainCallback' +import type { + ISlotType, + INodeInputSlot, + INodeOutputSlot +} from '@/lib/litegraph/src/interfaces' +import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' +import { LiteGraph } from '@/lib/litegraph/src/litegraph' +import type { LLink } from '@/lib/litegraph/src/LLink' +import { commonType } from '@/lib/litegraph/src/utils/type' +import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration' +import type { ComboInputSpec, InputSpec } from '@/schemas/nodeDefSchema' +import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2' +import { + zAutogrowOptions, + zDynamicComboInputSpec +} from '@/schemas/nodeDefSchema' +import { useLitegraphService } from '@/services/litegraphService' +import { app } from '@/scripts/app' +import type { ComfyApp } from '@/scripts/app' + +const INLINE_INPUTS = false + +type MatchTypeNode = LGraphNode & + Pick, 'onConnectionsChange'> & { + comfyDynamic: { matchType: Record> } + } +type AutogrowNode = LGraphNode & + Pick, 'onConnectionsChange' | 'widgets'> & { + comfyDynamic: { + autogrow: Record< + string, + { + min: number + max: number + inputSpecs: InputSpecV2[] + prefix?: string + names?: string[] + } + > + } + } + +function ensureWidgetForInput(node: LGraphNode, input: INodeInputSlot) { + node.widgets ??= [] + const { widget } = input + if (widget && node.widgets.some((w) => w.name === widget.name)) return + node.widgets.push({ + draw(ctx, _n, _w, y) { + ctx.save() + ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR + ctx.fillText(input.label ?? input.name, 20, y + 15) + ctx.restore() + }, + name: input.name, + options: {}, + serialize: false, + type: 'shim', + y: 0 + }) + input.alwaysVisible = true + input.widget = { name: input.name } +} + +function dynamicComboWidget( + node: LGraphNode, + inputName: string, + untypedInputData: InputSpec, + appArg: ComfyApp, + widgetName?: string +) { + const { addNodeInput } = useLitegraphService() + const parseResult = zDynamicComboInputSpec.safeParse(untypedInputData) + if (!parseResult.success) throw new Error('invalid DynamicCombo spec') + const inputData = parseResult.data + const options = Object.fromEntries( + inputData[1].options.map(({ key, inputs }) => [key, inputs]) + ) + const subSpec: ComboInputSpec = [Object.keys(options), {}] + const { widget, minWidth, minHeight } = app.widgets['COMBO']( + node, + inputName, + subSpec, + appArg, + widgetName + ) + function isInGroup(e: { name: string }): boolean { + return e.name.startsWith(inputName + '.') + } + const updateWidgets = (value?: string) => { + if (!node.widgets) throw new Error('Not Reachable') + const newSpec = value ? options[value] : undefined + + const removedInputs = remove(node.inputs, isInGroup) + for (const widget of remove(node.widgets, isInGroup)) widget.onRemove?.() + + if (!newSpec) return + + const insertionPoint = node.widgets.findIndex((w) => w === widget) + 1 + const startingLength = node.widgets.length + const startingInputLength = node.inputs.length + + if (insertionPoint === 0) + throw new Error("Dynamic widget doesn't exist on node") + const inputTypes: (Record | undefined)[] = [ + newSpec.required, + newSpec.optional + ] + inputTypes.forEach((inputType, idx) => { + for (const key in inputType ?? {}) { + const name = `${widget.name}.${key}` + const specToAdd = transformInputSpecV1ToV2(inputType![key], { + name, + isOptional: idx !== 0 + }) + specToAdd.display_name = key + addNodeInput(node, specToAdd) + const newInputs = node.inputs + .slice(startingInputLength) + .filter((inp) => inp.name.startsWith(name)) + for (const newInput of newInputs) { + if (INLINE_INPUTS && !newInput.widget) + ensureWidgetForInput(node, newInput) + } + } + }) + + const inputInsertionPoint = + node.inputs.findIndex((i) => i.name === widget.name) + 1 + const addedWidgets = node.widgets.splice(startingLength) + node.widgets.splice(insertionPoint, 0, ...addedWidgets) + if (inputInsertionPoint === 0) { + if ( + addedWidgets.length === 0 && + node.inputs.length !== startingInputLength + ) + //input is inputOnly, but lacks an insertion point + throw new Error('Failed to find input socket for ' + widget.name) + return + } + const addedInputs = spliceInputs(node, startingInputLength).map( + (addedInput) => { + const existingInput = node.inputs.findIndex( + (existingInput) => addedInput.name === existingInput.name + ) + return existingInput === -1 + ? addedInput + : spliceInputs(node, existingInput, 1)[0] + } + ) + //assume existing inputs are in correct order + spliceInputs(node, inputInsertionPoint, 0, ...addedInputs) + + for (const input of removedInputs) { + const inputIndex = node.inputs.findIndex((inp) => inp.name === input.name) + if (inputIndex === -1) { + node.inputs.push(input) + node.removeInput(node.inputs.length - 1) + } else { + node.inputs[inputIndex].link = input.link + if (!input.link) continue + const link = node.graph?.links?.[input.link] + if (!link) continue + link.target_slot = inputIndex + node.onConnectionsChange?.( + LiteGraph.INPUT, + inputIndex, + true, + link, + node.inputs[inputIndex] + ) + } + } + + node.size[1] = node.computeSize([...node.size])[1] + if (!node.graph) return + node._setConcreteSlots() + node.arrange() + app.canvas?.setDirty(true, true) + } + //A little hacky, but onConfigure won't work. + //It fires too late and is overly disruptive + let widgetValue = widget.value + Object.defineProperty(widget, 'value', { + get() { + return widgetValue + }, + set(value) { + widgetValue = value + updateWidgets(value) + } + }) + widget.value = widgetValue + return { widget, minWidth, minHeight } +} + +export const dynamicWidgets = { COMFY_DYNAMICCOMBO_V3: dynamicComboWidget } +const dynamicInputs: Record< + string, + (node: LGraphNode, inputSpec: InputSpecV2) => void +> = { + COMFY_AUTOGROW_V3: applyAutogrow, + COMFY_MATCHTYPE_V3: applyMatchType +} + +export function applyDynamicInputs( + node: LGraphNode, + inputSpec: InputSpecV2 +): boolean { + if (!(inputSpec.type in dynamicInputs)) return false + //TODO: move parsing/validation of inputSpec here? + dynamicInputs[inputSpec.type](node, inputSpec) + return true +} +function spliceInputs( + node: LGraphNode, + startIndex: number, + deleteCount = -1, + ...toAdd: INodeInputSlot[] +): INodeInputSlot[] { + if (deleteCount < 0) return node.inputs.splice(startIndex) + const ret = node.inputs.splice(startIndex, deleteCount, ...toAdd) + node.inputs.slice(startIndex).forEach((input, index) => { + const link = input.link && node.graph?.links?.get(input.link) + if (link) link.target_slot = startIndex + index + }) + return ret +} + +function changeOutputType( + node: LGraphNode, + output: INodeOutputSlot, + combinedType: ISlotType +) { + if (output.type === combinedType) return + output.type = combinedType + + //check and potentially remove links + if (!node.graph) return + for (const link_id of output.links ?? []) { + const link = node.graph.links[link_id] + if (!link) continue + const { input, inputNode, subgraphOutput } = link.resolve(node.graph) + const inputType = (input ?? subgraphOutput)?.type + if (!inputType) continue + const keep = LiteGraph.isValidConnection(combinedType, inputType) + if (!keep && subgraphOutput) subgraphOutput.disconnect() + else if (!keep && inputNode) inputNode.disconnectInput(link.target_slot) + if (input && inputNode?.onConnectionsChange) + inputNode.onConnectionsChange( + LiteGraph.INPUT, + link.target_slot, + keep, + link, + input + ) + } +} + +function withComfyMatchType(node: LGraphNode): asserts node is MatchTypeNode { + if (node.comfyDynamic?.matchType) return + node.comfyDynamic ??= {} + node.comfyDynamic.matchType = {} + + const outputGroups = node.constructor.nodeData?.output_matchtypes + node.onConnectionsChange = useChainCallback( + node.onConnectionsChange, + function ( + this: MatchTypeNode, + contype: ISlotType, + slot: number, + iscon: boolean, + linf: LLink | null | undefined + ) { + const input = this.inputs[slot] + if (contype !== LiteGraph.INPUT || !this.graph || !input) return + const [matchKey, matchGroup] = Object.entries( + this.comfyDynamic.matchType + ).find(([, group]) => input.name in group) ?? ['', undefined] + if (!matchGroup) return + if (iscon && linf) { + const { output, subgraphInput } = linf.resolve(this.graph) + const connectingType = (output ?? subgraphInput)?.type + if (connectingType) linf.type = connectingType + } + //NOTE: inputs contains input + const groupInputs: INodeInputSlot[] = node.inputs.filter( + (inp) => inp.name in matchGroup + ) + const connectedTypes = groupInputs.map((inp) => { + if (!inp.link) return '*' + const link = this.graph!.links[inp.link] + if (!link) return '*' + const { output, subgraphInput } = link.resolve(this.graph!) + return (output ?? subgraphInput)?.type ?? '*' + }) + //An input slot can accept a connection that is + // - Compatible with original type + // - Compatible with all other input types + //An output slot can output + // - Only what every input can output + groupInputs.forEach((input, idx) => { + const otherConnected = [ + ...connectedTypes.slice(0, idx), + ...connectedTypes.slice(idx + 1) + ] + const combinedType = commonType( + ...otherConnected, + matchGroup[input.name] + ) + if (!combinedType) throw new Error('invalid connection') + input.type = combinedType + }) + const outputType = commonType(...connectedTypes) + if (!outputType) throw new Error('invalid connection') + this.outputs.forEach((output, idx) => { + if (!(outputGroups?.[idx] == matchKey)) return + changeOutputType(this, output, outputType) + }) + app.canvas?.setDirty(true, true) + } + ) +} + +function applyMatchType(node: LGraphNode, inputSpec: InputSpecV2) { + const { addNodeInput } = useLitegraphService() + const name = inputSpec.name + const { allowed_types, template_id } = ( + inputSpec as InputSpecV2 & { + template: { allowed_types: string; template_id: string } + } + ).template + const typedSpec = { ...inputSpec, type: allowed_types } + addNodeInput(node, typedSpec) + withComfyMatchType(node) + node.comfyDynamic.matchType[template_id] ??= {} + node.comfyDynamic.matchType[template_id][name] = allowed_types + + //TODO: instead apply on output add? + //ensure outputs get updated + const index = node.inputs.length - 1 + requestAnimationFrame(() => { + const input = node.inputs[index] + if (!input) return + node.inputs[index] = shallowReactive(input) + node.onConnectionsChange?.( + LiteGraph.INPUT, + index, + !!input.link, + input.link ? node.graph?.links?.[input.link] : undefined, + input + ) + }) +} + +function autogrowOrdinalToName( + ordinal: number, + key: string, + groupName: string, + node: AutogrowNode +) { + const { + names, + prefix = '', + inputSpecs + } = node.comfyDynamic.autogrow[groupName] + const baseName = names + ? names[ordinal] + : (inputSpecs.length == 1 ? prefix : key) + ordinal + return { name: `${groupName}.${baseName}`, display_name: baseName } +} + +function addAutogrowGroup( + ordinal: number, + groupName: string, + node: AutogrowNode +) { + const { addNodeInput } = useLitegraphService() + const { max, min, inputSpecs } = node.comfyDynamic.autogrow[groupName] + if (ordinal >= max) return + + const namedSpecs = inputSpecs.map((input) => ({ + ...input, + isOptional: ordinal >= (min ?? 0) || input.isOptional, + ...autogrowOrdinalToName(ordinal, input.name, groupName, node) + })) + + const newInputs = namedSpecs.map((namedSpec) => { + addNodeInput(node, namedSpec) + const input = spliceInputs(node, node.inputs.length - 1, 1)[0] + if (inputSpecs.length !== 1 || (INLINE_INPUTS && !input.widget)) + ensureWidgetForInput(node, input) + return input + }) + + for (const newInput of newInputs) { + for (const existingInput of remove( + node.inputs, + (inp) => inp.name === newInput.name + )) { + //NOTE: link.target_slot is updated on spliceInputs call + newInput.link ??= existingInput.link + } + } + + const targetName = autogrowOrdinalToName( + ordinal - 1, + inputSpecs.at(-1)!.name, + groupName, + node + ).name + const lastIndex = node.inputs.findLastIndex((inp) => + inp.name.startsWith(targetName) + ) + const insertionIndex = lastIndex === -1 ? node.inputs.length : lastIndex + 1 + spliceInputs(node, insertionIndex, 0, ...newInputs) + app.canvas?.setDirty(true, true) +} + +const ORDINAL_REGEX = /\d+$/ +function resolveAutogrowOrdinal( + inputName: string, + groupName: string, + node: AutogrowNode +): number | undefined { + //TODO preslice groupname? + const name = inputName.slice(groupName.length + 1) + const { names } = node.comfyDynamic.autogrow[groupName] + if (names) { + const ordinal = names.findIndex((s) => s === name) + return ordinal === -1 ? undefined : ordinal + } + const match = name.match(ORDINAL_REGEX) + if (!match) return undefined + const ordinal = parseInt(match[0]) + return ordinal !== ordinal ? undefined : ordinal +} +function autogrowInputConnected(index: number, node: AutogrowNode) { + const input = node.inputs[index] + const groupName = input.name.slice(0, input.name.lastIndexOf('.')) + const lastInput = node.inputs.findLast((inp) => + inp.name.startsWith(groupName + '.') + ) + const ordinal = resolveAutogrowOrdinal(input.name, groupName, node) + if ( + !lastInput || + ordinal == undefined || + (ordinal !== resolveAutogrowOrdinal(lastInput.name, groupName, node) && + !app.configuringGraph) + ) + return + addAutogrowGroup(ordinal + 1, groupName, node) +} +function autogrowInputDisconnected(index: number, node: AutogrowNode) { + const input = node.inputs[index] + if (!input) return + const groupName = input.name.slice(0, input.name.lastIndexOf('.')) + const { min = 1, inputSpecs } = node.comfyDynamic.autogrow[groupName] + const ordinal = resolveAutogrowOrdinal(input.name, groupName, node) + if (ordinal == undefined || ordinal + 1 < min) return + + //resolve all inputs in group + const groupInputs = node.inputs.filter( + (inp) => + inp.name.startsWith(groupName + '.') && + inp.name.lastIndexOf('.') === groupName.length + ) + const stride = inputSpecs.length + if (stride + index >= node.inputs.length) return + if (groupInputs.length % stride !== 0) { + console.error('Failed to group multi-input autogrow inputs') + return + } + app.canvas?.setDirty(true, true) + //groupBy would be nice here, but may not be supported + for (let column = 0; column < stride; column++) { + for ( + let bubbleOrdinal = ordinal * stride + column; + bubbleOrdinal + stride < groupInputs.length; + bubbleOrdinal += stride + ) { + const curInput = groupInputs[bubbleOrdinal] + curInput.link = groupInputs[bubbleOrdinal + stride].link + if (!curInput.link) continue + const link = node.graph?.links[curInput.link] + if (!link) continue + const curIndex = node.inputs.findIndex((inp) => inp === curInput) + if (curIndex === -1) throw new Error('missing input') + link.target_slot = curIndex + node.onConnectionsChange?.( + LiteGraph.INPUT, + curIndex, + true, + link, + curInput + ) + } + const lastInput = groupInputs.at(column - stride) + if (!lastInput) continue + lastInput.link = null + node.onConnectionsChange?.( + LiteGraph.INPUT, + node.inputs.length + column - stride, + false, + null, + lastInput + ) + } + const removalChecks = groupInputs.slice((min - 1) * stride) + let i + for (i = removalChecks.length - stride; i >= 0; i -= stride) { + if (removalChecks.slice(i, i + stride).some((inp) => inp.link)) break + } + const toRemove = removalChecks.slice(i + stride * 2) + remove(node.inputs, (inp) => toRemove.includes(inp)) + for (const input of toRemove) { + const widgetName = input?.widget?.name + if (!widgetName) continue + for (const widget of remove(node.widgets, (w) => w.name === widgetName)) + widget.onRemove?.() + } + node.size[1] = node.computeSize([...node.size])[1] +} + +function withComfyAutogrow(node: LGraphNode): asserts node is AutogrowNode { + if (node.comfyDynamic?.autogrow) return + node.comfyDynamic ??= {} + node.comfyDynamic.autogrow = {} + + let pendingConnection: number | undefined + let swappingConnection = false + + const originalOnConnectInput = node.onConnectInput + node.onConnectInput = function (slot: number, ...args) { + pendingConnection = slot + requestAnimationFrame(() => (pendingConnection = undefined)) + return originalOnConnectInput?.apply(this, [slot, ...args]) ?? true + } + + node.onConnectionsChange = useChainCallback( + node.onConnectionsChange, + function ( + this: AutogrowNode, + contype: ISlotType, + slot: number, + iscon: boolean, + linf: LLink | null | undefined + ) { + const input = this.inputs[slot] + if (contype !== LiteGraph.INPUT || !input) return + //Return if input isn't known autogrow + const key = input.name.slice(0, input.name.lastIndexOf('.')) + const autogrowGroup = this.comfyDynamic.autogrow[key] + if (!autogrowGroup) return + if (app.configuringGraph && input.widget) + ensureWidgetForInput(node, input) + if (iscon) { + if (swappingConnection || !linf) return + autogrowInputConnected(slot, this) + } else { + if (pendingConnection === slot) { + swappingConnection = true + requestAnimationFrame(() => (swappingConnection = false)) + return + } + requestAnimationFrame(() => autogrowInputDisconnected(slot, this)) + } + } + ) +} +function applyAutogrow(node: LGraphNode, inputSpecV2: InputSpecV2) { + withComfyAutogrow(node) + + const parseResult = zAutogrowOptions.safeParse(inputSpecV2) + if (!parseResult.success) throw new Error('invalid Autogrow spec') + const inputSpec = parseResult.data + const { input, min = 1, names, prefix, max = 100 } = inputSpec.template + + const inputTypes: (Record | undefined)[] = [ + input.required, + input.optional + ] + const inputsV2 = inputTypes.flatMap((inputType, index) => + Object.entries(inputType ?? {}).map(([name, v]) => + transformInputSpecV1ToV2(v, { name, isOptional: index === 1 }) + ) + ) + node.comfyDynamic.autogrow[inputSpecV2.name] = { + names, + min, + max: names?.length ?? max, + prefix, + inputSpecs: inputsV2 + } + for (let i = 0; i === 0 || i < min; i++) + addAutogrowGroup(i, inputSpecV2.name, node) +} diff --git a/docs/hel-892/sdpose-reference/frontend__src__extensions__core__noteNode.ts b/docs/hel-892/sdpose-reference/frontend__src__extensions__core__noteNode.ts new file mode 100644 index 00000000..7e0ec56a --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__extensions__core__noteNode.ts @@ -0,0 +1,84 @@ +import { LGraphCanvas, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { LGraphNode } from '@/lib/litegraph/src/litegraph' + +import { app } from '../../scripts/app' +import { ComfyWidgets } from '../../scripts/widgets' + +// Node that add notes to your project + +app.registerExtension({ + name: 'Comfy.NoteNode', + registerCustomNodes() { + class NoteNode extends LGraphNode { + static override category: string + static collapsable: boolean + static title_mode: number + + groupcolor = LGraphCanvas.node_colors.yellow.groupcolor + override isVirtualNode: boolean + + constructor(title: string) { + super(title) + + this.color = LGraphCanvas.node_colors.yellow.color + this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor + + if (!this.properties) { + this.properties = { text: '' } + } + ComfyWidgets.STRING( + this, + 'text', + ['STRING', { default: this.properties.text, multiline: true }], + app + ) + + this.serialize_widgets = true + this.isVirtualNode = true + } + } + + // Load default visibility + + LiteGraph.registerNodeType( + 'Note', + Object.assign(NoteNode, { + title_mode: LiteGraph.NORMAL_TITLE, + title: 'Note', + collapsable: true + }) + ) + + NoteNode.category = 'utils' + + /** Markdown variant of NoteNode */ + class MarkdownNoteNode extends LGraphNode { + static override title = 'Markdown Note' + + groupcolor = LGraphCanvas.node_colors.yellow.groupcolor + + constructor(title: string) { + super(title) + + this.color = LGraphCanvas.node_colors.yellow.color + this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor + + if (!this.properties) { + this.properties = { text: '' } + } + ComfyWidgets.MARKDOWN( + this, + 'text', + ['STRING', { default: this.properties.text }], + app + ) + + this.serialize_widgets = true + this.isVirtualNode = true + } + } + + LiteGraph.registerNodeType('MarkdownNote', MarkdownNoteNode) + MarkdownNoteNode.category = 'utils' + } +}) diff --git a/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts b/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts new file mode 100644 index 00000000..baf6a441 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__LGraphNode.ts @@ -0,0 +1,4229 @@ +import { toValue } from 'vue' + +import { LGraphNodeProperties } from '@/lib/litegraph/src/LGraphNodeProperties' +import { + calculateInputSlotPosFromSlot, + getSlotPosition +} from '@/renderer/core/canvas/litegraph/slotCalculations' +import type { SlotPositionContext } from '@/renderer/core/canvas/litegraph/slotCalculations' +import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations' +import { LayoutSource } from '@/renderer/core/layout/types' +import { adjustColor } from '@/utils/colorUtil' +import type { ColorAdjustOptions } from '@/utils/colorUtil' +import { commonType, toClass } from '@/lib/litegraph/src/utils/type' + +import { SUBGRAPH_OUTPUT_ID } from '@/lib/litegraph/src/constants' +import type { DragAndScale } from './DragAndScale' +import type { LGraph } from './LGraph' +import { BadgePosition, LGraphBadge } from './LGraphBadge' +import { LGraphButton } from './LGraphButton' +import type { LGraphButtonOptions } from './LGraphButton' +import { LGraphCanvas } from './LGraphCanvas' +import { LLink } from './LLink' +import type { Reroute, RerouteId } from './Reroute' +import { getNodeInputOnPos, getNodeOutputOnPos } from './canvas/measureSlots' +import type { IDrawBoundingOptions } from './draw' +import { NullGraphError } from './infrastructure/NullGraphError' +import type { ReadOnlyRectangle } from './infrastructure/Rectangle' +import { Rectangle } from './infrastructure/Rectangle' +import type { + ColorOption, + CompassCorners, + DefaultConnectionColors, + Dictionary, + IColorable, + IContextMenuValue, + IFoundSlot, + INodeFlags, + INodeInputSlot, + INodeOutputSlot, + INodeSlot, + INodeSlotContextItem, + IPinnable, + ISlotType, + Panel, + Point, + Positionable, + ReadOnlyRect, + Rect, + Size +} from './interfaces' +import { LiteGraph, Subgraph } from './litegraph' +import type { LGraphNodeConstructor, SubgraphNode } from './litegraph' +import { + createBounds, + isInRect, + isInRectangle, + isPointInRect, + snapPoint +} from './measure' +import { NodeInputSlot } from './node/NodeInputSlot' +import { NodeOutputSlot } from './node/NodeOutputSlot' +import { + inputAsSerialisable, + isINodeInputSlot, + isWidgetInputSlot, + outputAsSerialisable +} from './node/slotUtils' +import type { SubgraphInputNode } from './subgraph/SubgraphInputNode' +import type { SubgraphOutputNode } from './subgraph/SubgraphOutputNode' +import type { NodeLike } from './types/NodeLike' +import type { CanvasPointerEvent } from './types/events' +import { + LGraphEventMode, + NodeSlotType, + RenderShape, + TitleMode +} from './types/globalEnums' +import type { ISerialisedNode, SubgraphIO } from './types/serialisation' +import type { + IBaseWidget, + IWidgetOptions, + TWidgetType, + TWidgetValue +} from './types/widgets' +import { findFreeSlotOfType } from './utils/collections' +import { warnDeprecated } from './utils/feedback' +import { distributeSpace } from './utils/spaceDistribution' +import { truncateText } from './utils/textUtils' +import { BaseWidget } from './widgets/BaseWidget' +import { toConcreteWidget } from './widgets/widgetMap' +import type { WidgetTypeMap } from './widgets/widgetMap' + +// #region Types + +export type NodeId = number | string + +export type NodeProperty = string | number | boolean | object + +interface INodePropertyInfo { + name?: string + type?: string + default_value?: NodeProperty + widget?: string + label?: string + values?: TWidgetValue[] +} + +interface IMouseOverData { + inputId?: number + outputId?: number + overWidget?: IBaseWidget +} + +interface ConnectByTypeOptions { + /** @deprecated Events */ + createEventInCase?: boolean + /** Allow our wildcard slot to connect to typed slots on remote node. Default: true */ + wildcardToTyped?: boolean + /** Allow our typed slot to connect to wildcard slots on remote node. Default: true */ + typedToWildcard?: boolean + /** The {@link Reroute.id} that the connection is being dragged from. */ + afterRerouteId?: RerouteId +} + +/** Internal type used for type safety when implementing generic checks for inputs & outputs */ +interface IGenericLinkOrLinks { + links?: INodeOutputSlot['links'] + link?: INodeInputSlot['link'] +} + +interface FindFreeSlotOptions { + /** Slots matching these types will be ignored. Default: [] */ + typesNotAccepted?: ISlotType[] + /** If true, the slot itself is returned instead of the index. Default: false */ + returnObj?: boolean +} + +interface DrawSlotsOptions { + fromSlot?: INodeInputSlot | INodeOutputSlot + colorContext: DefaultConnectionColors + editorAlpha: number + lowQuality: boolean +} + +interface DrawWidgetsOptions { + lowQuality?: boolean + editorAlpha?: number +} + +interface DrawTitleOptions { + scale: number + title_height?: number + low_quality?: boolean +} + +interface DrawTitleTextOptions extends DrawTitleOptions { + default_title_color: string +} + +export interface DrawTitleBoxOptions extends DrawTitleOptions { + box_size?: number +} + +/* +title: string +pos: [x,y] +size: [x,y] + +input|output: every connection + + { name:string, type:string, pos: [x,y]=Optional, direction: "input"|"output", links: Array }); + +general properties: + + clip_area: if you render outside the node, it will be clipped + + unsafe_execution: not allowed for safe execution + + skip_repeated_outputs: when adding new outputs, it won't show if there is one already connected + + resizable: if set to false it won't be resizable with the mouse + + widgets_start_y: widgets start at y distance from the top of the node + +flags object: + + collapsed: if it is collapsed + +supported callbacks: + + onAdded: when added to graph (warning: this is called BEFORE the node is configured when loading) + + onRemoved: when removed from graph + + onStart: when the graph starts playing + + onStop: when the graph stops playing + + onDrawForeground: render the inside widgets inside the node + + onDrawBackground: render the background area inside the node (only in edit mode) + + onMouseDown + + onMouseMove + + onMouseUp + + onMouseEnter + + onMouseLeave + + onExecute: execute the node + + onPropertyChanged: when a property is changed in the panel (return true to skip default behaviour) + + onGetInputs: returns an array of possible inputs + + onGetOutputs: returns an array of possible outputs + + onBounding: in case this node has a bigger bounding than the node itself (the callback receives the bounding as [x,y,w,h]) + + onDblClick: double clicked in the node + + onNodeTitleDblClick: double clicked in the node title + + onInputDblClick: input slot double clicked (can be used to automatically create a node connected) + + onOutputDblClick: output slot double clicked (can be used to automatically create a node connected) + + onConfigure: called after the node has been configured + + onSerialize: to add extra info when serializing (the callback receives the object that should be filled with the data) + + onSelected + + onDeselected + + onDropItem : DOM item dropped over the node + + onDropFile : file dropped over the node + + onConnectInput : if returns false the incoming connection will be canceled + + onConnectionsChange : a connection changed (new one or removed) (NodeSlotType.INPUT or NodeSlotType.OUTPUT, slot, true if connected, link_info, input_info ) + + onAction: action slot triggered + + getExtraMenuOptions: to add option to context menu +*/ + +export interface LGraphNode { + constructor: LGraphNodeConstructor +} + +// #endregion Types + +/** + * Base class for all nodes + * @param title a name for the node + * @param type a type for the node + */ + +export class LGraphNode + implements NodeLike, Positionable, IPinnable, IColorable +{ + // Static properties used by dynamic child classes + static title?: string + static MAX_CONSOLE?: number + static type?: string + static category?: string + static description?: string + static filter?: string + static skip_list?: boolean + static nodeData?: { + dev_only?: boolean + deprecated?: boolean + experimental?: boolean + output_node?: boolean + api_node?: boolean + name?: string + } + + static resizeHandleSize = 15 + static resizeEdgeSize = 5 + + /** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */ + static keepAllLinksOnBypass: boolean = false + + /** The title text of the node. */ + title: string + /** + * The font style used to render the node's title text. + */ + get titleFontStyle(): string { + return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get innerFontStyle(): string { + return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get displayType(): string { + return this.type + } + + graph: LGraph | Subgraph | null = null + id: NodeId + type: string = '' + inputs: INodeInputSlot[] = [] + outputs: INodeOutputSlot[] = [] + + private _concreteInputs: NodeInputSlot[] = [] + private _concreteOutputs: NodeOutputSlot[] = [] + + properties: Dictionary = {} + properties_info: INodePropertyInfo[] = [] + flags: INodeFlags = {} + widgets?: IBaseWidget[] + + /** Property manager for this node */ + changeTracker: LGraphNodeProperties + + /** + * The amount of space available for widgets to grow into. + * @see {@link layoutWidgets} + */ + freeWidgetSpace?: number + + locked?: boolean + + /** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */ + order: number = 0 + mode: LGraphEventMode = LGraphEventMode.ALWAYS + last_serialization?: ISerialisedNode + serialize_widgets?: boolean + /** + * The overridden fg color used to render the node. + * @see {@link renderingColor} + */ + color?: string + /** + * The overridden bg color used to render the node. + * @see {@link renderingBgColor} + */ + bgcolor?: string + /** + * The overridden box color used to render the node. + * @see {@link renderingBoxColor} + */ + boxcolor?: string + + /** The fg color used to render the node. */ + get renderingColor(): string { + const baseColor = + this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR + return adjustColor(baseColor, { lightness: LiteGraph.nodeLightness }) + } + + /** The bg color used to render the node. */ + get renderingBgColor(): string { + const baseBgColor = + this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR + const adjustments: ColorAdjustOptions = { + opacity: LiteGraph.nodeOpacity, + lightness: LiteGraph.nodeLightness + } + + return adjustColor( + this.mode === LGraphEventMode.BYPASS + ? LiteGraph.NODE_DEFAULT_BYPASS_COLOR + : baseBgColor, + adjustments + ) + } + + /** The box color used to render the node. */ + get renderingBoxColor(): string { + if (this.boxcolor) return this.boxcolor + + if (LiteGraph.node_box_coloured_when_on) { + if (this.action_triggered) return '#FFF' + if (this.execute_triggered) return '#AAA' + } + + if (LiteGraph.node_box_coloured_by_mode) { + const modeColour = + LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS] + if (modeColour) return modeColour + } + return LiteGraph.NODE_DEFAULT_BOXCOLOR + } + + /** @inheritdoc {@link IColorable.setColorOption} */ + setColorOption(colorOption: ColorOption | null): void { + if (colorOption == null) { + this.color = undefined + this.bgcolor = undefined + } else { + this.color = colorOption.color + this.bgcolor = colorOption.bgcolor + } + } + + /** @inheritdoc {@link IColorable.getColorOption} */ + getColorOption(): ColorOption | null { + return ( + Object.values(LGraphCanvas.node_colors).find( + (colorOption) => + colorOption.color === this.color && + colorOption.bgcolor === this.bgcolor + ) ?? null + ) + } + + /** + * The stroke styles that should be applied to the node. + */ + strokeStyles: Record< + string, + (this: LGraphNode) => IDrawBoundingOptions | undefined + > + + /** + * The progress of node execution. Used to render a progress bar. Value between 0 and 1. + */ + progress?: number + + exec_version?: number + action_call?: string + execute_triggered?: number + action_triggered?: number + /** + * @deprecated This property is unsupported and will be removed in a future release. + * Use `widgets_start_y` or a custom `arrange()` override instead. + */ + widgets_up?: boolean + widgets_start_y?: number + lostFocusAt?: number + gotFocusAt?: number + badges: (LGraphBadge | (() => LGraphBadge))[] = [] + title_buttons: LGraphButton[] = [] + badgePosition: BadgePosition = BadgePosition.TopLeft + onOutputRemoved?(this: LGraphNode, slot: number): void + onInputRemoved?(this: LGraphNode, slot: number, input: INodeInputSlot): void + /** + * The width of the node when collapsed. + * Updated by {@link LGraphCanvas.drawNode} + */ + _collapsed_width?: number + /** + * Called once at the start of every frame. Caller may change the values in {@link out}, which will be reflected in {@link boundingRect}. + * WARNING: Making changes to boundingRect via onBounding is poorly supported, and will likely result in strange behaviour. + */ + onBounding?(this: LGraphNode, out: Rect): void + console?: string[] + _level?: number + _shape?: RenderShape + mouseOver?: IMouseOverData + redraw_on_mouse?: boolean + resizable?: boolean + clonable?: boolean + _relative_id?: number + clip_area?: boolean + ignore_remove?: boolean + has_errors?: boolean + removable?: boolean + block_delete?: boolean + selected?: boolean + showAdvanced?: boolean + + declare comfyDynamic?: Record + declare comfyClass?: string + declare isVirtualNode?: boolean + applyToGraph?(extraLinks?: LLink[]): void + + isSubgraphNode(): this is SubgraphNode { + return false + } + + /** @inheritdoc {@link renderArea} */ + private _renderArea = new Rectangle() + /** + * Rect describing the node area, including shadows and any protrusions. + * Determines if the node is visible. Calculated once at the start of every frame. + */ + get renderArea(): ReadOnlyRect { + return this._renderArea + } + + /** @inheritdoc {@link boundingRect} */ + private _boundingRect: Rectangle = new Rectangle() + /** + * Cached node position & area as `x, y, width, height`. Includes changes made by {@link onBounding}, if present. + * + * Determines the node hitbox and other rendering effects. Calculated once at the start of every frame. + */ + get boundingRect(): ReadOnlyRectangle { + return this._boundingRect + } + + /** The offset from {@link pos} to the top-left of {@link boundingRect}. */ + get boundingOffset(): Readonly { + const { + pos: [posX, posY], + boundingRect: [bX, bY] + } = this + return [posX - bX, posY - bY] + } + + /** {@link pos} and {@link size} values are backed by this {@link Rectangle}. */ + _posSize = new Rectangle() + _pos: Point = this._posSize.pos + _size: Size = this._posSize.size + + public get pos() { + return this._pos + } + + /** Node position does not necessarily correlate to the top-left corner. */ + public set pos(value) { + if (!value || value.length < 2) return + + this._pos[0] = value[0] + this._pos[1] = value[1] + } + + public get size() { + return this._size + } + + public set size(value) { + if (!value || value.length < 2) return + + this._size[0] = value[0] + this._size[1] = value[1] + } + + /** + * The size of the node used for rendering. + */ + get renderingSize(): Size { + return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size + } + + get shape(): RenderShape | undefined { + return this._shape + } + + set shape(v: RenderShape | 'default' | 'box' | 'round' | 'circle' | 'card') { + const oldValue = this._shape + switch (v) { + case 'default': + this._shape = undefined + break + case 'box': + this._shape = RenderShape.BOX + break + case 'round': + this._shape = RenderShape.ROUND + break + case 'circle': + this._shape = RenderShape.CIRCLE + break + case 'card': + this._shape = RenderShape.CARD + break + default: + this._shape = v + } + if (oldValue !== this._shape) { + this.graph?.trigger('node:property:changed', { + nodeId: this.id, + property: 'shape', + oldValue, + newValue: this._shape + }) + } + } + + /** + * The shape of the node used for rendering. @see {@link RenderShape} + */ + get renderingShape(): RenderShape { + return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE + } + + public get is_selected(): boolean | undefined { + return this.selected + } + + public set is_selected(value: boolean) { + this.selected = value + } + + public get title_mode(): TitleMode { + return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE + } + + onConnectInput?( + this: LGraphNode, + target_slot: number, + type: unknown, + output: INodeOutputSlot | SubgraphIO, + node: LGraphNode | SubgraphInputNode, + slot: number + ): boolean + onConnectOutput?( + this: LGraphNode, + slot: number, + type: unknown, + input: INodeInputSlot | SubgraphIO, + target_node: number | LGraphNode | SubgraphOutputNode, + target_slot: number + ): boolean + onResize?(this: LGraphNode, size: Size): void + onPropertyChanged?( + this: LGraphNode, + name: string, + value: unknown, + prev_value?: unknown + ): boolean + /** Called for each connection that is created, updated, or removed. This includes "restored" connections when deserialising. */ + onConnectionsChange?( + this: LGraphNode, + type: ISlotType, + index: number, + isConnected: boolean, + link_info: LLink | null | undefined, + inputOrOutput: INodeInputSlot | INodeOutputSlot | SubgraphIO + ): void + onInputAdded?(this: LGraphNode, input: INodeInputSlot): void + onOutputAdded?(this: LGraphNode, output: INodeOutputSlot): void + onConfigure?(this: LGraphNode, serialisedNode: ISerialisedNode): void + onSerialize?(this: LGraphNode, serialised: ISerialisedNode): void + onExecute?( + this: LGraphNode, + param?: unknown, + options?: { action_call?: string } + ): void + onAction?( + this: LGraphNode, + action: string, + param: unknown, + options: { action_call?: string } + ): void + onDrawBackground?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onNodeCreated?(this: LGraphNode): void + /** + * Callback invoked by {@link connect} to override the target slot index. + * Its return value overrides the target index selection. + * @param target_slot The current input slot index + * @param requested_slot The originally requested slot index - could be negative, or if using (deprecated) name search, a string + * @returns {number | null} If a number is returned, the connection will be made to that input index. + * If an invalid index or non-number (false, null, NaN etc) is returned, the connection will be cancelled. + */ + onBeforeConnectInput?( + this: LGraphNode, + target_slot: number, + requested_slot?: number | string + ): number | false | null + onShowCustomPanelInfo?(this: LGraphNode, panel: Panel): void + onAddPropertyToPanel?(this: LGraphNode, pName: string, panel: Panel): boolean + onWidgetChanged?( + this: LGraphNode, + name: string, + value: unknown, + old_value: unknown, + w: IBaseWidget + ): void + onDeselected?(this: LGraphNode): void + onKeyUp?(this: LGraphNode, e: KeyboardEvent): void + onKeyDown?(this: LGraphNode, e: KeyboardEvent): void + onSelected?(this: LGraphNode): void + getExtraMenuOptions?( + this: LGraphNode, + canvas: LGraphCanvas, + options: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + getMenuOptions?(this: LGraphNode, canvas: LGraphCanvas): IContextMenuValue[] + onAdded?(this: LGraphNode, graph: LGraph): void + onDrawCollapsed?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + cavnas: LGraphCanvas + ): boolean + onDrawForeground?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + canvas: LGraphCanvas, + canvasElement: HTMLCanvasElement + ): void + onMouseLeave?(this: LGraphNode, e: CanvasPointerEvent): void + /** + * Override the default slot menu options. + */ + getSlotMenuOptions?(this: LGraphNode, slot: IFoundSlot): IContextMenuValue[] + /** + * Add extra menu options to the slot context menu. + */ + getExtraSlotMenuOptions?( + this: LGraphNode, + slot: IFoundSlot + ): IContextMenuValue[] + + // FIXME: Re-typing + onDropItem?(this: LGraphNode, event: Event): boolean + onDropData?( + this: LGraphNode, + data: string | ArrayBuffer, + filename: string, + file: File + ): void + onDropFile?(this: LGraphNode, file: File): void + onInputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onInputDblClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputDblClick?( + this: LGraphNode, + index: number, + e: CanvasPointerEvent + ): void + onGetPropertyInfo?(this: LGraphNode, property: string): INodePropertyInfo + onNodeOutputAdd?(this: LGraphNode, value: unknown): void + onNodeInputAdd?(this: LGraphNode, value: unknown): void + onMenuNodeInputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMenuNodeOutputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMouseUp?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onMouseEnter?(this: LGraphNode, e: CanvasPointerEvent): void + /** Blocks drag if return value is truthy. @param pos Offset from {@link LGraphNode.pos}. */ + onMouseDown?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): boolean + /** @param pos Offset from {@link LGraphNode.pos}. */ + onDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + /** @param pos Offset from {@link LGraphNode.pos}. */ + onNodeTitleDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onDrawTitle?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onDrawTitleText?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + title_text_font: string, + selected?: boolean + ): void + onDrawTitleBox?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number + ): void + onDrawTitleBar?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + fgcolor: string + ): void + onRemoved?(this: LGraphNode): void + onMouseMove?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + arg2: LGraphCanvas + ): void + onPropertyChange?(this: LGraphNode): void + updateOutputData?(this: LGraphNode, origin_slot: number): void + + private _getErrorStrokeStyle( + this: LGraphNode + ): IDrawBoundingOptions | undefined { + if (this.has_errors) { + return { + padding: 12, + lineWidth: 10, + color: LiteGraph.NODE_ERROR_COLOUR + } + } + } + + private _getSelectedStrokeStyle( + this: LGraphNode + ): IDrawBoundingOptions | undefined { + if (this.selected) { + return { + padding: this.has_errors ? 20 : undefined + } + } + } + + constructor(title: string, type?: string) { + this.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : -1 + this.title = title || 'Unnamed' + this.type = type ?? '' + this.size = [LiteGraph.NODE_WIDTH, 60] + this.pos = [10, 10] + this.strokeStyles = { + error: this._getErrorStrokeStyle, + selected: this._getSelectedStrokeStyle + } + // Initialize property manager with tracked properties + this.changeTracker = new LGraphNodeProperties(this) + } + + /** Internal callback for subgraph nodes. Do not implement externally. */ + _internalConfigureAfterSlots?(): void + + /** + * configure a node from an object containing the serialized info + */ + configure(info: ISerialisedNode): void { + if (this.graph) { + this.graph._version++ + } + if (info.id === -1) info.id = this.id + for (const j in info) { + if (j == 'properties') { + // i don't want to clone properties, I want to reuse the old container + for (const k in info.properties) { + this.properties[k] = info.properties[k] + this.onPropertyChanged?.(k, info.properties[k]) + } + continue + } + + // @ts-expect-error #594 + if (info[j] == null) { + continue + // @ts-expect-error #594 + } else if (typeof info[j] == 'object') { + // @ts-expect-error #594 + if (this[j]?.configure) { + // @ts-expect-error #594 + this[j]?.configure(info[j]) + } else { + // @ts-expect-error #594 + this[j] = LiteGraph.cloneObject(info[j], this[j]) + } + } else { + // value + // @ts-expect-error #594 + this[j] = info[j] + } + } + + if (!info.title) { + this.title = this.constructor.title + } + + this.inputs ??= [] + this.inputs = this.inputs.map((input) => + toClass(NodeInputSlot, input, this) + ) + for (const [i, input] of this.inputs.entries()) { + const link = + this.graph && input.link != null + ? this.graph._links.get(input.link) + : null + this.onConnectionsChange?.(NodeSlotType.INPUT, i, true, link, input) + this.onInputAdded?.(input) + } + + this.outputs ??= [] + this.outputs = this.outputs.map((output) => + toClass(NodeOutputSlot, output, this) + ) + for (const [i, output] of this.outputs.entries()) { + if (!output.links) continue + + for (const linkId of output.links) { + const link = this.graph ? this.graph._links.get(linkId) : null + this.onConnectionsChange?.(NodeSlotType.OUTPUT, i, true, link, output) + } + this.onOutputAdded?.(output) + } + + // SubgraphNode callback. + this._internalConfigureAfterSlots?.() + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + const input = this.inputs.find((i) => i.widget?.name === w.name) + if (input?.label) w.label = input.label + + if ( + w.options?.property && + this.properties[w.options.property] != undefined + ) + w.value = JSON.parse( + JSON.stringify(this.properties[w.options.property]) + ) + } + + if (info.widgets_values) { + let i = 0 + for (const widget of this.widgets ?? []) { + if (widget.serialize === false) continue + if (i >= info.widgets_values.length) break + widget.value = info.widgets_values[i++] + } + } + } + + // Sync the state of this.resizable. + if (this.pinned) this.resizable = false + + if (this.widgets_up) { + console.warn( + `[LiteGraph] Node type "${this.type}" uses deprecated property "widgets_up". ` + + 'This property is unsupported and will be removed. ' + + 'Use "widgets_start_y" or a custom arrange() override instead.' + ) + } + + this.onConfigure?.(info) + } + + /** + * serialize the content + */ + serialize(): ISerialisedNode { + // create serialization object + const o: ISerialisedNode = { + id: this.id, + type: this.type, + pos: [this.pos[0], this.pos[1]], + size: [this.size[0], this.size[1]], + flags: LiteGraph.cloneObject(this.flags), + order: this.order, + mode: this.mode, + showAdvanced: this.showAdvanced + } + + // special case for when there were errors + if (this.constructor === LGraphNode && this.last_serialization) + return { ...this.last_serialization, mode: o.mode, pos: o.pos } + + if (this.inputs) + o.inputs = this.inputs.map((input) => inputAsSerialisable(input)) + if (this.outputs) + // @ts-expect-error - Output serialization type mismatch + o.outputs = this.outputs.map((output) => outputAsSerialisable(output)) + + if (this.title && this.title != this.constructor.title) o.title = this.title + + if (this.properties) o.properties = LiteGraph.cloneObject(this.properties) + + const { widgets } = this + if (widgets && this.serialize_widgets) { + o.widgets_values = [] + for (const [i, widget] of widgets.entries()) { + if (widget.serialize === false) continue + // @ts-expect-error #595 No-null + o.widgets_values[i] = widget ? widget.value : null + } + } + + if (!o.type && this.constructor.type) o.type = this.constructor.type + + if (this.color) o.color = this.color + if (this.bgcolor) o.bgcolor = this.bgcolor + if (this.boxcolor) o.boxcolor = this.boxcolor + if (this.shape) o.shape = this.shape + + if (this.onSerialize?.(o)) + console.warn( + "node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter" + ) + + return o + } + + /* Creates a clone of this node */ + clone(): LGraphNode | null { + if (this.type == null) return null + const node = LiteGraph.createNode(this.type) + if (!node) return null + + // we clone it because serialize returns shared containers + const data = LiteGraph.cloneObject(this.serialize()) + const { inputs, outputs } = data + + // remove links + if (inputs) { + for (const input of inputs) { + input.link = null + } + } + + if (outputs) { + for (const { links } of outputs) { + if (links) links.length = 0 + } + } + + // @ts-expect-error Exceptional case: id is removed so that the graph can assign a new one on add. + data.id = undefined + + if (LiteGraph.use_uuids) data.id = LiteGraph.uuidv4() + + node.configure(data) + + return node + } + + /** + * serialize and stringify + */ + toString(): string { + return JSON.stringify(this.serialize()) + } + + /** + * get the title string + */ + getTitle(): string { + return this.title || this.constructor.title + } + + /** + * sets the value of a property + * @param name + * @param value + */ + setProperty(name: string, value: TWidgetValue): void { + this.properties ||= {} + if (value === this.properties[name]) return + + const prev_value = this.properties[name] + this.properties[name] = value + // abort change + if (this.onPropertyChanged?.(name, value, prev_value) === false) + this.properties[name] = prev_value + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + if (w.options.property == name) { + w.value = value + break + } + } + } + } + + /** + * sets the output data + * @param slot + * @param data + */ + setOutputData( + slot: number, + data: number | string | boolean | { toToolTip?(): string } + ): void { + const { outputs } = this + if (!outputs) return + + // this maybe slow and a niche case + if (slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + + // store data in the output itself in case we want to debug + output_info._data = data + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.data = data + } + } + } + + /** + * sets the output data type, useful when you want to be able to overwrite the data type + */ + setOutputDataType(slot: number, type: ISlotType): void { + const { outputs } = this + if (!outputs || slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + // store data in the output itself in case we want to debug + output_info.type = type + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.type = type + } + } + } + + /** + * Retrieves the input data (data traveling through the connection) from one slot + * @param slot + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns undefined + */ + getInputData(slot: number, force_update?: boolean): unknown { + if (!this.inputs) return + + if (slot >= this.inputs.length || this.inputs[slot].link == null) return + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + if (!force_update) return link.data + + // special case: used to extract data from the incoming connection before the graph has been executed + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.data + + if (node.updateOutputData) { + node.updateOutputData(link.origin_slot) + } else { + node.onExecute?.() + } + + return link.data + } + + /** + * Retrieves the input data type (in case this supports multiple input types) + * @param slot + * @returns datatype in string format + */ + getInputDataType(slot: number): ISlotType | null { + if (!this.inputs) return null + if (slot >= this.inputs.length || this.inputs[slot].link == null) + return null + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.type + + const output_info = node.outputs[link.origin_slot] + return output_info ? output_info.type : null + } + + /** + * Retrieves the input data from one slot using its name instead of slot number + * @param slot_name + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns null + */ + getInputDataByName(slot_name: string, force_update: boolean): unknown { + const slot = this.findInputSlot(slot_name) + return slot == -1 ? null : this.getInputData(slot, force_update) + } + + /** + * tells you if there is a connection in one input slot + * @param slot The 0-based index of the input to check + * @returns `true` if the input slot has a link ID (does not perform validation) + */ + isInputConnected(slot: number): boolean { + if (!this.inputs) return false + return slot < this.inputs.length && this.inputs[slot].link != null + } + + /** + * tells you info about an input connection (which node, type, etc) + * @returns object or null { link: id, name: string, type: string or 0 } + */ + getInputInfo(slot: number): INodeInputSlot | null { + return !this.inputs || !(slot < this.inputs.length) + ? null + : this.inputs[slot] + } + + /** + * Returns the link info in the connection of an input slot + * @returns object or null + */ + getInputLink(slot: number): LLink | null { + if (!this.inputs) return null + + if (slot < this.inputs.length) { + if (!this.graph) throw new NullGraphError() + + const input = this.inputs[slot] + if (input.link != null) { + return this.graph._links.get(input.link) ?? null + } + } + return null + } + + /** + * returns the node connected in the input slot + * @returns node or null + */ + getInputNode(slot: number): LGraphNode | null { + if (!this.inputs) return null + if (slot >= this.inputs.length) return null + + const input = this.inputs[slot] + if (!input || input.link === null) return null + if (!this.graph) throw new NullGraphError() + + const link_info = this.graph._links.get(input.link) + if (!link_info) return null + + return this.graph.getNodeById(link_info.origin_id) + } + + /** + * returns the value of an input with this name, otherwise checks if there is a property with that name + * @returns value + */ + getInputOrProperty(name: string): unknown { + const { inputs } = this + if (!inputs?.length) { + return this.properties ? this.properties[name] : null + } + if (!this.graph) throw new NullGraphError() + + for (const input of inputs) { + if (name == input.name && input.link != null) { + const link = this.graph._links.get(input.link) + if (link) return link.data + } + } + return this.properties[name] + } + + /** + * tells you the last output data that went in that slot + * @returns object or null + */ + getOutputData(slot: number): unknown { + if (!this.outputs) return null + if (slot >= this.outputs.length) return null + + const info = this.outputs[slot] + return info._data + } + + /** + * tells you info about an output connection (which node, type, etc) + * @returns object or null { name: string, type: string, links: [ ids of links in number ] } + */ + getOutputInfo(slot: number): INodeOutputSlot | null { + return !this.outputs || !(slot < this.outputs.length) + ? null + : this.outputs[slot] + } + + /** + * tells you if there is a connection in one output slot + */ + isOutputConnected(slot: number): boolean { + if (!this.outputs) return false + return ( + slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0 + ) + } + + /** + * tells you if there is any connection in the output slots + */ + isAnyOutputConnected(): boolean { + const { outputs } = this + if (!outputs) return false + + for (const output of outputs) { + if (output.links?.length) return true + } + return false + } + + /** + * retrieves all the nodes connected to this output slot + */ + getOutputNodes(slot: number): LGraphNode[] | null { + const { outputs } = this + if (!outputs || outputs.length == 0) return null + + if (slot >= outputs.length) return null + + const { links } = outputs[slot] + if (!links || links.length == 0) return null + if (!this.graph) throw new NullGraphError() + + const r: LGraphNode[] = [] + for (const id of links) { + const link = this.graph._links.get(id) + if (link) { + const target_node = this.graph.getNodeById(link.target_id) + if (target_node) { + r.push(target_node) + } + } + } + return r + } + + addOnTriggerInput(): number { + const trigS = this.findInputSlot('onTrigger') + if (trigS == -1) { + this.addInput('onTrigger', LiteGraph.EVENT, { + nameLocked: true + }) + return this.findInputSlot('onTrigger') + } + return trigS + } + + addOnExecutedOutput(): number { + const trigS = this.findOutputSlot('onExecuted') + if (trigS == -1) { + this.addOutput('onExecuted', LiteGraph.ACTION, { + nameLocked: true + }) + return this.findOutputSlot('onExecuted') + } + return trigS + } + + onAfterExecuteNode(param: unknown, options?: { action_call?: string }) { + const trigS = this.findOutputSlot('onExecuted') + if (trigS != -1) { + this.triggerSlot(trigS, param, null, options) + } + } + + changeMode(modeTo: number): boolean { + switch (modeTo) { + case LGraphEventMode.ON_EVENT: + break + + case LGraphEventMode.ON_TRIGGER: + this.addOnTriggerInput() + this.addOnExecutedOutput() + break + + case LGraphEventMode.NEVER: + break + + case LGraphEventMode.ALWAYS: + break + + // @ts-expect-error Not impl. + case LiteGraph.ON_REQUEST: + break + + default: + return false + break + } + this.mode = modeTo + return true + } + + /** + * Triggers the node code execution, place a boolean/counter to mark the node as being executed + */ + doExecute(param?: unknown, options?: { action_call?: string }): void { + options = options || {} + if (this.onExecute) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error Technically it works when id is a string. Array gets props. + this.graph.nodes_executing[this.id] = true + this.onExecute(param, options) + // @ts-expect-error deprecated + this.graph.nodes_executing[this.id] = false + + // save execution/action ref + this.exec_version = this.graph.iteration + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.execute_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an action, wrapped by logics to control execution flow + * @param action name + */ + actionDo( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + options = options || {} + if (this.onAction) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_${action || 'action'}_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = action || 'actioning' + this.onAction(action, param, options) + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = false + + // save execution/action ref + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.action_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an event in this node, this will trigger any output with the same name + * @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all + */ + trigger( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + const { outputs } = this + if (!outputs || !outputs.length) { + return + } + + if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime() + + for (const [i, output] of outputs.entries()) { + if ( + !output || + output.type !== LiteGraph.EVENT || + (action && output.name != action) + ) { + continue + } + this.triggerSlot(i, param, null, options) + } + } + + /** + * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + triggerSlot( + slot: number, + param: unknown, + link_id: number | null, + options?: { action_call?: string } + ): void { + options = options || {} + if (!this.outputs) return + + if (slot == null) { + console.error('slot must be a number') + return + } + + if (typeof slot !== 'number') + console.warn( + "slot must be a number, use node.trigger('name') if you want to use a string" + ) + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + this.graph._last_trigger_time = LiteGraph.getTime() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = LiteGraph.getTime() + const node = this.graph.getNodeById(link_info.target_id) + // node not found? + if (!node) continue + + if (node.mode === LGraphEventMode.ON_TRIGGER) { + // generate unique trigger ID if not present + if (!options.action_call) + options.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}` + // -- wrapping node.onExecute(param); -- + node.doExecute?.(param, options) + } else if (node.onAction) { + // generate unique action ID if not present + if (!options.action_call) + options.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}` + // pass the action name + const target_connection = node.inputs[link_info.target_slot] + node.actionDo(target_connection.name, param, options) + } + } + } + + /** + * clears the trigger slot animation + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + clearTriggeredSlot(slot: number, link_id: number): void { + if (!this.outputs) return + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = 0 + } + } + + /** + * changes node size and triggers callback + */ + setSize(size: Size): void { + this.size = size + this.onResize?.(this.size) + } + + /** + * Expands the node size to fit its content. + */ + expandToFitContent(): void { + const newSize = this.computeSize() + this.setSize([ + Math.max(this.size[0], newSize[0]), + Math.max(this.size[1], newSize[1]) + ]) + } + + /** + * add a new property to this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of the property (like values, etc) + */ + addProperty( + name: string, + default_value: NodeProperty | undefined, + type?: string, + extra_info?: Partial + ): INodePropertyInfo { + const o: INodePropertyInfo = { name, type, default_value } + if (extra_info) Object.assign(o, extra_info) + + this.properties_info ||= [] + this.properties_info.push(o) + this.properties ||= {} + this.properties[name] = default_value + return o + } + + /** + * add a new output slot to use in this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) + */ + addOutput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeOutputSlot & TProperties { + const output = Object.assign( + new NodeOutputSlot({ name, type, links: null }, this), + extra_info + ) + + this.outputs ||= [] + this.outputs.push(output) + this.onOutputAdded?.(output) + + if (LiteGraph.auto_load_slot_types) + LiteGraph.registerNodeAndSlotType(this, type, true) + + this.expandToFitContent() + this.setDirtyCanvas(true, true) + return output + } + + /** + * remove an existing output slot + */ + removeOutput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectOutput(slot) + } + const { outputs } = this + outputs.splice(slot, 1) + + for (let i = slot; i < outputs.length; ++i) { + const output = outputs[i] + if (!output || !output.links) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + for (const linkId of output.links) { + const link = this.graph._links.get(linkId) + if (link) link.origin_slot-- + } + } + } + + this.onOutputRemoved?.(slot) + this.setDirtyCanvas(true, true) + } + + /** + * add a new input slot to use in this node + * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 + * @param extra_info this can be used to have special properties of an input (label, color, position, etc) + */ + addInput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeInputSlot & TProperties { + type ||= 0 + + const input = Object.assign( + new NodeInputSlot({ name, type, link: null }, this), + extra_info + ) + + this.inputs ||= [] + this.inputs.push(input) + this.expandToFitContent() + + this.onInputAdded?.(input) + LiteGraph.registerNodeAndSlotType(this, type) + + this.setDirtyCanvas(true, true) + return input + } + + /** + * remove an existing input slot + */ + removeInput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectInput(slot, true) + } + const { inputs } = this + const slot_info = inputs.splice(slot, 1) + + for (let i = slot; i < inputs.length; ++i) { + const input = inputs[i] + if (!input?.link) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + const link = this.graph._links.get(input.link) + if (link) link.target_slot-- + } + } + this.onInputRemoved?.(slot, slot_info[0]) + this.setDirtyCanvas(true, true) + } + + /** + * computes the minimum size of a node according to its inputs and output slots + * @returns the total size + */ + computeSize(out?: Size): Size { + const ctorSize = this.constructor.size + if (ctorSize) return [ctorSize[0], ctorSize[1]] + + const { inputs, outputs, widgets } = this + let rows = Math.max( + inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1, + outputs ? outputs.length : 1 + ) + const size = out ?? [0, 0] + rows = Math.max(rows, 1) + // although it should be graphcanvas.inner_text_font size + const font_size = LiteGraph.NODE_TEXT_SIZE + + const padLeft = LiteGraph.NODE_TITLE_HEIGHT + const padRight = padLeft * 0.33 + const title_width = + padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight + let input_width = 0 + let widgetWidth = 0 + let output_width = 0 + + if (inputs) { + for (const input of inputs) { + const text = input.label || input.localized_name || input.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (isWidgetInputSlot(input)) { + const widget = this.getWidgetFromSlot(input) + if (widget && !this.isWidgetVisible(widget)) continue + + if (text_width > widgetWidth) widgetWidth = text_width + } else { + if (text_width > input_width) input_width = text_width + } + } + } + + if (outputs) { + for (const output of outputs) { + const text = output.label || output.localized_name || output.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (output_width < text_width) output_width = text_width + } + } + + const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1) + // Text + slot width + centre padding + const centrePadding = input_width && output_width ? 5 : 0 + const slotsWidth = + input_width + + output_width + + 2 * LiteGraph.NODE_SLOT_HEIGHT + + centrePadding + + // Total distance from edge of node to the inner edge of the widget 'previous' arrow button + const widgetMargin = + BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth + const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin + if (widgetWidth) widgetWidth += widgetPadding + + size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth) + size[1] = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + + // Get widget height & expand size if necessary + let widgets_height = 0 + if (widgets?.length) { + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + let widget_height = 0 + if (widget.computeSize) { + widget_height += widget.computeSize(size[0])[1] + } else if (widget.computeLayoutSize) { + // Expand widget width if necessary + const { minHeight, minWidth } = widget.computeLayoutSize(this) + const widgetWidth = minWidth + widgetPadding + if (widgetWidth > size[0]) size[0] = widgetWidth + + widget_height += minHeight + } else { + widget_height += LiteGraph.NODE_WIDGET_HEIGHT + } + widgets_height += widget_height + 4 + } + widgets_height += 8 + } + + // compute height using widgets height + if (this.widgets_up) size[1] = Math.max(size[1], widgets_height) + else if (this.widgets_start_y != null) + size[1] = Math.max(size[1], widgets_height + this.widgets_start_y) + else size[1] += widgets_height + + function compute_text_size(text: string, fontStyle: string) { + return ( + LGraphCanvas._measureText?.(text, fontStyle) ?? + font_size * (text?.length ?? 0) * 0.6 + ) + } + + if (this.constructor.min_height && size[1] < this.constructor.min_height) { + size[1] = this.constructor.min_height + } + + // margin + size[1] += 6 + + return size + } + + inResizeCorner(canvasX: number, canvasY: number): boolean { + const rows = this.outputs ? this.outputs.length : 1 + const outputs_offset = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + return isInRectangle( + canvasX, + canvasY, + this.pos[0] + this.size[0] - 15, + this.pos[1] + Math.max(this.size[1] - 15, outputs_offset), + 20, + 20 + ) + } + + /** + * Returns which resize corner the point is over, if any. + * @param canvasX X position in canvas coordinates + * @param canvasY Y position in canvas coordinates + * @returns The compass corner the point is in, otherwise `undefined`. + */ + findResizeDirection( + canvasX: number, + canvasY: number + ): CompassCorners | undefined { + if (this.resizable === false) return + + const { boundingRect } = this + if (!boundingRect.containsXy(canvasX, canvasY)) return + + // Check corners first (they take priority over edges) + return boundingRect.findContainingCorner( + canvasX, + canvasY, + LGraphNode.resizeHandleSize + ) + } + + /** + * returns all the info available about a property of this node. + * @param property name of the property + * @returns the object with all the available info + */ + getPropertyInfo(property: string) { + let info = null + + // there are several ways to define info about a property + // legacy mode + const { properties_info } = this + if (properties_info) { + for (const propInfo of properties_info) { + if (propInfo.name == property) { + info = propInfo + break + } + } + } + // litescene mode using the constructor + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + if (this.constructor[`@${property}`]) + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + info = this.constructor[`@${property}`] + + if (this.constructor.widgets_info?.[property]) + info = this.constructor.widgets_info[property] + + // litescene mode using the constructor + if (!info && this.onGetPropertyInfo) { + info = this.onGetPropertyInfo(property) + } + + info ||= {} + info.type ||= typeof this.properties[property] + if (info.widget == 'combo') info.type = 'enum' + + return info + } + + /** + * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties + * @param type the widget type + * @param name the text to show on the widget + * @param value the default value + * @param callback function to call when it changes (optionally, it can be the name of the property to modify) + * @param options the object that contains special properties of this widget + * @returns the created widget object + */ + addWidget< + Type extends TWidgetType, + TValue extends WidgetTypeMap[Type]['value'] + >( + type: Type, + name: string, + value: TValue, + callback: IBaseWidget['callback'] | string | null, + options?: IWidgetOptions | string + ): WidgetTypeMap[Type] | IBaseWidget { + this.widgets ||= [] + + if (!options && callback && typeof callback === 'object') { + options = callback + callback = null + } + + // options can be the property name + options ||= {} + if (typeof options === 'string') options = { property: options } + + // callback can be the property name + if (callback && typeof callback === 'string') { + options.property = callback + callback = null + } + + const w: IBaseWidget & { type: Type } = { + // @ts-expect-error - Type casting for widget type property + type: type.toLowerCase(), + name: name, + value: value, + callback: typeof callback !== 'function' ? undefined : callback, + options, + y: 0 + } + + if (w.options.y !== undefined) { + w.y = w.options.y + } + + if (!callback && !w.options.callback && !w.options.property) { + console.warn( + 'LiteGraph addWidget(...) without a callback or property assigned' + ) + } + if (type == 'combo' && !w.options.values) { + throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }" + } + + const widget = this.addCustomWidget(w) + this.expandToFitContent() + return widget + } + + addCustomWidget( + custom_widget: TPlainWidget + ): TPlainWidget | WidgetTypeMap[TPlainWidget['type']] { + this.widgets ||= [] + const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget + this.widgets.push(widget) + return widget + } + + addTitleButton(options: LGraphButtonOptions): LGraphButton { + this.title_buttons ||= [] + const button = new LGraphButton(options) + this.title_buttons.push(button) + return button + } + + onTitleButtonClick(button: LGraphButton, canvas: LGraphCanvas): void { + // Dispatch event for button click + canvas.dispatch('litegraph:node-title-button-clicked', { + node: this, + button: button + }) + } + + removeWidgetByName(name: string): void { + const widget = this.widgets?.find((x) => x.name === name) + if (widget) this.removeWidget(widget) + } + + removeWidget(widget: IBaseWidget): void { + if (!this.widgets) + throw new Error('removeWidget called on node without widgets') + + const widgetIndex = this.widgets.indexOf(widget) + if (widgetIndex === -1) throw new Error('Widget not found on this node') + + // Clean up slot references to prevent memory leaks + if (this.inputs) { + for (const input of this.inputs) { + if (input._widget === widget) { + input._widget = undefined + input.widget = undefined + } + } + } + + widget.onRemove?.() + this.widgets.splice(widgetIndex, 1) + } + + ensureWidgetRemoved(widget: IBaseWidget): void { + try { + this.removeWidget(widget) + } catch (error) { + console.error('Failed to remove widget', error) + } + } + + move(deltaX: number, deltaY: number): void { + if (this.pinned) return + + // If Vue nodes mode is enabled, skip LiteGraph's direct position update + // The layout store will handle the movement and sync back to LiteGraph + if (LiteGraph.vueNodesMode) { + // Vue nodes handle their own dragging through the layout store + // This prevents the snap-back issue from conflicting position updates + return + } + + this.pos[0] += deltaX + this.pos[1] += deltaY + } + + /** + * Internal method to measure the node for rendering. Prefer {@link boundingRect} where possible. + * + * Populates {@link out} with the results in graph space. + * Populates {@link _collapsed_width} with the collapsed width if the node is collapsed. + * Adjusts for title and collapsed status, but does not call {@link onBounding}. + * @param out `x, y, width, height` are written to this array. + * @param ctx The canvas context to use for measuring text. + */ + measure(out: Rect, ctx?: CanvasRenderingContext2D): void { + const titleMode = this.title_mode + const renderTitle = + titleMode != TitleMode.TRANSPARENT_TITLE && + titleMode != TitleMode.NO_TITLE + const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0 + + out[0] = this.pos[0] + out[1] = this.pos[1] + -titleHeight + if (!this.flags?.collapsed) { + out[2] = this.size[0] + out[3] = this.size[1] + titleHeight + } else { + if (ctx) ctx.font = this.innerFontStyle + this._collapsed_width = Math.min( + this.size[0], + ctx + ? ctx.measureText(this.getTitle() ?? '').width + + LiteGraph.NODE_TITLE_HEIGHT * 2 + : 0 + ) + out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[3] = LiteGraph.NODE_TITLE_HEIGHT + } + } + + /** + * returns the bounding of the object, used for rendering purposes + * @param out {Rect?} [optional] a place to store the output, to free garbage + * @param includeExternal {boolean?} [optional] set to true to + * include the shadow and connection points in the bounding calculation + * @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height] + */ + getBounding(out?: Rect, includeExternal?: boolean): Rect { + out ||= [0, 0, 0, 0] + + const rect = includeExternal ? this.renderArea : this.boundingRect + out[0] = rect[0] + out[1] = rect[1] + out[2] = rect[2] + out[3] = rect[3] + + return out + } + + /** + * Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}. + * Called automatically at the start of every frame. + */ + updateArea(ctx?: CanvasRenderingContext2D): void { + const bounds = this._boundingRect + this.measure(bounds, ctx) + this.onBounding?.(bounds) + + const renderArea = this._renderArea + renderArea.set(bounds) + // 4 offset for collapsed node connection points + renderArea[0] -= 4 + renderArea[1] -= 4 + // Add shadow & left offset + renderArea[2] += 6 + 4 + // Add shadow & top offsets + renderArea[3] += 5 + 4 + } + + /** + * checks if a point is inside the shape of a node + */ + isPointInside(x: number, y: number): boolean { + if (isInRect(x, y, this.boundingRect)) return true + + for (const badge of this.badges.map(toValue).filter((b) => b.onClick)) { + if (isInRect(x - this.pos[0], y - this.pos[1], badge.boundingRect)) + return true + } + return false + } + + /** + * Checks if the provided point is inside this node's collapse button area. + * @param x X co-ordinate to check + * @param y Y co-ordinate to check + * @returns true if the x,y point is in the collapse button area, otherwise false + */ + isPointInCollapse(x: number, y: number): boolean { + const squareLength = LiteGraph.NODE_TITLE_HEIGHT + return isInRectangle( + x, + y, + this.pos[0], + this.pos[1] - squareLength, + squareLength, + squareLength + ) + } + + /** + * Returns the input slot at the given position. Uses full 20 height, and approximates the label length. + * @param pos The graph co-ordinates to check + * @returns The input slot at the given position if found, otherwise `undefined`. + */ + getInputOnPos(pos: Point): INodeInputSlot | undefined { + return getNodeInputOnPos(this, pos[0], pos[1])?.input + } + + /** + * Returns the output slot at the given position. Uses full 20x20 box for the slot. + * @param pos The graph co-ordinates to check + * @returns The output slot at the given position if found, otherwise `undefined`. + */ + getOutputOnPos(pos: Point): INodeOutputSlot | undefined { + return getNodeOutputOnPos(this, pos[0], pos[1])?.output + } + + /** + * Returns the input or output slot at the given position. + * + * Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}. + * @param pos The graph co-ordinates to check + * @returns The input or output slot at the given position if found, otherwise `undefined`. + */ + getSlotOnPos(pos: Point): INodeInputSlot | INodeOutputSlot | undefined { + if (!isPointInRect(pos, this.boundingRect)) return + + return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos) + } + + /** + * @deprecated Use {@link getSlotOnPos} instead. + * checks if a point is inside a node slot, and returns info about which slot + * @param x + * @param y + * @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] } + */ + getSlotInPosition(x: number, y: number): IFoundSlot | null { + // search for inputs + const { inputs, outputs } = this + + if (inputs) { + for (const [i, input] of inputs.entries()) { + const pos = this.getInputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { input, slot: i, link_pos: pos } + } + } + } + + if (outputs) { + for (const [i, output] of outputs.entries()) { + const pos = this.getOutputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { output, slot: i, link_pos: pos } + } + } + } + + return null + } + + /** + * Gets the widget on this node at the given co-ordinates. + * @param canvasX X co-ordinate in graph space + * @param canvasY Y co-ordinate in graph space + * @returns The widget found, otherwise `null` + */ + getWidgetOnPos( + canvasX: number, + canvasY: number, + includeDisabled = false + ): IBaseWidget | undefined { + const { widgets, pos, size } = this + if (!widgets?.length) return + + const x = canvasX - pos[0] + const y = canvasY - pos[1] + const nodeWidth = size[0] + + for (const widget of widgets) { + if ( + (widget.computedDisabled && !includeDisabled) || + !this.isWidgetVisible(widget) + ) { + continue + } + + const h = + widget.computedHeight ?? + widget.computeSize?.(nodeWidth)[1] ?? + LiteGraph.NODE_WIDGET_HEIGHT + + const maybeDOMWidget = widget as { margin?: number } + const mtop = maybeDOMWidget.margin ?? -2 + const mbot = maybeDOMWidget.margin ?? 2 + const mx = maybeDOMWidget.margin ?? 6 + + const w = widget.width || nodeWidth + if ( + widget.last_y !== undefined && + isInRectangle( + x, + y, + mx, + widget.last_y + mtop, + w - 2 * mx, + h - mtop - mbot + ) + ) { + return widget + } + } + } + + /** + * Returns the input slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findInputSlot( + name: string, + returnObj?: TReturn + ): number + findInputSlot( + name: string, + returnObj?: TReturn + ): INodeInputSlot + findInputSlot(name: string, returnObj: boolean = false) { + const { inputs } = this + if (!inputs) return -1 + + for (const [i, input] of inputs.entries()) { + if (name == input.name) { + return !returnObj ? i : input + } + } + return -1 + } + + /** + * returns the output slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findOutputSlot( + name: string, + returnObj?: TReturn + ): number + findOutputSlot( + name: string, + returnObj?: TReturn + ): INodeOutputSlot + findOutputSlot(name: string, returnObj: boolean = false) { + const { outputs } = this + if (!outputs) return -1 + + for (const [i, output] of outputs.entries()) { + if (name == output.name) { + return !returnObj ? i : output + } + } + return -1 + } + + /** + * Finds the first free input slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeInputSlot | -1 + findInputSlotFree(optsIn?: FindFreeSlotOptions) { + return this._findFreeSlot(this.inputs, optsIn) + } + + /** + * Finds the first free output slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeOutputSlot | -1 + findOutputSlotFree(optsIn?: FindFreeSlotOptions) { + return this._findFreeSlot(this.outputs, optsIn) + } + + /** + * Finds the next free slot + * @param slots The slots to search, i.e. this.inputs or this.outputs + */ + private _findFreeSlot( + slots: TSlot[], + options?: FindFreeSlotOptions + ): TSlot | number { + const defaults = { + returnObj: false, + typesNotAccepted: [] + } + const opts = Object.assign(defaults, options || {}) + const length = slots?.length + if (!(length > 0)) return -1 + + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + if (!slot || slot.link || slot.links?.length) continue + if (opts.typesNotAccepted?.includes?.(slot.type)) continue + return !opts.returnObj ? i : slot + } + return -1 + } + + /** + * findSlotByType for INPUTS + */ + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot + findInputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this._findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * findSlotByType for OUTPUTS + */ + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot + findOutputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this._findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * returns the output (or input) slot with a given type, -1 if not found + * @param input use inputs instead of outputs + * @param type the type of the slot to find + * @param returnObj if the obj itself wanted + * @param preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway) + * @returns the slot (-1 if not found) + */ + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot | -1 + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot | -1 + findSlotByType( + input: boolean, + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number | INodeOutputSlot | INodeInputSlot { + return input + ? this._findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + : this._findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}. + * @param slots Slots to search (this.inputs or this.outputs) + * @param type Type of slot to look for + * @param returnObj If true, returns the slot itself. Otherwise, the index. + * @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot. + * @param doNotUseOccupied Do not fall back to occupied slots. + * @see {findSlotByType} + * @see {findOutputSlotByType} + * @see {findInputSlotByType} + * @returns If a match is found, the slot if returnObj is true, otherwise the index. If no matches are found, -1 + */ + private _findSlotByType( + slots: TSlot[], + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): TSlot | number { + const length = slots?.length + if (!length) return -1 + + // Empty string and * match anything (type: 0) + if (type == '' || type == '*') type = 0 + const sourceTypes = String(type).toLowerCase().split(',') + + // Run the search + let occupiedSlot: number | TSlot | null = null + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + const destTypes = + slot.type == '0' || slot.type == '*' + ? ['0'] + : String(slot.type).toLowerCase().split(',') + + for (const sourceType of sourceTypes) { + // TODO: Remove _event_ entirely. + const source = sourceType == '_event_' ? LiteGraph.EVENT : sourceType + + for (const destType of destTypes) { + const dest = destType == '_event_' ? LiteGraph.EVENT : destType + + if (source == dest || source === '*' || dest === '*') { + if (preferFreeSlot && (slot.links?.length || slot.link != null)) { + // In case we can't find a free slot. + occupiedSlot ??= returnObj ? slot : i + continue + } + return returnObj ? slot : i + } + } + } + } + + return doNotUseOccupied ? -1 : (occupiedSlot ?? -1) + } + + /** + * Determines the slot index to connect to when attempting to connect by type. + * @param findInputs If true, searches for an input. Otherwise, an output. + * @param node The node at the other end of the connection. + * @param slotType The type of slot at the other end of the connection. + * @param options Search restrictions to adhere to. + * @see {connectByType} + * @see {connectByTypeOutput} + */ + findConnectByTypeSlot( + findInputs: boolean, + node: LGraphNode, + slotType: ISlotType, + options?: ConnectByTypeOptions + ): number | undefined { + // LEGACY: Old options names + if (options && typeof options === 'object') { + if ('firstFreeIfInputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfInputGeneralInCase + if ('firstFreeIfOutputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfOutputGeneralInCase + if ('generalTypeInCase' in options) + options.typedToWildcard = !!options.generalTypeInCase + } + const optsDef: ConnectByTypeOptions = { + createEventInCase: true, + wildcardToTyped: true, + typedToWildcard: true + } + const opts = Object.assign(optsDef, options) + + if (!this.graph) throw new NullGraphError() + + if (node && typeof node === 'number') { + const nodeById = this.graph.getNodeById(node) + if (!nodeById) return + + node = nodeById + } + const slot = node.findSlotByType(findInputs, slotType, false, true) + if (slot >= 0 && slot !== null) return slot + + // TODO: Remove or reimpl. events. WILL CREATE THE onTrigger IN SLOT + if (opts.createEventInCase && slotType == LiteGraph.EVENT) { + if (findInputs) return -1 + if (LiteGraph.do_add_triggers_slots) return node.addOnExecutedOutput() + } + + // connect to the first general output slot if not found a specific type and + if (opts.typedToWildcard) { + const generalSlot = node.findSlotByType(findInputs, 0, false, true, true) + if (generalSlot >= 0) return generalSlot + } + // connect to the first free input slot if not found a specific type and this output is general + if ( + opts.wildcardToTyped && + (slotType == 0 || slotType == '*' || slotType == '') + ) { + const opt = { typesNotAccepted: [LiteGraph.EVENT] } + const nonEventSlot = findInputs + ? node.findInputSlotFree(opt) + : node.findOutputSlotFree(opt) + if (nonEventSlot >= 0) return nonEventSlot + } + } + + /** + * Finds the first free output slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findOutputByType( + type: ISlotType + ): { index: number; slot: INodeOutputSlot } | undefined { + return findFreeSlotOfType( + this.outputs, + type, + (output) => !output.links?.length + ) + } + + /** + * Finds the first free input slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findInputByType( + type: ISlotType + ): { index: number; slot: INodeInputSlot } | undefined { + return findFreeSlotOfType( + this.inputs, + type, + (input) => + input.link == null || !!this.graph?.getLink(input.link)?._dragging + ) + } + + /** + * connect this node output to the input of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slotType the input slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByType( + slot: number | string, + target_node: LGraphNode, + target_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + const slotIndex = this.findConnectByTypeSlot( + true, + target_node, + target_slotType, + optsIn + ) + if (slotIndex !== undefined) + return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId) + + // No compatible slot found - connection not possible + return null + } + + /** + * connect this node input to the output of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param source_node the target node + * @param source_slotType the output slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByTypeOutput( + slot: number | string, + source_node: LGraphNode, + source_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + // LEGACY: Old options names + if (typeof optsIn === 'object') { + if ('firstFreeIfInputGeneralInCase' in optsIn) + optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase + if ('generalTypeInCase' in optsIn) + optsIn.typedToWildcard = !!optsIn.generalTypeInCase + } + const slotIndex = this.findConnectByTypeSlot( + false, + source_node, + source_slotType, + optsIn + ) + if (slotIndex !== undefined) + return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId) + + console.error( + '[connectByType]: no way to connect type:', + source_slotType, + 'to node:', + source_node + ) + return null + } + + canConnectTo( + node: NodeLike, + toSlot: INodeInputSlot | SubgraphIO, + fromSlot: INodeOutputSlot | SubgraphIO + ) { + return ( + this.id !== node.id && + LiteGraph.isValidConnection(fromSlot.type, toSlot.type) + ) + } + + /** + * Connect an output of this node to an input of another node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) + * @returns the link_info is created, otherwise null + */ + connect( + slot: number | string, + target_node: LGraphNode, + target_slot: ISlotType, + afterRerouteId?: RerouteId + ): LLink | null { + // Allow legacy API support for searching target_slot by string, without mutating the input variables + let targetIndex: number | null + + const { graph, outputs } = this + if (!graph) { + // could be connected before adding it to a graph + // due to link ids being associated with graphs + console.error( + "Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them." + ) + return null + } + + // seek for the output slot + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return null + } + } else if (!outputs || slot >= outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + if (target_node && typeof target_node === 'number') { + const nodeById = graph.getNodeById(target_node) + if (!nodeById) throw 'target node is null' + + target_node = nodeById + } + if (!target_node) throw 'target node is null' + + // avoid loopback + if (target_node == this) return null + + // you can specify the slot by name + if (typeof target_slot === 'string') { + targetIndex = target_node.findInputSlot(target_slot) + if (targetIndex == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${targetIndex}`) + return null + } + } else if (target_slot === LiteGraph.EVENT) { + // TODO: Events + if (LiteGraph.do_add_triggers_slots) { + target_node.changeMode(LGraphEventMode.ON_TRIGGER) + targetIndex = target_node.findInputSlot('onTrigger') + } else { + return null + } + } else if (typeof target_slot === 'number') { + targetIndex = target_slot + } else { + targetIndex = 0 + } + + // Allow target node to change slot + if (target_node.onBeforeConnectInput) { + // This way node can choose another slot (or make a new one?) + const requestedIndex = target_node.onBeforeConnectInput( + targetIndex, + target_slot + ) + targetIndex = typeof requestedIndex === 'number' ? requestedIndex : null + } + + if ( + targetIndex === null || + !target_node.inputs || + targetIndex >= target_node.inputs.length + ) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + const input = target_node.inputs[targetIndex] + const output = outputs[slot] + + if (!output) return null + + if (output.links?.length) { + if ( + output.type === LiteGraph.EVENT && + !LiteGraph.allow_multi_output_for_events + ) { + graph.beforeChange() + this.disconnectOutput(slot) + } + } + + const link = this.connectSlots(output, target_node, input, afterRerouteId) + return link ?? null + } + + /** + * Connect two slots between two nodes + * @param output The output slot to connect + * @param inputNode The node that the input slot is on + * @param input The input slot to connect + * @param afterRerouteId The reroute ID to use for the link + * @returns The link that was created, or null if the connection was blocked + */ + connectSlots( + output: INodeOutputSlot, + inputNode: LGraphNode, + input: INodeInputSlot, + afterRerouteId: RerouteId | undefined + ): LLink | null | undefined { + const { graph } = this + if (!graph) throw new NullGraphError() + + const layoutMutations = useLayoutMutations() + + const outputIndex = this.outputs.indexOf(output) + if (outputIndex === -1) { + console.warn('connectSlots: output not found') + return + } + const inputIndex = inputNode.inputs.indexOf(input) + if (inputIndex === -1) { + console.warn('connectSlots: input not found') + return + } + + // check targetSlot and check connection types + if (!LiteGraph.isValidConnection(output.type, input.type)) { + this.setDirtyCanvas(false, true) + return null + } + + // Allow nodes to block connection + if ( + inputNode.onConnectInput?.( + inputIndex, + output.type, + output, + this, + outputIndex + ) === false + ) + return null + if ( + this.onConnectOutput?.( + outputIndex, + input.type, + input, + inputNode, + inputIndex + ) === false + ) + return null + + // if there is something already plugged there, disconnect + if (inputNode.inputs[inputIndex]?.link != null) { + graph.beforeChange() + inputNode.disconnectInput(inputIndex, true) + } + + const maybeCommonType = + input.type && output.type && commonType(input.type, output.type) + + const link = new LLink( + ++graph.state.lastLinkId, + maybeCommonType || input.type || output.type, + this.id, + outputIndex, + inputNode.id, + inputIndex, + afterRerouteId + ) + + // add to graph links list + graph._links.set(link.id, link) + + // Register link in Layout Store for spatial tracking + layoutMutations.setSource(LayoutSource.Canvas) + layoutMutations.createLink( + link.id, + this.id, + outputIndex, + inputNode.id, + inputIndex + ) + + // connect in output + output.links ??= [] + output.links.push(link.id) + // connect in input + const targetInput = inputNode.inputs[inputIndex] + targetInput.link = link.id + if (targetInput.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: inputNode.id, + slotType: NodeSlotType.INPUT, + slotIndex: inputIndex, + connected: true, + linkId: link.id + }) + } + + // Reroutes + const reroutes = LLink.getReroutes(graph, link) + for (const reroute of reroutes) { + reroute.linkIds.add(link.id) + if (reroute.floating) reroute.floating = undefined + reroute._dragging = undefined + } + + // If this is the terminus of a floating link, remove it + const lastReroute = reroutes.at(-1) + if (lastReroute) { + for (const linkId of lastReroute.floatingLinkIds) { + const link = graph.floatingLinks.get(linkId) + if (link?.parentId === lastReroute.id) { + graph.removeFloatingLink(link) + } + } + } + graph._version++ + + // link has been created now, so its updated + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + outputIndex, + true, + link, + output + ) + + inputNode.onConnectionsChange?.( + NodeSlotType.INPUT, + inputIndex, + true, + link, + input + ) + + this.setDirtyCanvas(false, true) + graph.afterChange() + + return link + } + + connectFloatingReroute( + pos: Point, + slot: INodeInputSlot | INodeOutputSlot, + afterRerouteId?: RerouteId + ): Reroute { + const { graph, id } = this + if (!graph) throw new NullGraphError() + + // Assertion: It's either there or it isn't. + const inputIndex = this.inputs.indexOf(slot as INodeInputSlot) + const outputIndex = this.outputs.indexOf(slot as INodeOutputSlot) + if (inputIndex === -1 && outputIndex === -1) throw new Error('Invalid slot') + + const slotType = outputIndex === -1 ? 'input' : 'output' + + const reroute = graph.setReroute({ + pos, + parentId: afterRerouteId, + linkIds: [], + floating: { slotType } + }) + + const parentReroute = graph.getReroute(afterRerouteId) + const fromLastFloatingReroute = + parentReroute?.floating?.slotType === 'output' + + // Adding from an output, or a floating reroute that is NOT the tip of an existing floating chain + if (afterRerouteId == null || !fromLastFloatingReroute) { + const link = new LLink( + -1, + slot.type, + outputIndex === -1 ? -1 : id, + outputIndex, + inputIndex === -1 ? -1 : id, + inputIndex + ) + link.parentId = reroute.id + graph.addFloatingLink(link) + return reroute + } + + // Adding a new floating reroute from the tip of a floating chain. + if (!parentReroute) + throw new Error('[connectFloatingReroute] Parent reroute not found') + + const link = parentReroute.getFloatingLinks('output')?.[0] + if (!link) + throw new Error('[connectFloatingReroute] Floating link not found') + + reroute.floatingLinkIds.add(link.id) + link.parentId = reroute.id + parentReroute.floating = undefined + return reroute + } + + /** + * disconnect one output to an specific node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node to which this slot is connected [Optional, + * if not target_node is specified all nodes will be disconnected] + * @returns if it was disconnected successfully + */ + disconnectOutput(slot: string | number, target_node?: LGraphNode): boolean { + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.outputs || slot >= this.outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return false + } + + // get output slot + const output = this.outputs[slot] + if (!output) return false + + if (output._floatingLinks) { + for (const link of output._floatingLinks) { + if (link.hasOrigin(this.id, slot)) { + this.graph?.removeFloatingLink(link) + } + } + } + + if (!output.links || output.links.length == 0) return false + const { links } = output + + // one of the output links in this slot + const graph = this.graph + if (!graph) throw new NullGraphError() + + if (target_node) { + const target = + typeof target_node === 'number' + ? graph.getNodeById(target_node) + : target_node + if (!target) throw 'Target Node not found' + + for (const [i, link_id] of links.entries()) { + const link_info = graph._links.get(link_id) + if (link_info?.target_id != target.id) continue + + // is the link we are searching for... + // remove here + links.splice(i, 1) + const input = target.inputs[link_info.target_slot] + // remove there + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // remove the link from the links pool + link_info.disconnect(graph, 'input') + graph._version++ + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + + break + } + } else { + // all the links in this output slot + for (const link_id of links) { + const link_info = graph._links.get(link_id) + if (!link_info) continue + if ( + link_info.target_id === SUBGRAPH_OUTPUT_ID && + graph instanceof Subgraph + ) { + const targetSlot = graph.outputNode.slots[link_info.target_slot] + if (targetSlot) { + targetSlot.linkIds.length = 0 + } else { + console.error('Missing subgraphOutput slot when disconnecting link') + } + } + + const target = graph.getNodeById(link_info.target_id) + graph._version++ + + if (target) { + const input = target.inputs[link_info.target_slot] + // remove other side link + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + } + // remove the link from the links pool + link_info.disconnect(graph, 'input') + + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + } + output.links = null + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * Disconnect one input + * @param slot Input slot index, or the name of the slot + * @param keepReroutes If `true`, reroutes will not be garbage collected. + * @returns true if disconnected successfully or already disconnected, otherwise false + */ + disconnectInput(slot: number | string, keepReroutes?: boolean): boolean { + // Allow search by string + if (typeof slot === 'string') { + slot = this.findInputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.inputs || slot >= this.inputs.length) { + if (LiteGraph.debug) { + console.error('Connect: Error, slot number not found') + } + return false + } + + const input = this.inputs[slot] + if (!input) { + console.error('disconnectInput: input not found', slot, this.inputs) + return false + } + + const { graph } = this + if (!graph) throw new NullGraphError() + + // Break floating links + if (input._floatingLinks?.size) { + for (const link of input._floatingLinks) { + graph.removeFloatingLink(link) + } + } + + const link_id = this.inputs[slot].link + if (link_id != null) { + this.inputs[slot].link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: this.id, + slotType: NodeSlotType.INPUT, + slotIndex: slot, + connected: false, + linkId: link_id + }) + } + + // remove other side + const link_info = graph._links.get(link_id) + if (link_info) { + // Let SubgraphInput do the disconnect. + if (link_info.origin_id === -10 && 'inputNode' in graph) { + graph.inputNode._disconnectNodeInput(this, input, link_info) + return true + } + + const target_node = graph.getNodeById(link_info.origin_id) + if (!target_node) { + console.error( + 'disconnectInput: output not found', + link_info.origin_slot + ) + return false + } + + const output = target_node.outputs[link_info.origin_slot] + if (!output?.links?.length) { + // Output not found - may have been removed + return false + } + + // search in the inputs list for this link + let i = 0 + for (const l = output.links.length; i < l; i++) { + if (output.links[i] == link_id) { + output.links.splice(i, 1) + break + } + } + + link_info.disconnect(graph, keepReroutes ? 'output' : undefined) + if (graph) graph._version++ + + this.onConnectionsChange?.( + NodeSlotType.INPUT, + slot, + false, + link_info, + input + ) + target_node.onConnectionsChange?.( + NodeSlotType.OUTPUT, + i, + false, + link_info, + output + ) + } + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * @deprecated Use {@link getInputPos} or {@link getOutputPos} instead. + * returns the center of a connection point in canvas coords + * @param is_input true if if a input slot, false if it is an output + * @param slot_number (could be the number of the slot or the string with the name of the slot) + * @param out [optional] a place to store the output, to free garbage + * @returns the position + */ + getConnectionPos(is_input: boolean, slot_number: number, out?: Point): Point { + out ||= [0, 0] + + const { + pos: [nodeX, nodeY], + inputs, + outputs + } = this + + if (this.flags.collapsed) { + const w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[0] = is_input ? nodeX : nodeX + w + out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // weird feature that never got finished + if (is_input && slot_number == -1) { + out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // hard-coded pos + const inputPos = inputs?.[slot_number]?.pos + const outputPos = outputs?.[slot_number]?.pos + + if (is_input && inputPos) { + out[0] = nodeX + inputPos[0] + out[1] = nodeY + inputPos[1] + return out + } else if (!is_input && outputPos) { + out[0] = nodeX + outputPos[0] + out[1] = nodeY + outputPos[1] + return out + } + + // default vertical slots + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + const slotIndex = is_input + ? this._defaultVerticalInputs.indexOf(this.inputs[slot_number]) + : this._defaultVerticalOutputs.indexOf(this.outputs[slot_number]) + + out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset + out[1] = + nodeY + + (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + + (this.constructor.slot_start_y || 0) + return out + } + + /** + * @internal The inputs that are not positioned with absolute coordinates. + */ + private get _defaultVerticalInputs() { + return this.inputs.filter( + (slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot)) + ) + } + + /** + * @internal The outputs that are not positioned with absolute coordinates. + */ + private get _defaultVerticalOutputs() { + return this.outputs.filter((slot: INodeOutputSlot) => !slot.pos) + } + + /** + * Get the context needed for slot position calculations + * @internal + */ + private _getSlotPositionContext(): SlotPositionContext { + return { + nodeX: this.pos[0], + nodeY: this.pos[1], + nodeWidth: this.size[0], + nodeHeight: this.size[1], + collapsed: this.flags.collapsed ?? false, + collapsedWidth: this._collapsed_width, + slotStartY: this.constructor.slot_start_y, + inputs: this.inputs, + outputs: this.outputs, + widgets: this.widgets + } + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param slot Input slot index + * @returns Position of the input slot + */ + getInputPos(slot: number): Point { + return getSlotPosition(this, slot, true) + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * @param input The actual node input object + * @returns Position of the centre of the input slot in graph co-ordinates. + */ + getInputSlotPos(input: INodeInputSlot): Point { + return calculateInputSlotPosFromSlot(this._getSlotPositionContext(), input) + } + + /** + * Gets the position of an output slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param outputSlotIndex Output slot index + * @returns Position of the output slot + */ + getOutputPos(outputSlotIndex: number): Point { + return getSlotPosition(this, outputSlotIndex, false) + } + + /** + * Get slot position using layout tree if available, fallback to node's position * Unified implementation used by both LitegraphLinkAdapter and useLinkLayoutSync + * @param slotIndex The slot index + * @param isInput Whether this is an input slot + * @returns Position of the slot center in graph coordinates + */ + getSlotPosition(slotIndex: number, isInput: boolean): Point { + return getSlotPosition(this, slotIndex, isInput) + } + + /** @inheritdoc */ + snapToGrid(snapTo: number): boolean { + return this.pinned ? false : snapPoint(this.pos, snapTo) + } + + /** @see {@link snapToGrid} */ + alignToGrid(): void { + this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE) + } + + /* Console output */ + trace(msg: string): void { + this.console ||= [] + this.console.push(msg) + // @ts-expect-error deprecated + if (this.console.length > LGraphNode.MAX_CONSOLE) this.console.shift() + } + + /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ + setDirtyCanvas(dirty_foreground: boolean, dirty_background?: boolean): void { + this.graph?.canvasAction((c) => + c.setDirty(dirty_foreground, dirty_background) + ) + } + + loadImage(url: string): HTMLImageElement { + interface AsyncImageElement extends HTMLImageElement { + ready?: boolean + } + + const img: AsyncImageElement = new Image() + img.src = LiteGraph.node_images_path + url + img.ready = false + + const dirty = () => this.setDirtyCanvas(true) + img.addEventListener('load', function (this: AsyncImageElement) { + this.ready = true + dirty() + }) + return img + } + + /** + * Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus + * @deprecated Use {@link LGraphCanvas.pointer} instead. + */ + captureInput(v: boolean): void { + warnDeprecated( + '[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.' + ) + if (!this.graph || !this.graph.list_of_graphcanvas) return + + const list = this.graph.list_of_graphcanvas + + for (const c of list) { + // releasing somebody elses capture?! + if (!v && c.node_capturing_input != this) continue + + // change + c.node_capturing_input = v ? this : null + } + } + + get collapsed() { + return !!this.flags.collapsed + } + + get collapsible() { + return !this.pinned && this.constructor.collapsable !== false + } + + /** + * Toggle node collapse (makes it smaller on the canvas) + */ + collapse(force?: boolean): void { + if (!this.collapsible && !force) return + if (!this.graph) throw new NullGraphError() + this.graph._version++ + this.flags.collapsed = !this.flags.collapsed + this.setDirtyCanvas(true, true) + } + + /** + * Toggles advanced mode of the node, showing advanced widgets + */ + toggleAdvanced() { + if (!this.widgets?.some((w) => w.advanced)) return + if (!this.graph) throw new NullGraphError() + this.graph._version++ + this.showAdvanced = !this.showAdvanced + this.expandToFitContent() + this.setDirtyCanvas(true, true) + } + + get pinned() { + return !!this.flags.pinned + } + + /** + * Prevents the node being accidentally moved or resized by mouse interaction. + * Toggles pinned state if no value is provided. + */ + pin(v?: boolean): void { + if (!this.graph) throw new NullGraphError() + + this.graph._version++ + this.flags.pinned = v ?? !this.flags.pinned + this.resizable = !this.pinned + if (!this.pinned) this.flags.pinned = undefined + } + + unpin(): void { + this.pin(false) + } + + localToScreen(x: number, y: number, dragAndScale: DragAndScale): Point { + return [ + (x + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0], + (y + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1] + ] + } + + get width() { + return this.collapsed + ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + : this.size[0] + } + + /** + * Returns the height of the node, including the title bar. + */ + get height() { + return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight + } + + /** + * Returns the height of the node, excluding the title bar. + */ + get bodyHeight() { + return this.collapsed ? 0 : this.size[1] + } + + drawBadges(ctx: CanvasRenderingContext2D, { gap = 2 } = {}): void { + const badgeInstances = this.badges.map((badge) => + badge instanceof LGraphBadge ? badge : badge() + ) + const isLeftAligned = this.badgePosition === BadgePosition.TopLeft + + let currentX = isLeftAligned + ? 0 + : this.width - + badgeInstances.reduce( + (acc, badge) => acc + badge.getWidth(ctx) + gap, + 0 + ) + const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap) + + for (const badge of badgeInstances) { + badge.draw(ctx, currentX, y - badge.height) + currentX += badge.getWidth(ctx) + gap + } + } + + /** + * Renders the node's title bar background + */ + drawTitleBarBackground( + ctx: CanvasRenderingContext2D, + { + scale, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + low_quality = false + }: DrawTitleOptions + ): void { + const fgcolor = this.renderingColor + const shape = this.renderingShape + const size = this.renderingSize + + if (this.onDrawTitleBar) { + this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor) + return + } + + if (this.title_mode === TitleMode.TRANSPARENT_TITLE) { + return + } + + if (this.collapsed) { + ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR + } + + ctx.fillStyle = this.constructor.title_color || fgcolor + ctx.beginPath() + + if (shape == RenderShape.BOX || low_quality) { + ctx.rect(0, -title_height, size[0], title_height) + } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) { + ctx.roundRect( + 0, + -title_height, + size[0], + title_height, + this.collapsed + ? [LiteGraph.ROUND_RADIUS] + : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0] + ) + } + ctx.fill() + ctx.shadowColor = 'transparent' + } + + /** + * Renders the node's title box, i.e. the dot in front of the title text that + * when clicked toggles the node's collapsed state. The term `title box` comes + * from the original LiteGraph implementation. + */ + drawTitleBox( + ctx: CanvasRenderingContext2D, + { + scale, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + box_size = 10 + }: DrawTitleBoxOptions + ): void { + const size = this.renderingSize + const shape = this.renderingShape + + if (this.onDrawTitleBox) { + this.onDrawTitleBox(ctx, title_height, size, scale) + return + } + + if ( + [RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape) + ) { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5 + 1, + 0, + Math.PI * 2 + ) + ctx.fill() + } + + ctx.fillStyle = this.renderingBoxColor + if (low_quality) { + ctx.fillRect( + title_height * 0.5 - box_size * 0.5, + title_height * -0.5 - box_size * 0.5, + box_size, + box_size + ) + } else { + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5, + 0, + Math.PI * 2 + ) + ctx.fill() + } + } else { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.fillRect( + (title_height - box_size) * 0.5 - 1, + (title_height + box_size) * -0.5 - 1, + box_size + 2, + box_size + 2 + ) + } + ctx.fillStyle = this.renderingBoxColor + ctx.fillRect( + (title_height - box_size) * 0.5, + (title_height + box_size) * -0.5, + box_size, + box_size + ) + } + } + + /** + * Renders the node's title text. + */ + drawTitleText( + ctx: CanvasRenderingContext2D, + { + scale, + default_title_color, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT + }: DrawTitleTextOptions + ): void { + const size = this.renderingSize + const selected = this.selected + + if (this.onDrawTitleText) { + this.onDrawTitleText( + ctx, + title_height, + size, + scale, + this.titleFontStyle, + selected + ) + return + } + + // Don't render title text if low quality + if (low_quality) { + return + } + + ctx.font = this.titleFontStyle + const rawTitle = this.getTitle() ?? `❌ ${this.type}` + const title = String(rawTitle) + (this.pinned ? '📌' : '') + if (title) { + if (selected) { + ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR + } else { + ctx.fillStyle = this.constructor.title_text_color || default_title_color + } + + // Calculate available width for title + let availableWidth = size[0] - title_height * 2 // Basic margins + + // Subtract space for title buttons + if (this.title_buttons?.length > 0) { + let buttonsWidth = 0 + const savedFont = ctx.font // Save current font + for (const button of this.title_buttons) { + if (button.visible) { + buttonsWidth += button.getWidth(ctx) + 2 // button width + gap + } + } + ctx.font = savedFont // Restore font after button measurements + if (buttonsWidth > 0) { + buttonsWidth -= 20 // Reduce by empty padding + availableWidth -= buttonsWidth + } + } + + // Truncate title if needed + let displayTitle = title + + if (this.collapsed) { + // For collapsed nodes, limit to 20 chars as before + displayTitle = title.substr(0, 20) + } else if (availableWidth > 0) { + // For regular nodes, truncate based on available width + displayTitle = truncateText(ctx, title, availableWidth) + } + + ctx.textAlign = 'left' + ctx.fillText( + displayTitle, + title_height, + LiteGraph.NODE_TITLE_TEXT_Y - title_height + ) + } + } + + /** + * Attempts to gracefully bypass this node in all of its connections by reconnecting all links. + * + * Each input is checked against each output. This is done on a matching index basis, i.e. input 3 -> output 3. + * If there are any input links remaining, + * and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`, + * each input will check for outputs that match, and take the first one that matches + * `true`: Try the index matching first, then every input to every output. + * `false`: Only matches indexes, e.g. input 3 to output 3. + * + * If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to + * the static {@link keepAllLinksOnBypass}. + * @returns `true` if any new links were established, otherwise `false`. + * @todo Decision: Change API to return array of new links instead? + */ + connectInputToOutput(): boolean | undefined { + const { inputs, outputs, graph } = this + if (!inputs || !outputs) return + if (!graph) throw new NullGraphError() + + const { _links } = graph + let madeAnyConnections = false + + // First pass: only match exactly index-to-index + for (const [index, input] of inputs.entries()) { + if (input.link == null) continue + + const output = outputs[index] + if (!output || !LiteGraph.isValidConnection(input.type, output.type)) + continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + bypassAllLinks(output, inNode, inLink, graph) + } + // Configured to only use index-to-index matching + if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass)) + return madeAnyConnections + + // Second pass: match any remaining links + for (const input of inputs) { + if (input.link == null) continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + for (const output of outputs) { + if (!LiteGraph.isValidConnection(input.type, output.type)) continue + + bypassAllLinks(output, inNode, inLink, graph) + break + } + } + return madeAnyConnections + + function bypassAllLinks( + output: INodeOutputSlot, + inNode: LGraphNode, + inLink: LLink, + graph: LGraph + ) { + const outLinks = output.links + ?.map((x) => _links.get(x)) + .filter((x) => !!x) + if (!outLinks?.length) return + + for (const outLink of outLinks) { + const outNode = graph.getNodeById(outLink.target_id) + if (!outNode) continue + + const result = inNode.connect( + inLink.origin_slot, + outNode, + outLink.target_slot, + inLink.parentId + ) + madeAnyConnections ||= !!result + } + } + } + + /** + * Returns `true` if the widget is visible, otherwise `false`. + */ + isWidgetVisible(widget: IBaseWidget): boolean { + const isHidden = + this.collapsed || widget.hidden || (widget.advanced && !this.showAdvanced) + return !isHidden + } + + updateComputedDisabled() { + if (!this.widgets) return + for (const widget of this.widgets) + widget.computedDisabled = + widget.disabled || this.getSlotFromWidget(widget)?.link != null + } + + drawWidgets( + ctx: CanvasRenderingContext2D, + { lowQuality = false, editorAlpha = 1 }: DrawWidgetsOptions + ): void { + if (!this.widgets) return + + const nodeWidth = this.size[0] + const { widgets } = this + const H = LiteGraph.NODE_WIDGET_HEIGHT + const showText = !lowQuality + ctx.save() + ctx.globalAlpha = editorAlpha + + this.updateComputedDisabled() + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + const { y } = widget + const outlineColour = widget.advanced + ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR + : LiteGraph.WIDGET_OUTLINE_COLOR + + widget.last_y = y + + ctx.strokeStyle = outlineColour + ctx.fillStyle = '#222' + ctx.textAlign = 'left' + if (widget.computedDisabled) ctx.globalAlpha *= 0.5 + const width = widget.width || nodeWidth + + if (typeof widget.draw === 'function') { + widget.draw(ctx, this, width, y, H, lowQuality) + } else { + toConcreteWidget(widget, this, false)?.drawWidget(ctx, { + width, + showText + }) + } + ctx.globalAlpha = editorAlpha + } + ctx.restore() + } + + /** + * When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots. + */ + drawCollapsedSlots(ctx: CanvasRenderingContext2D): void { + // Render the first connected slot only. + for (const slot of this._concreteInputs) { + if (slot.link != null) { + slot.drawCollapsed(ctx) + break + } + } + for (const slot of this._concreteOutputs) { + if (slot.links?.length) { + slot.drawCollapsed(ctx) + break + } + } + } + + get slots(): (INodeInputSlot | INodeOutputSlot)[] { + return [...this.inputs, ...this.outputs] + } + + private _measureSlot( + slot: NodeInputSlot | NodeOutputSlot, + slotIndex: number, + isInput: boolean + ): void { + const pos = isInput + ? this.getInputPos(slotIndex) + : this.getOutputPos(slotIndex) + + slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[2] = slot.isWidgetInputSlot + ? BaseWidget.margin + : LiteGraph.NODE_SLOT_HEIGHT + slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT + } + + private _measureSlots(): ReadOnlyRect | null { + const slots: (NodeInputSlot | NodeOutputSlot)[] = [] + + for (const [slotIndex, slot] of this._concreteInputs.entries()) { + // Unrecognized nodes (Nodes with error) has inputs but no widgets. Treat + // converted inputs as normal inputs. + /** Widget input slots are handled in {@link layoutWidgetInputSlots} */ + if (this.widgets?.length && isWidgetInputSlot(slot)) continue + + this._measureSlot(slot, slotIndex, true) + slots.push(slot) + } + for (const [slotIndex, slot] of this._concreteOutputs.entries()) { + this._measureSlot(slot, slotIndex, false) + slots.push(slot) + } + + return slots.length ? createBounds(slots, 0) : null + } + + private _getMouseOverSlot(slot: INodeSlot): INodeSlot | null { + const isInput = isINodeInputSlot(slot) + const mouseOverId = this.mouseOver?.[isInput ? 'inputId' : 'outputId'] ?? -1 + if (mouseOverId === -1) { + return null + } + return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId] + } + + private _isMouseOverSlot(slot: INodeSlot): boolean { + return this._getMouseOverSlot(slot) === slot + } + + private _isMouseOverWidget(widget: IBaseWidget | undefined): boolean { + if (!widget) return false + return this.mouseOver?.overWidget === widget + } + + /** + * Returns the input slot that is associated with the given widget. + */ + getSlotFromWidget( + widget: IBaseWidget | undefined + ): INodeInputSlot | undefined { + if (widget) + return this.inputs.find( + (slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name + ) + } + + /** + * Returns the widget that is associated with the given input slot. + */ + getWidgetFromSlot(slot: INodeInputSlot): IBaseWidget | undefined { + if (!isWidgetInputSlot(slot)) return + return this.widgets?.find((w) => w.name === slot.widget.name) + } + + /** + * Draws the node's input and output slots. + */ + drawSlots( + ctx: CanvasRenderingContext2D, + { fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions + ) { + for (const slot of [...this._concreteInputs, ...this._concreteOutputs]) { + const isValidTarget = fromSlot && slot.isValidTarget(fromSlot) + const isMouseOverSlot = this._isMouseOverSlot(slot) + + // change opacity of incompatible slots when dragging a connection + const isValid = !fromSlot || isValidTarget + const highlight = isValid && isMouseOverSlot + + // Show slot if it's not a widget input slot + // or if it's a widget input slot and satisfies one of the following: + // - the mouse is over the widget + // - the slot is valid during link drop + // - the slot is connected + if ( + isMouseOverSlot || + isValidTarget || + !slot.isWidgetInputSlot || + this._isMouseOverWidget(this.getWidgetFromSlot(slot)) || + slot.isConnected || + slot.alwaysVisible + ) { + ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha + slot.draw(ctx, { + colorContext, + lowQuality, + highlight + }) + } + } + } + + /** + * Arranges the node's widgets vertically. + * Sets following properties on each widget: + * - {@link IBaseWidget.computedHeight} + * - {@link IBaseWidget.y} + * @param widgetStartY The y-coordinate of the first widget + */ + private _arrangeWidgets(widgetStartY: number): void { + if (!this.widgets || !this.widgets.length) return + + const bodyHeight = this.bodyHeight + const startY = + this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2 + + let freeSpace = bodyHeight - startY + + // Collect fixed height widgets first + let fixedWidgetHeight = 0 + const growableWidgets: { + minHeight: number + prefHeight?: number + w: IBaseWidget + }[] = [] + + const visibleWidgets = this.widgets.filter((w) => !w.hidden) + + for (const w of visibleWidgets) { + if (w.computeSize) { + const height = w.computeSize()[1] + 4 + w.computedHeight = height + fixedWidgetHeight += height + } else if (w.computeLayoutSize) { + const { minHeight, maxHeight } = w.computeLayoutSize(this) + growableWidgets.push({ + minHeight, + prefHeight: maxHeight, + w + }) + } else { + const height = LiteGraph.NODE_WIDGET_HEIGHT + 4 + w.computedHeight = height + fixedWidgetHeight += height + } + } + + // Calculate remaining space for DOM widgets + freeSpace -= fixedWidgetHeight + this.freeWidgetSpace = freeSpace + + // Prepare space requests for distribution + const spaceRequests = growableWidgets.map((d) => ({ + minSize: d.minHeight, + maxSize: d.prefHeight + })) + + // Distribute space among DOM widgets + const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests) + + // Apply computed heights + for (const [i, d] of growableWidgets.entries()) { + d.w.computedHeight = allocations[i] + } + + // Position widgets + let y = startY + for (const w of visibleWidgets) { + w.y = y + y += w.computedHeight ?? 0 + } + + if (!this.graph) throw new NullGraphError() + + // Grow the node if necessary. + // Ref: https://github.com/Comfy-Org/ComfyUI_frontend/issues/2652 + // TODO: Move the layout logic before drawing of the node shape, so we don't + // need to trigger extra round of rendering. + if (y > bodyHeight) { + this.setSize([this.size[0], y]) + this.graph.setDirtyCanvas(false, true) + } + } + + /** + * Arranges the layout of the node's widget input slots. + */ + private _arrangeWidgetInputSlots(): void { + if (!this.widgets) return + + const slotByWidgetName = new Map< + string, + INodeInputSlot & { index: number } + >() + + for (const [i, slot] of this.inputs.entries()) { + if (!isWidgetInputSlot(slot)) continue + + slotByWidgetName.set(slot.widget.name, { ...slot, index: i }) + } + if (!slotByWidgetName.size) return + + // Only set custom pos if not using Vue positioning + // Vue positioning calculates widget slot positions dynamically + if (!LiteGraph.vueNodesMode) { + for (const widget of this.widgets) { + const slot = slotByWidgetName.get(widget.name) + if (!slot) continue + + const actualSlot = this._concreteInputs[slot.index] + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + actualSlot.pos = [offset, widget.y + offset] + this._measureSlot(actualSlot, slot.index, true) + } + } else { + // For Vue positioning, just measure the slots without setting pos + for (const widget of this.widgets) { + const slot = slotByWidgetName.get(widget.name) + if (!slot) continue + + this._measureSlot(this._concreteInputs[slot.index], slot.index, true) + } + } + } + + /** + * @internal Sets the internal concrete slot arrays, ensuring they are instances of + * {@link NodeInputSlot} or {@link NodeOutputSlot}. + * + * A temporary workaround until duck-typed inputs and outputs + * have been removed from the ecosystem. + */ + _setConcreteSlots(): void { + this._concreteInputs = this.inputs.map((slot) => + toClass(NodeInputSlot, slot, this) + ) + this._concreteOutputs = this.outputs.map((slot) => + toClass(NodeOutputSlot, slot, this) + ) + } + + /** + * Arranges node elements in preparation for rendering (slots & widgets). + */ + arrange(): void { + const slotsBounds = this._measureSlots() + const widgetStartY = slotsBounds + ? slotsBounds[1] + slotsBounds[3] - this.pos[1] + : 0 + this._arrangeWidgets(widgetStartY) + this._arrangeWidgetInputSlots() + } + + /** + * Draws a progress bar on the node. + * @param ctx The canvas context to draw on + */ + drawProgressBar(ctx: CanvasRenderingContext2D): void { + if (!this.progress) return + + const originalFillStyle = ctx.fillStyle + ctx.fillStyle = 'green' + ctx.fillRect(0, 0, this.width * this.progress, 6) + ctx.fillStyle = originalFillStyle + } +} diff --git a/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__widgets__BaseWidget.ts b/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__widgets__BaseWidget.ts new file mode 100644 index 00000000..689dd205 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__lib__litegraph__src__widgets__BaseWidget.ts @@ -0,0 +1,386 @@ +import { t } from '@/i18n' +import { drawTextInArea } from '@/lib/litegraph/src/draw' +import { Rectangle } from '@/lib/litegraph/src/infrastructure/Rectangle' +import type { Point } from '@/lib/litegraph/src/interfaces' +import type { + CanvasPointer, + LGraphCanvas, + LGraphNode, + Size +} from '@/lib/litegraph/src/litegraph' +import { LiteGraph } from '@/lib/litegraph/src/litegraph' +import type { CanvasPointerEvent } from '@/lib/litegraph/src/types/events' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' + +export interface DrawWidgetOptions { + /** The width of the node where this widget will be displayed. */ + width: number + /** Synonym for "low quality". */ + showText?: boolean +} + +interface DrawTruncatingTextOptions extends DrawWidgetOptions { + /** The canvas context to draw the text on. */ + ctx: CanvasRenderingContext2D + /** The amount of padding to add to the left of the text. */ + leftPadding?: number + /** The amount of padding to add to the right of the text. */ + rightPadding?: number +} + +export interface WidgetEventOptions { + e: CanvasPointerEvent + node: LGraphNode + canvas: LGraphCanvas +} + +export abstract class BaseWidget< + TWidget extends IBaseWidget = IBaseWidget +> implements IBaseWidget { + /** From node edge to widget edge */ + static margin = 15 + /** From widget edge to tip of arrow button */ + static arrowMargin = 6 + /** Arrow button width */ + static arrowWidth = 10 + /** Absolute minimum display width of widget values */ + static minValueWidth = 42 + /** Minimum gap between label and value */ + static labelValueGap = 5 + + declare computedHeight?: number + declare serialize?: boolean + computeLayoutSize?(node: LGraphNode): { + minHeight: number + maxHeight?: number + minWidth: number + maxWidth?: number + } + + private _node: LGraphNode + /** The node that this widget belongs to. */ + get node() { + return this._node + } + + linkedWidgets?: IBaseWidget[] + name: string + options: TWidget['options'] + label?: string + type: TWidget['type'] + y: number = 0 + last_y?: number + width?: number + disabled?: boolean + computedDisabled?: boolean + hidden?: boolean + advanced?: boolean + promoted?: boolean + tooltip?: string + element?: HTMLElement + callback?( + value: TWidget['value'], + canvas?: LGraphCanvas, + node?: LGraphNode, + pos?: Point, + e?: CanvasPointerEvent + ): void + mouse?( + event: CanvasPointerEvent, + pointerOffset: Point, + node: LGraphNode + ): boolean + computeSize?(width?: number): Size + onPointerDown?( + pointer: CanvasPointer, + node: LGraphNode, + canvas: LGraphCanvas + ): boolean + + private _value?: TWidget['value'] + get value(): TWidget['value'] { + return this._value + } + + set value(value: TWidget['value']) { + this._value = value + } + + constructor(widget: TWidget & { node: LGraphNode }) + constructor(widget: TWidget, node: LGraphNode) + constructor(widget: TWidget & { node: LGraphNode }, node?: LGraphNode) { + // Private fields + this._node = node ?? widget.node + + // The set and get functions for DOM widget values are hacked on to the options object; + // attempting to set value before options will throw. + // https://github.com/Comfy-Org/ComfyUI_frontend/blob/df86da3d672628a452baed3df3347a52c0c8d378/src/scripts/domWidget.ts#L125 + this.name = widget.name + this.options = widget.options + this.type = widget.type + + // `node` has no setter - Object.assign will throw. + // TODO: Resolve this workaround. Ref: https://github.com/Comfy-Org/litegraph.js/issues/1022 + const { + node: _, + // @ts-expect-error Prevent naming conflicts with custom nodes. + outline_color, + // @ts-expect-error Prevent naming conflicts with custom nodes. + background_color, + // @ts-expect-error Prevent naming conflicts with custom nodes. + height, + // @ts-expect-error Prevent naming conflicts with custom nodes. + text_color, + // @ts-expect-error Prevent naming conflicts with custom nodes. + secondary_text_color, + // @ts-expect-error Prevent naming conflicts with custom nodes. + disabledTextColor, + // @ts-expect-error Prevent naming conflicts with custom nodes. + displayName, + // @ts-expect-error Prevent naming conflicts with custom nodes. + displayValue, + // @ts-expect-error Prevent naming conflicts with custom nodes. + labelBaseline, + promoted, + linkedWidgets, + ...safeValues + } = widget + + Object.assign(this, safeValues) + } + + get outline_color() { + if (this.promoted) return LiteGraph.WIDGET_PROMOTED_OUTLINE_COLOR + return this.advanced + ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR + : LiteGraph.WIDGET_OUTLINE_COLOR + } + + get background_color() { + return LiteGraph.WIDGET_BGCOLOR + } + + get height() { + return LiteGraph.NODE_WIDGET_HEIGHT + } + + get text_color() { + return LiteGraph.WIDGET_TEXT_COLOR + } + + get secondary_text_color() { + return LiteGraph.WIDGET_SECONDARY_TEXT_COLOR + } + + get disabledTextColor() { + return LiteGraph.WIDGET_DISABLED_TEXT_COLOR + } + + get displayName() { + return this.label || this.name + } + + // TODO: Resolve this workaround. Ref: https://github.com/Comfy-Org/litegraph.js/issues/1022 + get _displayValue(): string { + return this.computedDisabled ? '' : String(this.value) + } + + get labelBaseline() { + return this.y + this.height * 0.7 + } + + /** + * Draws the widget + * @param ctx The canvas context + * @param options The options for drawing the widget + * @remarks Not naming this `draw` as `draw` conflicts with the `draw` method in + * custom widgets. + */ + abstract drawWidget( + ctx: CanvasRenderingContext2D, + options: DrawWidgetOptions + ): void + + /** + * Draws the standard widget shape - elongated capsule. The path of the widget shape is not + * cleared, and may be used for further drawing. + * @param ctx The canvas context + * @param options The options for drawing the widget + * @remarks Leaves {@link ctx} dirty. + */ + protected drawWidgetShape( + ctx: CanvasRenderingContext2D, + { width, showText }: DrawWidgetOptions + ): void { + const { height, y } = this + const { margin } = BaseWidget + + ctx.textAlign = 'left' + ctx.strokeStyle = this.outline_color + ctx.fillStyle = this.background_color + ctx.beginPath() + + if (showText) { + ctx.roundRect(margin, y, width - margin * 2, height, [height * 0.5]) + } else { + ctx.rect(margin, y, width - margin * 2, height) + } + ctx.fill() + if (showText && !this.computedDisabled) ctx.stroke() + } + + /** + * Draws a placeholder for widgets that only have a Vue implementation. + * @param ctx The canvas context + * @param options The options for drawing the widget + * @param label The label to display (e.g., "ImageCrop", "BoundingBox") + */ + protected drawVueOnlyWarning( + ctx: CanvasRenderingContext2D, + { width }: DrawWidgetOptions, + label: string + ): void { + const { y, height } = this + + ctx.save() + + ctx.fillStyle = this.background_color + ctx.fillRect(15, y, width - 30, height) + + ctx.strokeStyle = this.outline_color + ctx.strokeRect(15, y, width - 30, height) + + ctx.fillStyle = this.text_color + ctx.font = '11px monospace' + ctx.textAlign = 'center' + ctx.textBaseline = 'middle' + + ctx.fillText( + `${label}: ${t('widgets.node2only')}`, + width / 2, + y + height / 2 + ) + + ctx.restore() + } + + /** + * A shared routine for drawing a label and value as text, truncated + * if they exceed the available width. + */ + protected drawTruncatingText({ + ctx, + width, + leftPadding = 5, + rightPadding = 20 + }: DrawTruncatingTextOptions): void { + const { height, y } = this + const { margin } = BaseWidget + + // Measure label and value + const { displayName, _displayValue } = this + const labelWidth = ctx.measureText(displayName).width + const valueWidth = ctx.measureText(_displayValue).width + + const gap = BaseWidget.labelValueGap + const x = margin * 2 + leftPadding + + const totalWidth = width - x - 2 * margin - rightPadding + const requiredWidth = labelWidth + gap + valueWidth + + const area = new Rectangle(x, y, totalWidth, height * 0.7) + + ctx.fillStyle = this.secondary_text_color + + if (requiredWidth <= totalWidth) { + // Draw label & value normally + drawTextInArea({ ctx, text: displayName, area, align: 'left' }) + } else if (LiteGraph.truncateWidgetTextEvenly) { + // Label + value will not fit - scale evenly to fit + const scale = (totalWidth - gap) / (requiredWidth - gap) + area.width = labelWidth * scale + + drawTextInArea({ ctx, text: displayName, area, align: 'left' }) + + // Move the area to the right to render the value + area.right = x + totalWidth + area.setWidthRightAnchored(valueWidth * scale) + } else if (LiteGraph.truncateWidgetValuesFirst) { + // Label + value will not fit - use legacy scaling of value first + const cappedLabelWidth = Math.min(labelWidth, totalWidth) + + area.width = cappedLabelWidth + drawTextInArea({ ctx, text: displayName, area, align: 'left' }) + + area.right = x + totalWidth + area.setWidthRightAnchored( + Math.max(totalWidth - gap - cappedLabelWidth, 0) + ) + } else { + // Label + value will not fit - scale label first + const cappedValueWidth = Math.min(valueWidth, totalWidth) + + area.width = Math.max(totalWidth - gap - cappedValueWidth, 0) + drawTextInArea({ ctx, text: displayName, area, align: 'left' }) + + area.right = x + totalWidth + area.setWidthRightAnchored(cappedValueWidth) + } + ctx.fillStyle = this.text_color + drawTextInArea({ ctx, text: _displayValue, area, align: 'right' }) + } + + /** + * Handles the click event for the widget + * @param options The options for handling the click event + */ + abstract onClick(options: WidgetEventOptions): void + + /** + * Handles the drag event for the widget + * @param options The options for handling the drag event + */ + onDrag?(options: WidgetEventOptions): void + + /** + * Sets the value of the widget + * @param value The value to set + * @param options The options for setting the value + */ + setValue( + value: TWidget['value'], + { e, node, canvas }: WidgetEventOptions + ): void { + const oldValue = this.value + if (value === this.value) return + + const v = this.type === 'number' ? Number(value) : value + this.value = v + if ( + this.options?.property && + node.properties[this.options.property] !== undefined + ) { + node.setProperty(this.options.property, v) + } + const pos = canvas.graph_mouse + this.callback?.(this.value, canvas, node, pos, e) + + node.onWidgetChanged?.(this.name ?? '', v, oldValue, this) + if (node.graph) node.graph._version++ + } + + /** + * Clones the widget. + * @param node The node that will own the cloned widget. + * @returns A new widget with the same properties as the original + * @remarks Subclasses with custom constructors must override this method. + * + * Correctly and safely typing this is currently not possible (practical?) in TypeScript 5.8. + */ + createCopyForNode(node: LGraphNode): this { + // @ts-expect-error - Constructor type casting for widget cloning + const cloned: this = new (this.constructor as typeof this)(this, node) + cloned.value = this.value + return cloned + } +} diff --git a/docs/hel-892/sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts b/docs/hel-892/sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts new file mode 100644 index 00000000..78f9d0c9 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts @@ -0,0 +1,126 @@ +import { useNodeImage, useNodeVideo } from '@/composables/node/useNodeImage' +import { useNodeImageUpload } from '@/composables/node/useNodeImageUpload' +import { useValueTransform } from '@/composables/useValueTransform' +import { t } from '@/i18n' +import type { LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { IComboWidget } from '@/lib/litegraph/src/types/widgets' +import type { ResultItem, ResultItemType } from '@/schemas/apiSchema' +import type { InputSpec } from '@/schemas/nodeDefSchema' +import type { ComfyWidgetConstructor } from '@/scripts/widgets' +import { useNodeOutputStore } from '@/stores/imagePreviewStore' +import { isImageUploadInput } from '@/types/nodeDefAugmentation' +import { createAnnotatedPath } from '@/utils/createAnnotatedPath' +import { addToComboValues } from '@/utils/litegraphUtil' + +const ACCEPTED_IMAGE_TYPES = 'image/png,image/jpeg,image/webp' +const ACCEPTED_VIDEO_TYPES = 'video/webm,video/mp4' + +type InternalFile = string | ResultItem +type InternalValue = InternalFile | InternalFile[] +type ExposedValue = string | string[] + +const isImageFile = (file: File) => file.type.startsWith('image/') +const isVideoFile = (file: File) => file.type.startsWith('video/') + +const findFileComboWidget = (node: LGraphNode, inputName: string) => + node.widgets!.find((w) => w.name === inputName) as IComboWidget & { + value: ExposedValue + } + +export const useImageUploadWidget = () => { + const widgetConstructor: ComfyWidgetConstructor = ( + node: LGraphNode, + inputName: string, + inputData: InputSpec + ) => { + if (!isImageUploadInput(inputData)) { + throw new Error( + 'Image upload widget requires imageInputName augmentation' + ) + } + + const inputOptions = inputData[1] + const { imageInputName, allow_batch, image_folder = 'input' } = inputOptions + const folder: ResultItemType | undefined = image_folder + const nodeOutputStore = useNodeOutputStore() + + const isAnimated = !!inputOptions.animated_image_upload + const isVideo = !!inputOptions.video_upload + const accept = isVideo ? ACCEPTED_VIDEO_TYPES : ACCEPTED_IMAGE_TYPES + const { showPreview } = isVideo ? useNodeVideo(node) : useNodeImage(node) + + const fileFilter = isVideo ? isVideoFile : isImageFile + const fileComboWidget = findFileComboWidget(node, imageInputName) + const initialFile = `${fileComboWidget.value}` + const formatPath = (value: InternalFile) => + createAnnotatedPath(value, { rootFolder: image_folder }) + + const transform = (internalValue: InternalValue): ExposedValue => { + if (!internalValue) return initialFile + if (Array.isArray(internalValue)) + return allow_batch + ? internalValue.map(formatPath) + : formatPath(internalValue[0]) + return formatPath(internalValue) + } + + Object.defineProperty( + fileComboWidget, + 'value', + useValueTransform(transform, initialFile) + ) + + // Setup file upload handling + const { openFileSelection } = useNodeImageUpload(node, { + allow_batch, + fileFilter, + accept, + folder, + onUploadComplete: (output) => { + output.forEach((path) => addToComboValues(fileComboWidget, path)) + + // Create a NEW array to ensure Vue reactivity detects the change + const newValue = allow_batch ? [...output] : output[0] + + // @ts-expect-error litegraph combo value type does not support arrays yet + fileComboWidget.value = newValue + fileComboWidget.callback?.(newValue) + } + }) + + // Create the button widget for selecting the files + const uploadWidget = node.addWidget( + 'button', + inputName, + 'image', + () => openFileSelection(), + { + serialize: false, + canvasOnly: true + } + ) + uploadWidget.label = t('g.choose_file_to_upload') + + // Add our own callback to the combo widget to render an image when it changes + fileComboWidget.callback = function () { + nodeOutputStore.setNodeOutputs(node, fileComboWidget.value, { + isAnimated + }) + node.graph?.setDirtyCanvas(true) + } + + // On load if we have a value then render the image + // The value isn't set immediately so we need to wait a moment + // No change callbacks seem to be fired on initial setting of the value + requestAnimationFrame(() => { + nodeOutputStore.setNodeOutputs(node, fileComboWidget.value, { + isAnimated + }) + showPreview({ block: false }) + }) + + return { widget: uploadWidget } + } + + return widgetConstructor +} diff --git a/docs/hel-892/sdpose-reference/frontend__src__utils__executionUtil.ts b/docs/hel-892/sdpose-reference/frontend__src__utils__executionUtil.ts new file mode 100644 index 00000000..ea3e4e53 --- /dev/null +++ b/docs/hel-892/sdpose-reference/frontend__src__utils__executionUtil.ts @@ -0,0 +1,157 @@ +import type { + ExecutableLGraphNode, + ExecutionId, + LGraph +} from '@/lib/litegraph/src/litegraph' +import { + ExecutableNodeDTO, + LGraphEventMode +} from '@/lib/litegraph/src/litegraph' +import type { + ComfyApiWorkflow, + ComfyWorkflowJSON +} from '@/platform/workflow/validation/schemas/workflowSchema' + +import { ExecutableGroupNodeDTO, isGroupNode } from './executableGroupNodeDto' +import { compressWidgetInputSlots } from './litegraphUtil' + +/** + * Converts the current graph workflow for sending to the API. + * @note Node widgets are updated before serialization to prepare queueing. + * + * @param graph The graph to convert. + * @param options The options for the conversion. + * - `sortNodes`: Whether to sort the nodes by execution order. + * @returns The workflow and node links + */ +export const graphToPrompt = async ( + graph: LGraph, + options: { sortNodes?: boolean } = {} +): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => { + const { sortNodes = false } = options + + for (const node of graph.computeExecutionOrder(false)) { + const innerNodes = node.getInnerNodes + ? node.getInnerNodes(new Map()) + : [node] + for (const innerNode of innerNodes) { + if (innerNode.isVirtualNode) { + innerNode.applyToGraph?.() + } + } + } + + const workflow = graph.serialize({ sortNodes }) + + // Remove localized_name from the workflow + for (const node of workflow.nodes) { + for (const slot of node.inputs ?? []) { + delete slot.localized_name + } + for (const slot of node.outputs ?? []) { + delete slot.localized_name + } + } + + compressWidgetInputSlots(workflow) + workflow.extra ??= {} + workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__ + + const nodeDtoMap = new Map() + for (const node of graph.computeExecutionOrder(false)) { + const dto: ExecutableLGraphNode = isGroupNode(node) + ? new ExecutableGroupNodeDTO(node, [], nodeDtoMap) + : new ExecutableNodeDTO(node, [], nodeDtoMap) + + nodeDtoMap.set(dto.id, dto) + + if ( + node.mode === LGraphEventMode.NEVER || + node.mode === LGraphEventMode.BYPASS + ) { + continue + } + + for (const innerNode of dto.getInnerNodes()) { + nodeDtoMap.set(innerNode.id, innerNode) + } + } + + const output: ComfyApiWorkflow = {} + // Process nodes in order of execution + for (const node of nodeDtoMap.values()) { + // Don't serialize muted nodes + if ( + node.isVirtualNode || + node.mode === LGraphEventMode.NEVER || + node.mode === LGraphEventMode.BYPASS + ) { + continue + } + + const inputs: ComfyApiWorkflow[string]['inputs'] = {} + const { widgets } = node + + // Store all widget values + if (widgets) { + for (const [i, widget] of widgets.entries()) { + if (!widget.name || widget.options?.serialize === false) continue + + const widgetValue = widget.serializeValue + ? await widget.serializeValue(node, i) + : widget.value + // By default, Array values are reserved to represent node connections. + // We need to wrap the array as an object to avoid the misinterpretation + // of the array as a node connection. + // The backend automatically unwraps the object to an array during + // execution. + inputs[widget.name] = Array.isArray(widgetValue) + ? { + __value__: widgetValue + } + : widgetValue + } + } + + // Store all node links + for (const [i, input] of node.inputs.entries()) { + const resolvedInput = node.resolveInput(i) + if (!resolvedInput) continue + + // Resolved to an actual widget value rather than a node connection + if (resolvedInput.widgetInfo) { + const { value } = resolvedInput.widgetInfo + inputs[input.name] = Array.isArray(value) ? { __value__: value } : value + continue + } + + inputs[input.name] = [ + String(resolvedInput.origin_id), + // @ts-expect-error link.origin_slot is already number. + parseInt(resolvedInput.origin_slot) + ] + } + + output[String(node.id)] = { + inputs, + // TODO(huchenlei): Filter out all nodes that cannot be mapped to a + // comfyClass. + class_type: node.comfyClass!, + // Ignored by the backend. + _meta: { + title: node.title + } + } + } + + // Remove inputs connected to removed nodes + for (const { inputs } of Object.values(output)) { + for (const [i, input] of Object.entries(inputs)) { + if (Array.isArray(input) && input.length === 2 && !output[input[0]]) { + delete inputs[i] + } + } + } + + return { workflow: workflow as ComfyWorkflowJSON, output } +} diff --git a/docs/hel-892/sdpose-reference/identity.json b/docs/hel-892/sdpose-reference/identity.json new file mode 100644 index 00000000..6c7ae501 --- /dev/null +++ b/docs/hel-892/sdpose-reference/identity.json @@ -0,0 +1,35 @@ +[ + { + "repo": "core0150", + "upstream": "ComfyUI", + "tag": "v0.15.0", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.15.0", + "tag_sha256": "f3c7ba4af6144b4be77d359a64191999032e106b58800208683051f1e703f59d", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "commit_record_sha256": "e2ba46fdda05c083b72f05a40d4f62d034cc772a0579e3f03a74152988244d3a", + "installed_or_executed": false + }, + { + "repo": "core0151", + "upstream": "ComfyUI", + "tag": "v0.15.1", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.15.1", + "tag_sha256": "9a8b752179bf5aac26a5f9c79e9cfc190042019390009c5761e8c9d1b13e282c", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "commit_record_sha256": "df64c3da930aebd32514b259f7b610bdd5a0cde3ebec46e2481e4e27d5f0ce4b", + "installed_or_executed": false + }, + { + "repo": "frontend", + "upstream": "ComfyUI_frontend", + "tag": "v1.39.19", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "tag_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/ref/tags/v1.39.19", + "tag_sha256": "dbdd4d0ae2a418a58198a20be9606992af165501135c34b2c459b11fdb8641a1", + "commit_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "commit_record_sha256": "ed59717c9b6ea008d633fad905ecb4e01d02b34094b2d4c781b930b2bd5837db", + "installed_or_executed": false + } +] diff --git a/docs/hel-892/sdpose-reference/sources.json b/docs/hel-892/sdpose-reference/sources.json new file mode 100644 index 00000000..2184ed0e --- /dev/null +++ b/docs/hel-892/sdpose-reference/sources.json @@ -0,0 +1,175 @@ +{ + "sources": [ + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "LICENSE", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/LICENSE", + "local_file": "core0150__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "nodes.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/nodes.py", + "local_file": "core0150__nodes.py", + "sha256": "e578644f44b86b4952e01385e8d42f1f30808e0f2488335933c16e22a9b64ce4" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_post_processing.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_extras/nodes_post_processing.py", + "local_file": "core0150__comfy_extras__nodes_post_processing.py", + "sha256": "220008cee54ccd54ad7d31a8048c4e36a69bea7c234ec8cf144e35a477b8a9c4" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_io.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy_api/latest/_io.py", + "local_file": "core0150__comfy_api__latest___io.py", + "sha256": "babe511f46396750db3cf322a07c790b09c72e498876b8012a24ced1d2bf0c5c" + }, + { + "id": "core0150", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy/utils.py", + "commit": "b874bd2b8c324d58cfc37bff0754dd16815a8f3c", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/b874bd2b8c324d58cfc37bff0754dd16815a8f3c/comfy/utils.py", + "local_file": "core0150__comfy__utils.py", + "sha256": "feb283ab6ccd5f4807cb2b3f3893a274e2c3194f8ed9df6da7f143ffa3768286" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "LICENSE", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/LICENSE", + "local_file": "core0151__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_extras/nodes_video.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_extras/nodes_video.py", + "local_file": "core0151__comfy_extras__nodes_video.py", + "sha256": "1dc7e77804692e66446b4b70e1fd83b99dbaa197d1a25d621ea6f1a139dbc575" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_util/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/video_types.py", + "local_file": "core0151__comfy_api__latest___util__video_types.py", + "sha256": "b20939f97928f634bedbb39dd003c8b04e560118807cda57dbb5ed3b8ac71a02" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_util/__init__.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_util/__init__.py", + "local_file": "core0151__comfy_api__latest___util____init__.py", + "sha256": "a00432018a3aa989a98d94470c657bfef2a89031fe1e844c19a616636291ba0a" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "folder_paths.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/folder_paths.py", + "local_file": "core0151__folder_paths.py", + "sha256": "da62dbe3cc99c8d2bce4dd1df01c5a0ca149f9ed8522cc477e661629052ce112" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "LICENSE", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/LICENSE", + "local_file": "frontend__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/lib/litegraph/src/LGraphNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "frontend__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "24e48e7d8886a968cd825042bd4d5eb075bc24731dcca266ebb8f8ef1a75f033" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/utils/executionUtil.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/utils/executionUtil.ts", + "local_file": "frontend__src__utils__executionUtil.ts", + "sha256": "b32c235e5bdb498c4ab2f7b65a70be4cd211d550f8fcfa0aceb55f2425c67cd6" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/core/graph/widgets/dynamicWidgets.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/core/graph/widgets/dynamicWidgets.ts", + "local_file": "frontend__src__core__graph__widgets__dynamicWidgets.ts", + "sha256": "f7dbc6697582194ffdeef1010fd7510a444e563f43ebc85920be096a5dffd53e" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts", + "local_file": "frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts", + "sha256": "77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/extensions/core/noteNode.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/extensions/core/noteNode.ts", + "local_file": "frontend__src__extensions__core__noteNode.ts", + "sha256": "1014f719e3d67d9c5183a5e8631d4c2d6581dfe67083f32eb23774ec3074bef2" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_input_impl/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input_impl/video_types.py", + "local_file": "core0151__comfy_api__latest___input_impl__video_types.py", + "sha256": "df7ee740f063fd4e2180551fba3b9ab2dcb335042442c49f5d6fef0b277cf6a5" + }, + { + "id": "core0151", + "repo": "Comfy-Org/ComfyUI", + "file": "comfy_api/latest/_input/video_types.py", + "commit": "3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f/comfy_api/latest/_input/video_types.py", + "local_file": "core0151__comfy_api__latest___input__video_types.py", + "sha256": "6a4cdb3085ed8a4289e63168536e9a530c95aad94c7e2de1eddf8738af11f5a7" + }, + { + "id": "frontend", + "repo": "Comfy-Org/ComfyUI_frontend", + "file": "src/lib/litegraph/src/widgets/BaseWidget.ts", + "commit": "d91c283b7b758787b4d29126c1a9ac39dc14d6a7", + "url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/d91c283b7b758787b4d29126c1a9ac39dc14d6a7/src/lib/litegraph/src/widgets/BaseWidget.ts", + "local_file": "frontend__src__lib__litegraph__src__widgets__BaseWidget.ts", + "sha256": "0835d3d10d5bc8fcdd86bb1a35e4cf53a82681d6087f9da2a900882bf0ddac3f" + } + ] +} diff --git a/e2e/run-sdpose-document.py b/e2e/run-sdpose-document.py new file mode 100644 index 00000000..b3d34910 --- /dev/null +++ b/e2e/run-sdpose-document.py @@ -0,0 +1,78 @@ +"""Foreground local browser check; stop every owned service before returning.""" + +from __future__ import annotations + +import os +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / ".local-evidence/sdpose-document/browser" + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + # Refuse to reuse another operator's service or port. + import socket + + for port in (8247, 5173): + with socket.socket() as sock: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", port)) + processes = [] + logs = [] + try: + commands = [ + ([sys.executable, str(ROOT / "e2e/workflow-document-server.py")], ROOT), + ( + ["node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1"], + ROOT / "calliope-web", + ), + ] + for i, (command, cwd) in enumerate(commands): + log = (OUT / f"service-{i}.log").open("w") + logs.append(log) + processes.append( + subprocess.Popen(command, cwd=cwd, stdout=log, stderr=log, start_new_session=True) + ) + for url in ( + "http://127.0.0.1:8247/api/workflows", + "http://127.0.0.1:5173/connections", + ): + deadline = time.monotonic() + 30 + while True: + if any(p.poll() is not None for p in processes): + raise RuntimeError("Local service exited; inspect service logs") + try: + with urllib.request.urlopen(url, timeout=1) as response: + if response.status == 200: + break + except (urllib.error.URLError, TimeoutError): + pass + if time.monotonic() > deadline: + raise TimeoutError(url) + time.sleep(0.2) + names = ["sdpose"] + for name in names: + subprocess.run(["node", f"e2e/{name}-document.mjs"], cwd=ROOT, check=True) + finally: + for p in processes: + if p.poll() is None: + os.killpg(p.pid, signal.SIGTERM) + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGKILL) + p.wait(timeout=5) + for log in logs: + log.close() + print("All owned browser services stopped.") + + +if __name__ == "__main__": + main() diff --git a/e2e/sdpose-document.mjs b/e2e/sdpose-document.mjs new file mode 100644 index 00000000..82309ed9 --- /dev/null +++ b/e2e/sdpose-document.mjs @@ -0,0 +1,97 @@ +// Local GET-only SDPose 18 positions and fifteen source-bound summaries. +import fs from 'node:fs'; +import assert from 'node:assert/strict'; +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const out='.local-evidence/sdpose-document/browser';fs.mkdirSync(out,{recursive:true}); +const checks=[],requests=[],errors=[],blockedFonts=[],assertionGroups={};let group='aggregate'; +function check(condition,label){assert.ok(condition,label);checks.push(label);assertionGroups[group]=(assertionGroups[group]||0)+1;console.log('PASS '+label);} +const browser=await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE}); +try { + const page=await browser.newPage({viewport:{width:1440,height:1000}}); + await page.route('**/*',route=>{ + const u=new URL(route.request().url()); + if(u.hostname==='fonts.googleapis.com'){blockedFonts.push(String(u));return route.fulfill({contentType:'text/css',body:''});} + if(u.hostname!=='127.0.0.1'||u.pathname==='/api/view'){errors.push('Forbidden request '+u);return route.abort();} + return route.continue(); + }); + page.on('request',r=>{if(r.url().includes('/api/'))requests.push({method:r.method(),url:r.url()});}); + page.on('pageerror',e=>errors.push(e.message)); + requests.push({method:'GET',url:'http://127.0.0.1:8247/api/workflows'}); + const records=await(await fetch('http://127.0.0.1:8247/api/workflows')).json(); + const names=['sdpose_视频人物姿势骨架提取','gemma4_提示词反推(图像视频音频)','图像合并成四宫格','图像分割-多宫格分割','Qwen_image2.1_图像编辑_背景移除','Qwen_image2.1_图像编辑_提示词增强','Qwen_image2.1_文生图_提示词增强','ControlNet_aux_常用样例','Qwen3-ASR-语音转文字','Qwen3-ASR-Subtitle语音转字幕','Minimax-H3提示词增强','音频转MP3格式','音频人声分离','视频-音频分离','图像嵌入文字描述']; + const details=[]; + for(const name of names){const r=records.find(r=>r.name===name);assert.ok(r);const url=`http://127.0.0.1:8247/api/workflows/${r.id}`;requests.push({method:'GET',url});details.push(await(await fetch(url)).json());} + check(details.length===15&&details.reduce((n,d)=>n+d.doc_json.fixed_version.fields.length,0)===394,'15图394保存位置'); + check(details.reduce((n,d)=>n+(d.doc_json.source_notes?.length||0),0)===14,'15图14源注释'); + await page.goto('http://127.0.0.1:5173/connections',{waitUntil:'networkidle'}); + const dialog=page.getByRole('dialog',{name:'工作流说明'}); + const fixedCard=dialog.locator('.card').filter({has:page.getByText('固定版本参数说明',{exact:true})}); + async function begin(name){const row=page.locator('.wf-row').filter({has:page.locator('.wf-name').filter({hasText:name})}).first();const button=row.getByRole('button',{name:'说明',exact:true});await button.focus();await page.keyboard.press('Enter');return button;} + async function loaded(){await dialog.getByText('用途与来源',{exact:true}).waitFor();await dialog.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));} + for(const width of [1440,390]){ + await page.setViewportSize({width,height:width===390?844:1000}); + for(const d of details){ + group=d===details[0]?'new_sdpose':'old_fourteen';const b=d.doc_json.fixed_version,button=await begin(d.name);await loaded(); + const overview=dialog.locator('.card').filter({has:page.getByText('用途与来源',{exact:true})}); + check((await overview.innerText()).includes(b.user_overview),`${width} ${d.name}默认中文用途`); + check(!(await dialog.getByText('源图与审校记录',{exact:true}).locator('..').evaluate(el=>el.open)),`${width} ${d.name}源审校默认折叠`); + check(!(await dialog.getByText('核对范围与来源依据',{exact:true}).locator('..').evaluate(el=>el.open)),`${width} ${d.name}技术范围默认折叠`); + const visible=await fixedCard.innerText(); + check(!visible.includes('执行标量')&&!visible.includes('widgetId')&&!visible.includes(b.source_sha256)&&!visible.includes('UUID'),`${width} ${d.name}默认无执行计数/实现标识`); + check(visible.includes('依据固定版本整理,目标环境与实际效果未核对。'),`${width} ${d.name}默认依据限制可见`); + for(const t of ['说明未定稿','未验证实跑','未检查'])check((await dialog.innerText()).includes(t),`${width} ${d.name} ${t}`); + check(!d.is_enabled&&!d.doc_completed_at&&!d.exec_verified_at,`${width} ${d.name}停用/时间戳空`); + check(await fixedCard.locator('summary').filter({hasText:/^节点 [\d:]+ · /}).count()===b.fields.length,`${width} ${d.name}参数全保留`); + check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width} ${d.name}默认无溢出`); + await dialog.locator('.drawer-body').evaluate(el=>el.scrollTop=0); + await page.screenshot({path:`${out}/${width}-${d.id}-default.png`}); + await dialog.getByText('源图与审校记录',{exact:true}).click(); + check((await overview.innerText()).includes(d.doc_json.purpose)&&(await overview.innerText()).includes(d.source_repo_path),`${width} ${d.name}原用途/源路径展开保留`); + await dialog.getByText('核对范围与来源依据',{exact:true}).click(); + const flowText=await fixedCard.innerText(); + for(const line of b.flow)check(flowText.includes(line),`${width} ${d.name}展开流程 ${b.flow.indexOf(line)}`); + await dialog.getByText('版本、源图与连线依据',{exact:true}).click(); + check((await fixedCard.innerText()).includes(b.source_sha256)&&b.versions.every(v=>(v&&true)),`${width} ${d.name}原件摘要可展开`); + const versionText=await fixedCard.innerText(); + for(const v of b.versions)check(versionText.includes(v),`${width} ${d.name}版本 ${b.versions.indexOf(v)}`); + if(details.indexOf(d)<1){ + for(const f of b.fields){ + const summary=fixedCard.locator(`details[data-fixed-field="${f.pointer}"] > summary`);await summary.focus();await page.keyboard.press('Enter');const box=summary.locator('..'); + check(await box.evaluate(el=>el.open),`${width} ${f.node_id}.${f.field}键盘展开`); + let text=await box.innerText();check(text.includes(f.effect)&&text.includes(f.limits)&&text.includes(f.schema_default)&&text.includes(f.execution_note)&&text.includes(f.unit),`${width} ${f.node_id}.${f.field}用途/单位/范围/来源条件`); + check(await box.locator(':scope > pre').textContent()===(typeof f.value==='string'?f.value:JSON.stringify(f.value,null,2)),`${width} ${f.node_id}.${f.field}精确保留现值`); + check(!text.includes(f.pointer),`${width} ${f.node_id}.${f.field}指针默认折叠`); + await box.getByText('来源依据',{exact:true}).click();text=await box.innerText(); + check(text.includes(f.pointer)&&text.includes(f.class_type)&&text.includes(f.json_type)&&f.evidence.every(i=>{const e=b.sources[i];return text.includes(e.commit)&&text.includes(e.sha256)&&text.includes(e.lines.join('~'));}),`${width} ${f.node_id}.${f.field}精确源码/类型/指针`); + check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width} ${f.node_id}.${f.field}展开无溢出`); + if(['fps','resize_type.longer_size','score_threshold','batch_size','filename_prefix'].includes(f.field))await page.screenshot({path:`${out}/${width}-${f.field}.png`}); + await summary.click(); + } + for(const n of b.comments){const summary=dialog.getByText(`节点 ${n.node_id}`,{exact:true});await summary.click();const expected=d.doc_json.source_notes.find(x=>String(x.node_id)===n.node_id);check(await summary.locator('..').locator('pre').textContent()===JSON.stringify(expected.content,null,2),`${width}注释${n.node_id}全文`);check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}注释${n.node_id}无溢出`);await summary.click();} + await dialog.getByRole('button',{name:'关闭',exact:true}).focus();await page.keyboard.press('Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}Tab焦点保留`);await page.keyboard.press('Shift+Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}ShiftTab焦点保留`); + } + await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width} ${d.name}关闭归还焦点`); + } + } + group='shared_regressions'; + for(const name of ['旧工作流回退(隔离测试夹具)','空说明回退(隔离测试夹具)']){await begin(name);await loaded();check((await dialog.innerText()).includes('隔离库旧条目回退测试'),'旧/空说明回退 '+name);await page.keyboard.press('Escape');} + // Missing summary and mismatched bindings are tested with local GET fixtures, without writes. + for(const variant of ['missing-overview','mismatched','html-summary']){ + const d=structuredClone(details[0]); + if(variant==='missing-overview')delete d.doc_json.fixed_version.user_overview; + if(variant==='mismatched')d.doc_json.fixed_version={matched:false,notice:'固定版本参数说明待核对:源文件、声明版本或说明依据未匹配,未采用旧定义。'}; + if(variant==='html-summary')d.doc_json.fixed_version.user_overview='仅纯文本'; + await page.route(`**/api/workflows/${d.id}`,route=>route.fulfill({json:d}));await begin(d.name);await loaded(); + if(variant==='missing-overview')check((await dialog.innerText()).includes('这张图的用途和操作重点可在下方使用步骤中查看;目标环境与实际效果仍待核对。'),'缺摘要自然中文回退'); + if(variant==='mismatched')check((await dialog.innerText()).includes(d.doc_json.fixed_version.notice)&&!await dialog.getByText('核对范围与来源依据',{exact:true}).count(),'错绑定提示明确且不展示旧字段'); + if(variant==='html-summary')check((await dialog.innerText()).includes(d.doc_json.fixed_version.user_overview)&&await dialog.locator('img').count()===0,'摘要HTML仅纯文本不创建图像或请求'); + check(!(await dialog.innerText()).includes('undefined'),'回退不暴露undefined');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${d.id}`); + } + let release,entered,delivered;const hold=new Promise(r=>release=r),intercept=new Promise(r=>entered=r),done=new Promise(r=>delivered=r); + await page.route(`**/api/workflows/${details[0].id}`,async route=>{entered();await hold;await route.fulfill({json:details[0]});delivered();}); + await begin(details[0].name);await intercept;await page.keyboard.press('Escape');await begin(details[1].name);await loaded();release();await done; + check((await dialog.innerText()).includes(details[1].doc_json.fixed_version.user_overview)&&await fixedCard.locator('summary').filter({hasText:/^节点 [\d:]+ · /}).count()===25,'迟到SDPose响应不覆盖Gemma图摘要/25字段');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${details[0].id}`); + await page.route(`**/api/workflows/${details[0].id}`,route=>route.fulfill({status:500,json:{detail:'隔离失败夹具'}}));await begin(details[0].name);await dialog.getByRole('alert').waitFor({timeout:20000});check(await dialog.getByRole('button',{name:'重试',exact:true}).isVisible(),'GET失败显示重试');check(await dialog.getByText('用途与来源',{exact:true}).count()===0,'读取失败隐藏旧摘要');await page.unroute(`**/api/workflows/${details[0].id}`);await dialog.getByRole('button',{name:'重试',exact:true}).click();await loaded();check((await dialog.innerText()).includes(details[0].doc_json.fixed_version.user_overview),'重试恢复摘要');await page.keyboard.press('Escape'); + check(errors.length===0,'无脚本错误或禁止请求 '+JSON.stringify(errors));check(requests.every(r=>r.method==='GET'&&new URL(r.url).hostname==='127.0.0.1'&&!r.url.includes('/api/view')),'全程本地GET无写/生成/目标/历史预览请求'); + fs.writeFileSync(`${out}/browser-results.json`,JSON.stringify({assertion_count:checks.length,assertionGroups,checks,requests,errors,blockedFonts,viewports:[1440,390]},null,2)); +} finally {await browser.close();}